Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 27 ยท Themes and APIs

Catalog and Admin APIs

Use the OpenCart API user, session login and api/ routes, build your own JSON endpoint in an extension, protect it with tokens and IP lists, and send webhooks.

Sooner or later a store has to talk to other software: an ERP that pulls orders, a mobile app that shows products, a warehouse system that wants to be told when an order is paid. OpenCart offers two ways to do this. There is a built-in API that the admin panel itself uses to build orders, and there are the routes of your own extensions, which can return JSON for any purpose you design. Understanding both, and knowing where the built-in one is not enough, saves a lot of time.

In this lesson you will learn how the OpenCart API user and its login work, what the api/ routes do, how to write a JSON endpoint inside an extension, how to protect it with tokens and IP rules, and how to notify external systems with webhooks. The real OpenCart code and the HTTP calls are read-only here, because OpenCart cannot run on this site. The runnable examples are plain PHP stand-ins for the logic. General integration ideas are in Integrations and signatures in Webhooks and Signatures. Routes themselves are explained in Routing and Controllers.

The API user and the login call

In the admin panel, under System > Users > API, you create an API user. It has a username, a generated key, a status, and a list of allowed IP addresses. The API user is a separate thing from admin users: it has no panel access and no password in the normal sense, and the key is a secret.

The flow of a client using the built-in API (read-only, shown as a conceptual curl session; route names and the method separator vary between versions):

TEXT
# 1. log in; the response contains a token or session information
curl -X POST "https://shop.example/index.php?route=api/account/login&language=en-gb" \
     -d "username=integration" -d "key=THE_SECRET_KEY"

# 2. call an api/ route, passing the session information from step 1
curl -X POST "https://shop.example/index.php?route=api/sale/cart.add&language=en-gb" \
     -d "product_id=42" -d "quantity=2"

The details differ by version, so check the catalog/controller/api folder of the release you run:

  • In 4.0.0 and 4.0.1 a route method was separated from its class by a pipe (api/sale/cart|add); from 4.0.2 it uses a dot (api/sale/cart.add). A client written for one breaks on the other. Pin the version you support and say so in your documentation.
  • The API session is a normal OpenCart session. Everything you add to the cart through the API lives in that session, which means that two parallel clients need two separate logins.
  • The login checks the key and the calling IP address against the API user's allowed list. A client on a changing IP, such as a phone, will not pass. This is a deliberate protection and not a bug.

What the built-in API is for

The routes under api/ mirror the steps the admin panel needs to create an order by hand: set the customer, add products to the cart, choose payment and shipping methods, apply a coupon or voucher, and finally confirm the order. They are not a REST API in the modern sense:

  • They are session-based and stateful: you build a cart step by step.
  • They return JSON with either success or error keys, in a format you must parse yourself.
  • There are no general listing routes such as "all products updated since yesterday", so they are poor at data synchronisation.

Use the built-in API when you want to create orders the same way the admin does, for example a phone-order tool. For reading data in bulk, exposing a clean catalog, or notifying other systems, write your own endpoint.

sequenceDiagram
    participant C as Client
    participant S as Store api/ routes
    C->>S: POST api/account/login (username, key)
    S-->>C: success + session information
    C->>S: POST api/sale/cart.add (product_id, quantity)
    S-->>C: success or error JSON
    C->>S: POST api/sale/order.confirm
    S-->>C: success + order_id

The built-in API is a conversation inside one session: login, build the cart, confirm the order.

Your own JSON endpoint

Any controller method can return JSON. An extension that exposes a read-only stock check can offer a route such as extension/acme/api/stock.index (read-only, simplified; permission and routing details follow the catalog controller rules from Routing and Controllers):

PHP
<?php
namespace Opencart\Catalog\Controller\Extension\Acme\Api;

class Stock extends \Opencart\System\Engine\Controller {
    public function index(): void {
        $json = [];

        if (!$this->isAuthorised()) {
            $this->response->addHeader('HTTP/1.1 401 Unauthorized');
            $json['error'] = 'Invalid token';
        } else {
            $product_id = (int)($this->request->get['product_id'] ?? 0);

            $this->load->model('catalog/product');
            $product = $this->model_catalog_product->getProduct($product_id);

            if ($product) {
                $json['product_id'] = $product_id;
                $json['quantity']   = (int)$product['quantity'];
            } else {
                $this->response->addHeader('HTTP/1.1 404 Not Found');
                $json['error'] = 'Unknown product';
            }
        }

        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }

    private function isAuthorised(): bool {
        $given = $this->request->server['HTTP_AUTHORIZATION'] ?? '';
        $token = 'Bearer ' . $this->config->get('module_acme_stock_token');
        return $given !== '' && hash_equals($token, $given);
    }
}

Points worth copying:

  • Cast input immediately ((int)), and use model methods, not hand-written SQL in controllers.
  • Use proper HTTP statuses (401, 404, 422, 429) along with a small JSON error. Clients and monitoring depend on them.
  • Compare secrets with hash_equals, which takes the same time regardless of how many characters match.
  • Set the Content-Type header and send JSON only. Never mix HTML notices (from display_errors) into the output; keep errors in the log in production.
  • Keep the token in a setting edited in the admin form, not in the source code. Generate it with bin2hex(random_bytes(32)).

Tokens, expiry and IP rules

A single static bearer token is acceptable for server-to-server calls, but add layers as the risk grows: an allow list of IP addresses (cheap and effective, but fails behind changing proxies, so decide which header you trust before you read X-Forwarded-For), expiring tokens that are issued by a login call, and rate limiting so a leaked token cannot be used for unlimited scraping. Log the caller and the result (never the secret). The stand-in below puts these together.

A token-checked endpoint stand-in

This stand-in simulates the whole exchange in one file, with no network. A login function checks the key and the caller's IP address and issues a token that expires; a stock endpoint checks the token and returns status code plus JSON. The "time" is a fixed number so the output never changes.

PHP Login, token and JSON responses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Every failure has its own status: 401 for who-are-you problems, 403 for a known caller from a forbidden place, 404 for a missing resource. A client can react to the status code without reading the text.

Webhooks to external systems

APIs answer when asked. A webhook is the opposite: the store calls another system when something happens, such as an order being paid. In OpenCart this is usually an event on order creation or status change, which writes a job into a table and lets a background step deliver it, because a slow remote server must not delay the customer's checkout. The delivery should carry an event id (so the receiver can ignore duplicates), a timestamp, and a signature made with a shared secret. The reasons and the receiver's checks are in Webhooks and Signatures and Idempotency. A complete build is the project Order Webhook Exporter.

Sending code is short (read-only):

PHP
$body = json_encode(['event' => 'order.paid', 'order_id' => 1005, 'id' => 'evt_9f3a']);
$time = time();
$signature = hash_hmac('sha256', $time . '.' . $body, $secret);

$curl = curl_init($url);
curl_setopt_array($curl, [
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => $body,
    CURLOPT_HTTPHEADER     => ['Content-Type: application/json', 'X-Timestamp: ' . $time, 'X-Signature: ' . $signature],
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CONNECTTIMEOUT => 3,
    CURLOPT_TIMEOUT        => 8,
]);
$response = curl_exec($curl);

The signed text includes the timestamp, so a captured request cannot be replayed much later. The next stand-in builds and verifies such a signature, without any network.

PHP Signing and verifying a webhook

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Changing a single digit in the body, using another secret, or replaying the request after the tolerance window all lead to rejection.

Choosing the right interface

Need Use
Create an order like the admin does Built-in api/ routes
Let an app read products or stock Your own endpoint with a token
Tell another system about an order Event, queue table and signed webhook
Bulk import or export Admin import tools or a CLI-style script, not web requests

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why can a client with a correct API key still be refused at login?

    The built-in API checks the key and the caller's IP against the API user's allowed addresses.
  2. 2. What is a main weakness of the built-in api/ routes for data synchronisation?

    They mirror the admin order-entry steps. For reading data in bulk, an extension endpoint is a better fit.
  3. 3. Which comparison should you use for a secret token in PHP?

    hash_equals compares in constant time, so response timing does not reveal how much of the secret was right.
  4. 4. Why does a signed webhook include a timestamp in the signed text?

    The receiver checks that the timestamp is recent and that the signature covers it, so an old request fails.

Summary

  • The built-in API uses an API user with a key and an IP allow list; it is session-based and meant for creating orders like the admin does, and its route format differs between 4.0.0/4.0.1 and later versions.
  • For anything else, write a JSON endpoint in your extension: cast input, use models, answer with correct HTTP statuses and a Content-Type of JSON.
  • Protect endpoints with a secret token compared via hash_equals, optional IP rules, expiry and rate limits, and keep secrets in settings.
  • Webhooks are outgoing calls started by events; queue them, sign them with a timestamp, include an event id and use short timeouts.

Next: Security for Extension Developers