A custom API endpoint in OpenCartA free open-source CMS for online stores, written in PHP with a MySQL/MariaDB database. Everything that is not part of the core is added through extensions. More in the glossary → is a regular storefrontWhat the customer sees: the home page, categories, product page, and cart. More in the glossary → controllerCode that receives a request and prepares data. More in the glossary → in your module that returns JSON instead of an HTML page. The core does not provide a ready-made REST API for products or orders, so integrations with a CRM, accounting system, or mobile app almost always need such a controller. Below we cover where to place it, how to protect it with a key, how to return the response correctly, and the small details that break an endpoint on a live server.
Examples are for OpenCart 4.1; in 4.0.x, model triggers and event handling differ.
Why not the built-in API, and where should the controller go?
The core's built-in API only covers the order scenario: cart, customer, shipping and payment methods, confirmation, and status history. What it includes and how it authenticates is described in the article on the built-in OpenCart API. For a list of products, stock levels, or new orders for a period, you need your own controller.
Place it in the storefront (catalog), not in the admin. Admin controllers require an administrator session and user_token, so an external system cannot reach them without logging in. On the storefront, the controller is available at index.php?route=... without any prerequisites, and you handle the protection yourself.
| OpenCart 3.0 | OpenCart 4.1 | |
|---|---|---|
| File | catalog/ | extension/ |
| Class | ControllerExtensionModuleMysync extends Controller | namespace Opencart\Catalog\Controller\Extension\Mysync\Module;, class Mysync |
| Method route | extension/ | extension/ |
| When available | as soon as the file is in place | only if the extension package is installed |
The last row is important. In 4.1, the startup/extension controller registers namespaces only for packages listed in the extension table, that is, installed under "ExtensionsAdditional functionality: a module, a payment or shipping method, a feed, or a theme. They are managed in "Extensions → Extensions." More in the glossary → → Extensions." Until the module is installed, the route returns a "not found" error. In 3.0, the file with catalog/controller is loaded directly by the route, even if nobody installed the module. Therefore, in 3.0 you must check the module status in code, otherwise the endpoint will keep working after the module is "removed" in the admin.
The method separator (slash in 3.0, dot in 4.1) is covered in detail in the article on the route= parameter, and the file layout of a package is described in the anatomy of an extension. The extension type is not critical: the endpoint can go into a module of type module, or into a separate package that outputs nothing on pages.
What does a minimal endpoint look like?
The skeleton is the same in both versions: check that the module is enabled, verify the key, collect the data, and return JSON with the correct header and HTTP code.
Example: extension/mysync/catalog/controller/module/mysync.php (OpenCart 4.1)
<?php
namespace Opencart\Catalog\Controller\Extension\Mysync\Module;
class Mysync extends \Opencart\System\Engine\Controller {
public function products(): void {
if (!$this->authorize()) {
return;
}
$page = max(1, $this->request->get('page', 'int'));
$limit = min(500, max(1, $this->request->get('limit', 'int') ?: 100));
$this->load->model('extension/mysync/module/mysync');
$products = $this->model_extension_mysync_module_mysync->getProducts(($page - 1) * $limit, $limit);
$this->json(200, [
'page' => $page,
'limit' => $limit,
'products' => $products
]);
}
private function authorize(): bool {
if (!$this->config->get('module_mysync_status')) {
$this->json(404, ['error' => 'not_found']);
return false;
}
$key = (string)($this->request->server['HTTP_X_API_KEY'] ?? '');
if ($key === '' || !hash_equals((string)$this->config->get('module_mysync_key'), $key)) {
$this->json(401, ['error' => 'unauthorized']);
return false;
}
return true;
}
private function json(int $code, array $data): void {
$protocol = $this->request->server['SERVER_PROTOCOL'] ?? 'HTTP/1.1';
$this->response->addHeader($protocol . ' ' . $code);
$this->response->addHeader('Content-Type: application/json; charset=utf-8');
$this->response->setOutput(json_encode($data, JSON_UNESCAPED_UNICODE));
}
}
The private methods authorize() and json() are not called by the route: the core dispatcher only calls public methods in both 3.0 and 4.1, and blocks names starting with __. The address of this endpoint is index.php?route=extension/.
There are few differences in 3.0. The class is global (class ControllerExtensionModuleMysync extends Controller), without type declarations in signatures. The model is loaded as $this and is available as $this. The $this helper does not exist in 3.0: it appeared in Request 4.1. In 3.0, write isset($this.
Store the key and status as regular module settings with the module_mysync_ prefix. The core loads store settings into $this->config at startup, so no separate query is needed. The admin form is built using the same rules as for any module; see module settings and the setting table.
How do you protect the endpoint?
The storefront controller address is public, so access control is entirely your responsibility. The minimum set:
- A long random key from the module settings, compared with
hash_equals()rather than==. You can generate it during installation, for example withoc_token(64)in 4.1 ortoken(64)in 3.0. - The key in a header, not in the URL. GET parameters end up in web server access logs, proxies, and analytics. The
X-Api-Keyheader is usually not written to them. - HTTPS only. Check the request scheme, or at least store the endpoint address in the settings with https.
- A separate key for writing. If the endpoint also modifies data (prices, stock), give a read-only integration a different key.
Why X-Api-Key and not the standard Authorization: Bearer? On some hosts with Apache and PHP-FPM or CGI, the Authorization header is not passed to $_SERVER without an extra rule in .htaccess. A custom header X-... arrives as HTTP_X_API_KEY without any configuration. If a partner specifically requires Bearer, check both variants.
For integrations with higher requirements, instead of a static key you can sign the request with HMAC and a timestamp, as startup/api does in 4.1: then an intercepted request cannot be replayed after a few minutes.
How do you accept JSON in the request body?
If an external system sends Content-Type: application/, PHP does not parse the body into $_POST. Because of this, $this is empty in both versions. Read the body yourself:
Example: a method that accepts JSON with stock changes (OpenCart 4.1)
public function stock(): void {
if (!$this->authorize()) {
return;
}
if (($this->request->server['REQUEST_METHOD'] ?? '') !== 'POST') {
$this->json(405, ['error' => 'method_not_allowed']);
return;
}
$input = json_decode((string)file_get_contents('php://input'), true);
if (!is_array($input) || empty($input['items']) || !is_array($input['items'])) {
$this->json(422, ['error' => 'invalid_body']);
return;
}
$this->load->model('extension/mysync/module/mysync');
$updated = 0;
foreach (array_slice($input['items'], 0, 1000) as $item) {
if (isset($item['sku'], $item['quantity'])) {
$updated += $this->model_extension_mysync_module_mysync->setQuantityBySku((string)$item['sku'], (int)$item['quantity']);
}
}
$this->json(200, ['updated' => $updated]);
}
Data from php://input does not pass through htmlspecialchars, so it reaches the model "raw." This is good for accuracy (names with quotes are not corrupted), but every value must be cast to the right type and escaped for SQL just like form data. How to do this without injections is explained in the article on safe SQL queries. The package size limit (here 1000 items) protects against timeouts when a partner sends the entire warehouse in one request.
Which model should you use for data?
The temptation is to call core models, for example catalog/product and its getProducts(). They suit the storefront, but often not integrations:
- they return only enabled products of the current store with an availability date in the past, while an accounting system usually needs all of them;
- prices are calculated for the customer groupA segment of buyers (retail, wholesale) with different prices and terms. More in the glossary → from
config_customer_group_id, that is, for a guest; - in 3.0,
getProducts()first selects ids and then makes a separategetProduct()for each one. On a page of 500 products, that is 500 extra queries.
For exports, write your own model method that selects exactly the needed columns in one query using LIMIT:
Example: a model method for exporting products (OpenCart 4.1)
public function getProducts(int $start, int $limit): array {
$query = $this->db->query("SELECT p.`product_id`, p.`model`, p.`sku`, p.`quantity`, p.`price`, p.`status`, pd.`name`
FROM `" . DB_PREFIX . "product` p
LEFT JOIN `" . DB_PREFIX . "product_description` pd ON (pd.`product_id` = p.`product_id` AND pd.`language_id` = '" . (int)$this->config->get('config_language_id') . "')
ORDER BY p.`product_id`
LIMIT " . (int)$start . "," . (int)$limit);
return $query->rows;
}
For incremental synchronization (only changed items), add a filter on p.date_modified and return the time to continue from in the response. A large OFFSET over tens of thousands of products slows down, so for a full traversal a "cursor" by product_id > останній is better. There is an article on slow queries about indexes for such queries.
What breaks the endpoint on a live server?
Maintenance mode
The startup/maintenance controller lets through only api... routes, and in 3.0 also extension/. Your endpoint at extension/ or extension/ will receive the maintenance HTML page with code 503. The integration client must be able to handle 503 and retry the request later. You cannot name your route "under api": in 4.1, startup/api blocks all api/... except two built-in ones.
PHP warnings in the response body
If error display is enabled in the settings, any warning is printed before the JSON, and the client receives an invalid response. The same problem is described in the article on diagnosing payment callbacks. On a live site, turn off error display but keep logging enabled.
Caching and compression
The response passes through Response::output(), so when compression is enabled (level set in the server settings), JSON is served as gzip if the client accepts it. This is usually a plus. However, page caching at the hosting or CDN level for route=extension/... addresses must be disabled: otherwise two different keys would receive the same cached response. Add the Cache-Control: no-store header.
A session on every request
The core startup opens a session and sets a cookie even for a request from a partner server. With the db driver, this is a row in the session table for every call without a cookie. Sessions are cleaned up by the garbage collector, but if an integration makes thousands of requests per hour, the table grows noticeably. The client should keep the cookie between requests.
CORS for browser clients
If the endpoint is called by JavaScript from another domain, add Access-Control-Allow-Origin with a specific domain and handle the OPTIONS request. Do not keep the secret key in browser code: for the frontend, create separate read-only endpoints for public data only. For how to return JSON for AJAX on your own site, see the article on AJAX in OpenCart.
Summary
- An endpoint is a public method of a storefront controller in a module. In 3.0 the route is written with a slash; in 4.1 the method is separated by a dot.
- In 4.1 the route works only for an installed extension. In 3.0 the file is always available, so check the module status in code.
- Take the key from the module settings, pass it in the
X-Api-Keyheader, and compare it withhash_equals(). - Return JSON with
Content-Typeand the correct HTTP code: 401, 404, 405, 422, 200. - Read the JSON body from
php://input, cast values to types, and limit the package size. - For exports, write a custom model with
LIMITinstead of calling the storefrontgetProducts(). - Prepare the client for 503 in maintenance mode, turn off error display, and disable response caching.
If there is no ready-made integration with your accounting system, look at how, for example, OpenCart data exchange with BAS and other accounting systems is built. Other materials on data exchange are collected in the section "API and integrations".