# Built-in OpenCart API: What It Does and How to Enable It in 3.0 and 4.1

> What the built-in OpenCart 3.0 and 4.1 API can really do: key and IP, api_token and HMAC signature, available order calls, and when you need a custom endpoint.

Джерело: https://opencartcode.com/en/wiki/dev-api/api-opencart
OpenCart: 3.0, 4.1
Оновлено: 2026-11-25

The built-in [OpenCart](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#opencart) API is a set of controllers `catalog/controller/api/` through which you can build a cart, place, edit or delete an order, and add an entry to its history. The core itself uses it when an administrator edits an order. There is no REST API for products, categories or customers in the core. To use the built-in API, you need an API user with a key, an allowed IP address and the correct authentication scheme. And that scheme is completely different in 3.0 and 4.1.

Examples are for OpenCart 4.1; in 4.0.x, model triggers and event handling differ.

## What can the built-in API do and what can't it do?

The set of calls revolves around one scenario: assembling an order the same way a customer does at checkout, just without a browser. That is why the API includes the cart, customer, addresses, shipping and payment methods, coupons and order confirmation, but there is no catalog.

| What | OpenCart 3.0 | OpenCart 4.1 |
| --- | --- | --- |
| Login | `api/login` returns `api_token` | there is no separate login, each request is signed |
| Cart | `api/cart/add`, `edit`, `remove`, `products` | `api/order` with `call=product_add`, `cart` |
| Customer | `api/customer` | `call=customer` |
| Addresses and methods | `api/payment/address`, `methods`, `method`; likewise `api/shipping/...` | `call=payment_address`, `shipping_address`, `shipping_methods`, `shipping_method`, `payment_methods`, `payment_method` |
| Discounts | `api/coupon`, `api/voucher`, `api/reward` | `call=extension` (total modules) |
| Orders | `api/order/add`, `edit`, `delete`, `info` | `call=confirm` |
| Order status history | `api/order/history` | `call=history_add` |
| Subscriptions | none | `api/subscription` |

In other words, the built-in API suits tasks like "the CRM changes the [order status](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#order-status)" or "a phone operator places an order from another system". You cannot export products, update stock levels or retrieve a list of orders through it: for that, you write a custom endpoint in a module. For how to return JSON from a [controller](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#controller), see the article on [AJAX and JSON responses](https://opencartcode.com/en/wiki/dev-mvc/ajax-opencart).

One more feature: API calls change the order state through the same models as the [storefront](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#storefront). Adding history goes through `addOrderHistory()` in 3.0 and `addHistory()` in 4.1, with all its consequences: stock deduction, emails, coupons. What exactly happens in this case is covered in the article on [changing order status](https://opencartcode.com/en/wiki/dev-flows/addorderhistory-opencart).

## How do you enable the API in the admin?

In both branches the path is the same: System → Users → API.

1. Create an API user or open an existing one (the installer creates one itself). The General tab has the name (API Username), the key (API Key) and the status. The key is generated with a button; its length is sufficient, so do not shorten it.
2. Enable the status. A disabled user will pass neither login in 3.0 nor signature verification in 4.1.
3. On the IP tab, add the addresses from which requests will come. Without this, access is denied in both versions.
4. For order editing in the admin to work, select this user in the API User field on the Option tab in System → Settings.

Option tab: the API user field through which the admin edits orders · OpenCart 4.1.0.4

The third tab differs. In 3.0 it is Sessions: open `api_token` with IPs, which can be deleted. In 4.1 it is History: a log of calls with the name `call` and the IP, which `startup/api` fills in after each successful request. For diagnosing an integration in 4.1, this is the first place to look.

### IP address behind a proxy

In 3.0 the IP is taken from `REMOTE_ADDR`. If the site sits behind Cloudflare or another proxy and the web server does not restore the client's real address, the core sees the proxy's IP. Then you have to whitelist those IPs, which effectively opens the API to everyone. In 4.1 the IP is determined by `oc_get_ip()`: first `CF-Connecting-IP`, `X-Forwarded-For` and other proxy headers, and only then `REMOTE_ADDR`. This is convenient behind a proxy, but if the site runs without one, a client can set such a header itself. Therefore, in 4.1 the IP whitelist is only a supplementary filter, and real protection comes from the secret key and the signature.

## How does authentication work in OpenCart 3.0?

In 3.0 the API is built on sessions. The client first logs in, receives `api_token` (this is the session identifier) and then passes it as a GET parameter in every request.

`catalog/controller/api/login.php` · OpenCart 3.0.5.1 · lines 10–15

```php
		// Login with API Key
		if (isset($this->request->post['username']) && isset($this->request->post['key'])) {
			$api_info = $this->model_account_api->login($this->request->post['username'], $this->request->post['key']);
		} elseif (isset($this->request->post['key'])) {
			$api_info = $this->model_account_api->login('Default', $this->request->post['key']);
		}
```

If you send only `key`, the core looks for a user with the name `Default`. After checking the key and IP, a new session is created, its id is written to the `api_session` table, and `api_id` is stored in the session. After that, `startup/session` for each `api/...` route with the `api_token` parameter looks up this session together with the IP and the user status. Every API controller first checks `$this->session->data['api_id']` and without it returns an access error.

Example: changing order status through the API (OpenCart 3.0)

```bash
# 1. Вхід: у відповіді JSON з api_token
curl -s -X POST "https://example.com/index.php?route=api/login" \
  --data-urlencode "username=crm" --data-urlencode "key=ВАШ_КЛЮЧ"

# 2. Історія замовлення 15: order_id у GET, решта в POST
curl -s -X POST "https://example.com/index.php?route=api/order/history&api_token=TOKEN&order_id=15" \
  --data "order_status_id=5&notify=1&comment=Оплата+підтверджена"
```

API sessions live briefly: `startup/session` deletes `api_session` records that have not been accessed for more than an hour. An integration that makes a request once a day must log in again each time. How sessions themselves work is explained in the article on [sessions and cache](https://opencartcode.com/en/wiki/dev-architecture/opencart-session).

> The message "Your IP ... is not allowed to access this API" when editing an order in the 3.0 admin means that your browser's IP is not in the API user's list in the settings. The 3.0 admin opens an API session and then sends requests from the browser, so the administrator's IP must be on the whitelist. There is a button next to the message that adds this address.

## How does authentication work in OpenCart 4.1?

In 4.1 the scheme has been rewritten. There is no separate login, and `api_token` as in 3.0 should not be used here: the 4.1.0.4 database schema has no `api_session` table. Instead, the `startup/api` controller verifies every request to `api/order` and `api/subscription`. The remaining `api/...` routes (for example `api/cart`) are not directly accessible and always return 403.

Required GET parameters: `route`, `call`, `username`, `store_id`, `language`, `currency`, `time` and `signature`. It checks that the user exists and is enabled, that the IP is in the whitelist, and that `time` differs from the server time by no more than 450 seconds. Finally, the HMAC signature is verified.

`catalog/controller/startup/api.php` · OpenCart 4.1.0.4 · lines 84–99

```php
			if ($status) {
				$string  = (string)$this->request->get['route'] . "\n";
				$string .= (string)$this->request->get['call'] . "\n";
				$string .= $api_info['username'] . "\n";
				$string .= (string)$this->request->server['HTTP_HOST'] . "\n";
				$string .= (!empty($this->request->server['PHP_SELF']) ? rtrim(dirname($this->request->server['PHP_SELF']), '/') . '/' : '/') . "\n";
				$string .= (int)$this->request->get['store_id'] . "\n";
				$string .= (string)$this->request->get['language'] . "\n";
				$string .= (string)$this->request->get['currency'] . "\n";
				$string .= md5(http_build_query($this->request->post)) . "\n";
				$string .= $time . "\n";

				if (!hash_equals(base64_encode(hash_hmac('sha1', $string, $api_info['key'], true)), rawurldecode($this->request->get['signature']))) {
					$status = false;
				}
			}
```

The client must build exactly the same string. Here is a minimal client for calling `history_add` that requires no preliminary steps:

Example: signed API call (OpenCart 4.1)

```php
$username = 'crm';
$key      = 'ВАШ_КЛЮЧ';
$host     = 'example.com';
$path     = '/';            // каталог, де лежить index.php, зі слешем у кінці
$time     = time();

$get = [
    'route'    => 'api/order',
    'call'     => 'history_add',
    'username' => $username,
    'store_id' => 0,
    'language' => 'uk-ua',
    'currency' => 'UAH',
    'time'     => $time
];

$post = [
    'order_id'        => 15,
    'order_status_id' => 5,
    'comment'         => 'Оплата підтверджена',
    'notify'          => 1
];

$string  = $get['route'] . "\n" . $get['call'] . "\n" . $username . "\n" . $host . "\n" . $path . "\n";
$string .= $get['store_id'] . "\n" . $get['language'] . "\n" . $get['currency'] . "\n";
$string .= md5(http_build_query($post)) . "\n" . $time . "\n";

$get['signature'] = base64_encode(hash_hmac('sha1', $string, $key, true));

$curl = curl_init('https://' . $host . $path . 'index.php?' . http_build_query($get));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post));

$response = json_decode(curl_exec($curl), true);
```

Three places where the signature most often doesn't match:

- **Host and path.** The server takes `HTTP_HOST` and the script directory. If the client calls `www.example.com` but signs `example.com`, the check will fail. For a store in a subdirectory, the path will be `/shop/`.
- **POST after processing.** The server computes `md5` from `$this->request->post`, while Request passes values through `htmlspecialchars` (see the article on [Request and Response](https://opencartcode.com/en/wiki/dev-architecture/opencart-request-response)). As long as the values contain no quotes, ampersands or angle brackets, the hashes match. If they do, the client has to compute the hash from equally escaped values.
- **Time.** A clock difference of more than 450 seconds gives 403 even with the correct key.

## How does the admin use the API and why does it matter for modules?

**OpenCart 3.0:** the order page in the admin opens an API session for the user from `config_api_id`, passes `api_token` to the [template](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#template), and then JavaScript sends requests from the browser to `index.php?route=api/...` of the storefront. Because of this, order editing is affected by everything between the browser and the storefront: a different storefront domain, mixed http/https, CORS, WAF.

**OpenCart 4.1:** the scheme differs from 3.0. There are no `api_session` and `api_token` tables here, so the admin does not open an API session the way 3.0 does. The API user for order editing must still be selected in the API User field on the Option tab. For exactly how the admin calls the API controllers, see the `admin/controller/sale/order.php` code of your release.

For module authors, two consequences follow:

- Events on the order model (`addOrder`, `editOrder`, `addOrderHistory` or `addHistory`) fire both when placing an order on the storefront, when an administrator edits an order, and when an external API call is made. If a module needs to distinguish these cases, check the route or `$this->session->data['api_id']` in 3.0. How to subscribe to such events is described in the article on the [event system](https://opencartcode.com/en/wiki/dev-events-ocmod/events-opencart).
- Payment and shipping modules must work correctly without the customer's browser. For example, `getQuote()` or `getMethods()` must not rely on cookies or session data that does not exist in the API context.

The order data flow is the same as at checkout, so for understanding the fields, the articles on [checkout in code](https://opencartcode.com/en/wiki/dev-flows/checkout-opencart-kod) and the [order table](https://opencartcode.com/en/wiki/dev-database/table-order-opencart) are useful.

## When is the built-in API not enough?

In practice, integrations with external services (CRM, accounting systems, marketplaces) almost always need things the built-in API lacks. These include exporting products and stock, a list of new orders from a certain date, and price updates. There are two ways to handle this:

1. **A custom endpoint in a module.** A controller in `catalog/controller/extension/...` (3.0) or `extension/{код}/catalog/controller/...` (4.1) that checks its own token or signature and returns JSON. The key check can be modeled on `startup/api` or you can use the `api` table from the core. The route of such a controller is built by the usual rules (slash in 3.0, dot before the method in 4.1; see the article on [routing](https://opencartcode.com/en/wiki/dev-mvc/opencart-route)).
2. **Webhooks.** Instead of an external system polling the store, the store itself notifies it about a new order or a status change from an event handler after `addHistory`.

The built-in API remains the simplest way to change an order status from outside without custom code: it already performs all the checks, deducts stock and sends emails just like the admin does. For product tasks or bulk operations, it is not suitable.

## Summary

- The built-in API handles orders: cart, customer, addresses, shipping and payment methods, confirmation and history. It has no catalog.
- The user, key and IP whitelist are set in System → Users → API. For the admin, select it in the API User field on the Option tab.
- OpenCart 3.0: `api/login` returns `api_token`, which lives for an hour since the last access and is verified together with the IP.
- OpenCart 4.1: there is no login; only `api/order` and `api/subscription` are available, and each request is signed with HMAC-SHA1 according to the rules of `startup/api.php` with a 450-second window.
- The 3.0 admin calls the API from the browser through `api_token`, while in 4.1 there are no API sessions. Events on the order model fire in all these scenarios.
- For products, stock and exports, write a custom endpoint or webhooks.

Other materials on data exchange with external systems are collected in the section ["API and integrations"](https://opencartcode.com/en/wiki/dev-api).

## FAQ

**Can the built-in API return a list of products or orders?**

No, there are no such calls in either 3.0 or 4.1. This requires a custom controller in a module that returns JSON and checks access itself.

**Can I have several API users?**

Yes, it's better to give each integration its own user with its own key and IP. That way, one system's access can be disabled without affecting the others.

**Why did the external integration stop working after upgrading from 3.0 to 4.1?**

In 4.1 there is no api/login or api_token, and routes like api/cart/add are closed. The client needs to be rewritten to use signed requests to api/order with the call parameter.

**Does the API work when the store is in maintenance mode?**

Yes, in both versions startup/maintenance lets through routes starting with api, even when the storefront is closed.
