OpenCart 4 має вбудований REST API, який дозволяє інтегрувати магазин з зовнішніми системами: мобільними додатками, CRM, ERP та іншими сервісами.
Налаштування API
Для початку роботи з API потрібно:
- Увімкнути API в адмін-панелі: System → Users → API
- Створити API користувача
- Згенерувати API ключ
- Налаштувати дозволені IP (опціонально)
Автентифікація
OpenCart 4 використовує token-based автентифікацію:
// Отримання токена
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => 'https://your-store.com/index.php?route=api/account/login',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => [
'username' => 'api_user',
'key' => 'your_api_key'
]
]);
$response = curl_exec($curl);
$data = json_decode($response, true);
$token = $data['api_token'];
Основні Endpoints
Товари
// Отримання списку товарів
GET /index.php?route=api/product&api_token={token}
// Отримання одного товару
GET /index.php?route=api/product&api_token={token}&product_id=123
// Пошук товарів
GET /index.php?route=api/product&api_token={token}&search=laptop
Кошик
// Додати товар в кошик
POST /index.php?route=api/cart/add&api_token={token}
{
"product_id": 123,
"quantity": 2,
"option": {
"226": "red"
}
}
// Отримати вміст кошика
GET /index.php?route=api/cart/products&api_token={token}
// Видалити з кошика
POST /index.php?route=api/cart/remove&api_token={token}
{
"key": "cart_item_key"
}
Замовлення
// Створення замовлення
POST /index.php?route=api/order/add&api_token={token}
{
"customer_id": 1,
"payment_address": {...},
"shipping_address": {...},
"payment_method": "cod",
"shipping_method": "flat.flat"
}
// Історія замовлень
GET /index.php?route=api/order/history&api_token={token}&order_id=100
API — це контракт між системами. Документуйте всі endpoints та версіонуйте API для зворотної сумісності.
— Best Practice
Створення власного API endpoint
<?php
// catalog/controller/api/custom.php
namespace Opencart\Catalog\Controller\Api;
class Custom extends \Opencart\System\Engine\Controller {
public function index(): void {
$this->load->language('api/custom');
$json = [];
if (!isset($this->session->data['api_id'])) {
$json['error'] = 'Unauthorized';
} else {
// Ваша логіка
$json['success'] = true;
$json['data'] = [
'message' => 'Custom API works!'
];
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
}
Обробка помилок
// Стандартна структура відповіді
{
"success": true,
"data": {...}
}
// Помилка
{
"error": "Product not found",
"error_code": 404
}
Приклад: Мобільний додаток
// JavaScript/React Native приклад
const API_URL = 'https://your-store.com/index.php';
let apiToken = null;
async function login() {
const response = await fetch(`${API_URL}?route=api/account/login`, {
method: 'POST',
body: JSON.stringify({
username: 'api_user',
key: 'api_key'
})
});
const data = await response.json();
apiToken = data.api_token;
}
async function getProducts() {
const response = await fetch(
`${API_URL}?route=api/product&api_token=${apiToken}`
);
return response.json();
}
Висновок
REST API відкриває багато можливостей для інтеграції OpenCart з іншими системами. Почніть з вивчення вбудованих endpoints, а потім створюйте власні для специфічних потреб вашого бізнесу.