Server-side integration with PHP and cURL
All PHP examples use cURL which is included in most PHP installations. Make sure you have:
PHP 7.4+ with cURL extension enabled
API Key from Connect2Print admin panel
Store your API key in environment variables or a .env file, never hardcode it in your source code.
Fetch your account information to verify authentication:
<?php
// Set your API key
$apiKey = 'c2p_live_your_api_key_here';
$baseUrl = 'https://app1.connect2print.com/api/v1';
// Initialize cURL
$ch = curl_init("{$baseUrl}/account");
// Set cURL options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer {$apiKey}",
"Accept: application/json"
]);
// Execute request
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// Parse response
if ($httpCode === 200) {
$data = json_decode($response, true);
if ($data['success']) {
echo "Account: " . $data['data']['company_name'] . "\n";
echo "Email: " . $data['data']['email'] . "\n";
}
} else {
echo "Error: HTTP {$httpCode}\n";
echo $response . "\n";
}
?>
Fetch all orders using pagination:
<?php
$apiKey = 'c2p_live_your_api_key_here';
$baseUrl = 'https://app1.connect2print.com/api/v1';
function makeRequest($url, $apiKey) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer {$apiKey}",
"Accept: application/json"
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200) {
throw new Exception("HTTP Error {$httpCode}: {$response}");
}
return json_decode($response, true);
}
// Fetch all orders
$page = 1;
$perPage = 50;
$allOrders = [];
do {
$url = "{$baseUrl}/orders?page={$page}&per_page={$perPage}";
$data = makeRequest($url, $apiKey);
if (!$data['success']) {
throw new Exception("API Error: " . $data['error']['message']);
}
// Add orders from this page
$allOrders = array_merge($allOrders, $data['data']);
// Check if there are more pages
$hasMore = $data['pagination']['has_more'];
$page++;
echo "Fetched page {$page}, total orders: " . count($allOrders) . "\n";
// Rate limit protection
if ($hasMore) {
usleep(100000); // 100ms delay
}
} while ($hasMore);
echo "Total orders fetched: " . count($allOrders) . "\n";
?>
Create a new customer with validation:
<?php
$apiKey = 'c2p_live_your_api_key_here';
$baseUrl = 'https://app1.connect2print.com/api/v1';
// Customer data
$customerData = [
'email' => 'john.doe@example.com',
'company_name' => 'Acme Corporation',
'contact_name' => 'John Doe',
'phone' => '+45 12 34 56 78',
'billing_address' => [
'street_address' => 'Main Street 123',
'city' => 'Copenhagen',
'postal_code' => '1000',
'country' => 'DK'
]
];
// Initialize cURL
$ch = curl_init("{$baseUrl}/customers");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($customerData));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer {$apiKey}",
"Content-Type: application/json",
"Accept: application/json"
]);
// Execute request
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$data = json_decode($response, true);
if ($httpCode === 201) {
echo "Customer created successfully!\n";
echo "Customer ID: " . $data['data']['id'] . "\n";
echo "Email: " . $data['data']['email'] . "\n";
} elseif ($httpCode === 400) {
echo "Validation error:\n";
if (isset($data['error']['details'])) {
foreach ($data['error']['details'] as $field => $errors) {
echo " {$field}: " . implode(', ', $errors) . "\n";
}
}
} else {
echo "Error: HTTP {$httpCode}\n";
echo $response . "\n";
}
?>
Update an existing order (PATCH request):
<?php
$apiKey = 'c2p_live_your_api_key_here';
$baseUrl = 'https://app1.connect2print.com/api/v1';
$orderId = 123;
// Data to update
$updateData = [
'status' => 'processing',
'internal_notes' => 'Printing started on machine #2'
];
// Initialize cURL
$ch = curl_init("{$baseUrl}/orders/{$orderId}");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PATCH');
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($updateData));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer {$apiKey}",
"Content-Type: application/json",
"Accept: application/json"
]);
// Execute request
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$data = json_decode($response, true);
if ($httpCode === 200) {
echo "Order updated successfully!\n";
echo "New status: " . $data['data']['status'] . "\n";
} elseif ($httpCode === 404) {
echo "Order not found\n";
} else {
echo "Error: HTTP {$httpCode}\n";
echo $response . "\n";
}
?>
Upload a production file (multipart/form-data):
<?php
$apiKey = 'c2p_live_your_api_key_here';
$baseUrl = 'https://app1.connect2print.com/api/v1';
// File to upload
$filePath = '/path/to/your/file.pdf';
if (!file_exists($filePath)) {
die("File not found: {$filePath}\n");
}
// Prepare file data
$cFile = new CURLFile($filePath, 'application/pdf', basename($filePath));
$postData = [
'file' => $cFile,
'related_type' => 'order',
'related_id' => 123
];
// Initialize cURL
$ch = curl_init("{$baseUrl}/files/upload");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer {$apiKey}",
"Accept: application/json"
]);
// Execute request
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$data = json_decode($response, true);
if ($httpCode === 201) {
echo "File uploaded successfully!\n";
echo "File ID: " . $data['data']['id'] . "\n";
echo "Filename: " . $data['data']['filename'] . "\n";
echo "Size: " . number_format($data['data']['file_size'] / 1024, 2) . " KB\n";
} else {
echo "Error: HTTP {$httpCode}\n";
echo $response . "\n";
}
?>
Handle all types of API errors gracefully:
<?php
class Connect2PrintAPI {
private $apiKey;
private $baseUrl;
public function __construct($apiKey) {
$this->apiKey = $apiKey;
$this->baseUrl = 'https://app1.connect2print.com/api/v1';
}
public function request($method, $endpoint, $data = null) {
$url = $this->baseUrl . $endpoint;
$ch = curl_init($url);
$headers = [
"Authorization: Bearer {$this->apiKey}",
"Accept: application/json"
];
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
if ($data !== null) {
$headers[] = "Content-Type: application/json";
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Execute with error handling
$response = curl_exec($ch);
if (curl_errno($ch)) {
$error = curl_error($ch);
curl_close($ch);
throw new Exception("cURL Error: {$error}");
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$data = json_decode($response, true);
// Handle different HTTP status codes
switch ($httpCode) {
case 200:
case 201:
return $data['data'] ?? $data;
case 400:
throw new Exception("Validation Error: " .
$this->formatValidationErrors($data));
case 401:
throw new Exception("Unauthorized: Invalid API key");
case 403:
throw new Exception("Forbidden: Insufficient permissions");
case 404:
throw new Exception("Not Found: Resource doesn't exist");
case 429:
$retryAfter = $data['retry_after'] ?? 60;
throw new Exception("Rate Limit Exceeded. Retry after {$retryAfter}s");
case 500:
case 502:
case 503:
throw new Exception("Server Error ({$httpCode}). Please try again later");
default:
throw new Exception("HTTP Error {$httpCode}: " .
($data['error']['message'] ?? $response));
}
}
private function formatValidationErrors($data) {
if (!isset($data['error']['details'])) {
return $data['error']['message'] ?? 'Unknown error';
}
$errors = [];
foreach ($data['error']['details'] as $field => $messages) {
$errors[] = "{$field}: " . implode(', ', $messages);
}
return implode('; ', $errors);
}
}
// Usage example
try {
$api = new Connect2PrintAPI('c2p_live_your_api_key_here');
// Create a customer
$customer = $api->request('POST', '/customers', [
'email' => 'test@example.com',
'company_name' => 'Test Company'
]);
echo "Customer created: {$customer['id']}\n";
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
// Log the error
error_log("API Error: " . $e->getMessage());
}
?>
Receive and validate webhook notifications:
<?php
// webhook.php - Handle incoming webhooks
// Get the webhook secret from your settings
$webhookSecret = 'your_webhook_secret_here';
// Get the signature from headers
$signature = $_SERVER['HTTP_X_WEBHOOK_SIGNATURE'] ?? '';
if (empty($signature)) {
http_response_code(401);
die('Missing signature');
}
// Get the raw body
$body = file_get_contents('php://input');
// Calculate expected signature
$expectedSignature = hash_hmac('sha256', $body, $webhookSecret);
// Verify signature
if (!hash_equals($signature, $expectedSignature)) {
http_response_code(401);
die('Invalid signature');
}
// Parse the webhook data
$webhook = json_decode($body, true);
if (!$webhook) {
http_response_code(400);
die('Invalid JSON');
}
// Log the webhook (for debugging)
error_log("Webhook received: " . $webhook['event']);
// Handle different webhook events
switch ($webhook['event']) {
case 'order.created':
handleOrderCreated($webhook['data']);
break;
case 'order.completed':
handleOrderCompleted($webhook['data']);
break;
case 'invoice.paid':
handleInvoicePaid($webhook['data']);
break;
case 'shipment.delivered':
handleShipmentDelivered($webhook['data']);
break;
default:
error_log("Unknown webhook event: " . $webhook['event']);
}
// Always return 200 OK to acknowledge receipt
http_response_code(200);
echo json_encode(['success' => true]);
// Handler functions
function handleOrderCreated($order) {
// Send notification email
$to = 'orders@example.com';
$subject = "New Order #{$order['id']}";
$message = "New order from {$order['customer']['company_name']}\n";
$message .= "Total: {$order['total']} {$order['currency']}\n";
mail($to, $subject, $message);
}
function handleOrderCompleted($order) {
// Update your local database
// Trigger fulfillment process
error_log("Order {$order['id']} completed");
}
function handleInvoicePaid($invoice) {
// Update accounting system
// Send payment confirmation
error_log("Invoice {$invoice['id']} paid");
}
function handleShipmentDelivered($shipment) {
// Update order status
// Send delivery confirmation
error_log("Shipment {$shipment['id']} delivered");
}
?>
Don't repeat cURL setup code. Create a class or function that handles authentication and request execution.
When you receive a 429 response, wait for the time specified in the Retry-After header before retrying.
Validate required fields and formats on your end before making API calls to reduce errors.
Keep logs of API interactions for debugging and auditing. Include timestamps and request IDs.
Make your code more robust by using PHP's type system for API request/response handling.