Интеграция API OpenCart 4.0 - Руководство разработчика

Интеграция API OpenCart 4.0
OpenCart 4.0 приносит мощные API функции, которые позволяют интегрироваться с внешними сервисами и создавать кастомные решения. Это руководство покажет полный процесс.
Основы API:
1. Настройка Authentication
// Генерация API Token
$username = "api_user";
$password = "secure_password";
$api_token = hash("sha256", $username . $password . date("Y-m-d H:i:s"));
// Настройка Headers
$headers = [
"Content-Type: application/json",
"Authorization: Bearer " . $api_token,
"Accept: application/json"
];
2. Основные endpoints:
/api/customers
- управление клиентами/api/products
- управление товарами/api/orders
- управление заказами/api/categories
- управление категориями/api/manufacturers
- управление производителями
Практические примеры:
1. Добавление нового товара:
function addProduct($product_data, $headers) {
$url = "https://yourstore.com/api/products";
$data = [
"name" => $product_data["name"],
"description" => $product_data["description"],
"price" => $product_data["price"],
"sku" => $product_data["sku"],
"quantity" => $product_data["quantity"],
"status" => 1,
"category_id" => $product_data["category_id"],
"image" => $product_data["image_url"]
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($http_code === 201) {
return json_decode($response, true);
} else {
throw new Exception("API Error: " . $response);
}
}
2. Получение данных заказа:
function getOrder($order_id, $headers) {
$url = "https://yourstore.com/api/orders/" . $order_id;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($http_code === 200) {
return json_decode($response, true);
} else {
return false;
}
}
Расширенная функциональность:
1. Настройка Webhook:
// Обработчик Webhook endpoint
function handleOpenCartWebhook() {
$payload = file_get_contents("php://input");
$data = json_decode($payload, true);
// Проверка подписи webhook
$signature = $_SERVER["HTTP_X_OPENCART_SIGNATURE"] ?? "";
if (!verifyWebhookSignature($payload, $signature)) {
http_response_code(401);
exit("Unauthorized");
}
$event_type = $data["event"] ?? "";
switch ($event_type) {
case "order.created":
processNewOrder($data["order"]);
break;
case "order.updated":
updateOrderStatus($data["order"]);
break;
case "product.updated":
syncProductToWarehouse($data["product"]);
break;
case "customer.registered":
sendWelcomeEmail($data["customer"]);
break;
default:
error_log("Unknown webhook event: " . $event_type);
}
http_response_code(200);
echo "OK";
}
2. Синхронизация инвентаря для множества товаров:
class InventorySync {
private $api_url;
private $headers;
public function __construct($api_url, $headers) {
$this->api_url = $api_url;
$this->headers = $headers;
}
public function syncBulkInventory($products) {
$batch_size = 50;
$batches = array_chunk($products, $batch_size);
foreach ($batches as $batch) {
$this->processBatch($batch);
sleep(1); // Rate limiting
}
}
}
Соображения безопасности:
✅ Best Practices:
- Использовать только HTTPS
- Хранить API keys в environment variables
- Input validation для всех данных
- Защита от SQL injection
- Внедрить rate limiting
- Добавить comprehensive logging
- Error handling для всех requests
Обработка ошибок:
function handleApiError($response_code, $response_body) {
switch ($response_code) {
case 401:
throw new UnauthorizedException("Invalid API credentials");
case 403:
throw new ForbiddenException("Access denied");
case 404:
throw new NotFoundException("Resource not found");
case 429:
throw new RateLimitException("Rate limit exceeded");
case 500:
throw new ServerException("Internal server error: " . $response_body);
default:
if ($response_code >= 400) {
throw new ApiException("API Error ($response_code): " . $response_body);
}
return json_decode($response_body, true);
}
}
Тестирование и отладка:
🔧 Инструменты тестирования:
- Использовать Postman/Insomnia для тестирования API calls
- Писать unit tests для всех API functions
- Создавать integration tests для end-to-end scenarios
- Настроить log monitoring в production environment
- Собирать performance metrics для API response times
Заключение: Правильное использование API и качественная интеграция могут значительно улучшить функциональность вашего OpenCart магазина и создать ценные бизнес-решения.