No results found

Try a different search query

Popular searches:

Add to Cart

Cart

You have no purchases yet

Browse Marketplace
Original Subtotal:
Product discounts:
Quantity Discount:
Total:
View Cart
API and integrations

Webhook in OpenCart: How to Notify an External System About Orders in 3.0 and 4.1

How to build a webhook in OpenCart 3.0 and 4.1: an event on status change, a retry queue, HMAC signing, timeouts, and what to do when the external system is unavailable.

11 min read OC 3.0 OC 4.1

A webhook 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 built on an event: the module subscribes to order statusA stage of processing: "Pending," "Shipped," "Complete." Custom statuses are added in the dictionary. More in the glossary → changes and sends an HTTP request with the order data to an external system (CRM, accounting, Telegram bot). The core has no ready-made webhook mechanism in either 3.0 or 4.1. However, an event handler, a queue table in the module, and a cron job for retries handle the task reliably, and checkout doesn't slow down even when the CRM is down.

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

Which event should you subscribe to?

Almost everything that happens to an order after it's placed goes through one storefrontWhat the customer sees: the home page, categories, product page, and cart. More in the glossary → model method: addOrderHistory() in 3.0 and addHistory() in 4.1. It is called by payment confirmation, the payment gateway callback, a status change by an administrator, and the built-in API. That makes it the best point for a webhook. What the method does is covered in the article on addOrderHistory and status changes.

  • OpenCart 3.0: trigger catalog/model/checkout/order/addOrderHistory/after (slash before the method).
  • OpenCart 4.1: trigger catalog/model/checkout/order.addHistory/after (dot before the method).

A trigger with the wrong separator simply won't fire, and there will be no error. This is the most common reason a webhook "goes silent" after a module is moved from 3.0 to 4.1.

Why the storefront (catalog) event rather than the admin one? When an administrator changes the status in the order card, the admin in both versions runs this through storefront code. In 3.0, the admin browser calls the built-in storefront API, and in 4.1 the admin creates a storefront instance in the same process and runs the api/order controllerCode that receives a request and prepares data. More in the glossary → there, and the startup startup/event also runs. So an event on the storefront model fires for both the customer and the administrator. Details are in the article on the built-in API.

There is one exception to be aware of: deleting an order in the 4.1 admin goes through the admin model sale/order and does not call storefront models. If the external system needs a deletion notification, in 4.1 subscribe separately to admin/model/sale/order.deleteOrder/after. In 3.0, deletion goes through the storefront API.

Why not send the request directly from the handler?

The simplest option is to call curl in the after handler and forget about it. It works as long as the CRM responds quickly. Problems start with the first failure:

  • Checkout waits. The handler runs in the same request as order confirmation. If the CRM takes 20 seconds to respond, the customer stares at a "loading" screen for 20 seconds, and the payment gateway may not wait for a response to its callback.
  • Messages get lost. If the CRM is unavailable, nobody retries: the event has already been processed.
  • An exception breaks the chain. An unhandled error in the handler interrupts the request after the status has already been saved. Subsequent event handlers, the customer email, or the response to the payment gateway may not run.

So the reliable scheme is this: the handler only writes the event to a queue table and, optionally, makes one quick attempt with a short timeout. Anything that fails is sent later by cron.

flowchart TD
  A["addHistory / addOrderHistory"] --> B["after event: write to queue"]
  B --> C{"Quick attempt, timeout 3 s"}
  C -- "2xx" --> D["Mark: sent"]
  C -- "error" --> E["attempts + 1, next attempt later"]
  E --> F["Cron picks up overdue records"]
  F --> C

How do you register the event and write the handler?

The event is registered when the module is installed and removed when it is uninstalled. The signatures of the event model methods differ between versions:

  • OpenCart 3.0: $this->model_setting_event->addEvent($code, $trigger, $action, $status = 1, $sort_order = 0).
  • OpenCart 4.1: $this->model_setting_event->addEvent(array $data) with the keys code, description, trigger, action, status, sort_order.

Example: registering the event in the module's install() (OpenCart 4.1)

$this->load->model('setting/event');

$this->model_setting_event->addEvent([
    'code'        => 'mywebhook_order',
    'description' => 'Webhook: зміна статусу замовлення',
    'trigger'     => 'catalog/model/checkout/order.addHistory/after',
    'action'      => 'extension/mywebhook/event/webhook.order',
    'status'      => true,
    'sort_order'  => 0
]);

In 3.0, the same call looks like addEvent('mywebhook_order', 'catalog/model/checkout/order/addOrderHistory/after', 'extension/module/mywebhook/order'). How triggers work, handler order, and removing events are described in the article on addEvent and handler order.

The handler receives the route, the call arguments, and the result. For addHistory, the first argument is order_id, and the second is the new order_status_id.

Example: extension/mywebhook/catalog/controller/event/webhook.php (OpenCart 4.1)

<?php
namespace Opencart\Catalog\Controller\Extension\Mywebhook\Event;

class Webhook extends \Opencart\System\Engine\Controller {
    public function order(string &$route, array &$args, mixed &$output): void {
        if (!$this->config->get('module_mywebhook_status')) {
            return;
        }

        $order_id        = (int)($args[0] ?? 0);
        $order_status_id = (int)($args[1] ?? 0);

        if (!$order_id || !$order_status_id) {
            return;
        }

        try {
            $this->load->model('extension/mywebhook/module/webhook');

            $queue_id = $this->model_extension_mywebhook_module_webhook->enqueue($order_id, 'order.status', $order_status_id);

            $this->model_extension_mywebhook_module_webhook->send($queue_id, 3);
        } catch (\Throwable $e) {
            $this->log->write('mywebhook: ' . $e->getMessage());
        }
    }
}

In 3.0, the handler is a controller method catalog/controller/extension/module/mywebhook.php with the signature order(&$route, &$args, &$output). Don't return anything from it: in 3.0, a value returned from an after handler replaces the method's result. In 4.1, the returned value is ignored.

How do you set up the queue and what goes into the payload?

The queue is a regular module table, created by install(). The minimal set of columns:

Example: webhook queue table

CREATE TABLE IF NOT EXISTS `oc_mywebhook_queue` (
  `queue_id` int(11) NOT NULL AUTO_INCREMENT,
  `order_id` int(11) NOT NULL,
  `event` varchar(32) NOT NULL,
  `payload` mediumtext NOT NULL,
  `status` tinyint(1) NOT NULL DEFAULT '0',
  `attempts` int(11) NOT NULL DEFAULT '0',
  `last_error` varchar(255) NOT NULL DEFAULT '',
  `next_try` datetime NOT NULL,
  `date_added` datetime NOT NULL,
  PRIMARY KEY (`queue_id`),
  KEY `status_next_try` (`status`, `next_try`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

InnoDB is needed here in both branches, even in 3.0, where the core is almost entirely on MyISAM: cron and storefront requests write to the table at the same time, and row-level locking instead of whole-table locking helps noticeably. The charset and collation are set explicitly: if you specify only DEFAULT CHARSET=utf8mb4 without COLLATE, MySQL or MariaDB will use the default collation of that charset (utf8mb4_general_ci or utf8mb4_0900_ai_ci), not the database collation. utf8mb4_unicode_ci matches the core tables of 3.0.5.1 and 4.1.0.4. In 3.0.4.1, the core tables use utf8 / utf8_general_ci, so a JOIN on text fields with them may produce Illegal mix of collations (a JOIN on order_id works). Another option is to remove both DEFAULT CHARSET and COLLATE, in which case the table will take the database's charset and collation. Also keep in mind that in 3.0 the database connection works in utf8, so emoji in the payload won't be saved even in a utf8mb4 table. General rules for module tables are in the article on custom module tables.

Build the payload at the moment it is queued, not when it is sent. That way the CRM receives the order state as of the event, even if the retry happens an hour later. Take the data from the storefront model checkout/order:

  • OpenCart 3.0: getOrder(), getOrderProducts(), getOrderTotals().
  • OpenCart 4.1: getOrder(), getProducts(), getTotals().

Don't send the whole getOrder() array as is: it contains the IP, user agent, and service fields. Build an explicit structure from the needed fields (number, status, total, currency, customer, shipping address, products) and add an event_id field with queue_id. The recipient uses it to filter out duplicates. The composition of the order table fields is described in the article on the order table.

How to send: timeout, signature, retries

Example: send() method in the module model (OpenCart 4.1)

public function send(int $queue_id, int $timeout = 10): bool {
    $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "mywebhook_queue` WHERE `queue_id` = '" . (int)$queue_id . "' AND `status` = '0'");

    if (!$query->num_rows) {
        return false;
    }

    $body      = $query->row['payload'];
    $time      = time();
    $signature = hash_hmac('sha256', $time . '.' . $body, (string)$this->config->get('module_mywebhook_secret'));

    $curl = curl_init((string)$this->config->get('module_mywebhook_url'));
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 2);
    curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($curl, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'X-Webhook-Id: ' . (int)$queue_id,
        'X-Webhook-Timestamp: ' . $time,
        'X-Webhook-Signature: sha256=' . $signature
    ]);

    curl_exec($curl);

    $code  = (int)curl_getinfo($curl, CURLINFO_HTTP_CODE);
    $error = curl_error($curl);

    curl_close($curl);

    if ($code >= 200 && $code < 300) {
        $this->db->query("UPDATE `" . DB_PREFIX . "mywebhook_queue` SET `status` = '1' WHERE `queue_id` = '" . (int)$queue_id . "'");

        return true;
    }

    $attempts = (int)$query->row['attempts'] + 1;
    $delay    = min(86400, 60 * (2 ** $attempts));

    $this->db->query("UPDATE `" . DB_PREFIX . "mywebhook_queue` SET `attempts` = '" . $attempts . "', `status` = '" . ($attempts >= 10 ? 2 : 0) . "', `last_error` = '" . $this->db->escape(mb_substr($code . ' ' . $error, 0, 255)) . "', `next_try` = DATE_ADD(NOW(), INTERVAL " . (int)$delay . " SECOND) WHERE `queue_id` = '" . (int)$queue_id . "'");

    return false;
}

A few rules built into this code:

  • A short timeout in the event (2 seconds for the connection, 3 for the response), and a longer one in cron. The customer should not wait for the CRM.
  • HMAC signature over the timestamp and body lets the recipient verify that the request came from the store and was not replayed a week later. Store the secret in the module settings and don't confuse it with the key for incoming requests.
  • Success means only 2xx. A 301 redirectA permanent redirect from an old address to a new one. Mandatory when the structure changes. More in the glossary → or a login page returning 200 from a misconfigured server is a common trap. So do not enable CURLOPT_FOLLOWLOCATION; specify the final webhook URL.
  • Exponential backoff and a retry limit. After the tenth failure, the record moves to status 2 and must be handled manually. It's good to show such records on the module's admin page with a "retry" button.

Cron for retries

OpenCart 4.1: register the task via $this->model_setting_cron->addCron($code, $description, $cycle, $action, $status). The handler receives (int $cron_id, string $code, string $cycle, string $date_added, string $date_modified). Tasks are run by cron/cron, which is called from php cron.php or at the address index.php?route=cron/cron. The schedule is set by the word for strtotime, for example hour, so the built-in cron won't run the task more often than once an hour. If you need more frequent retries, call your own method with a separate system cron.

OpenCart 3.0: there is no built-in scheduler. Create a retry controller with key verification and call it from the system cron, for example every 5 minutes. Both options are described in detail in the article on cron in OpenCart.

The retry method selects status = 0 AND next_try <= NOW() records from LIMIT (for example, 50) and calls send() for each. The limit prevents a single cron run from hanging for an hour if the CRM responds in 10 seconds per request.

What to consider on the recipient's side and with duplicates?

It is impossible to guarantee a webhook without duplicates. The request may have arrived while the response was lost, and then cron will send it again. So agree with the recipient on three things:

  1. Processing by event_id (or the X-Webhook-Id header) is idempotent: a repeated request with the same id changes nothing and returns 200.
  2. Order is not guaranteed. A retry of an old event may arrive after a new one, so the recipient compares the status and event time rather than simply overwriting the data.
  3. The response must be fast: accept, put into its own queue, and return 2xx. Long processing on the CRM side leads to timeouts and extra retries.

Also think about which statuses should trigger the webhook. In 3.0, the order is created with status 0 already at the confirmation step, and the first addOrderHistory() call with a non-zero status effectively means "new order". If the CRM needs exactly this event, include the previous status in the payload as well. It can be read in the before handler of the same method or from order_history. How an order goes through the steps up to this point is described in the article on checkout in code.

If you need a ready-made data exchange instead of custom development, the Advanced REST API module covers some of these tasks: the external system fetches orders itself via REST.

Summary

  • The webhook subscribes to catalog/model/checkout/order/addOrderHistory/after in 3.0 or catalog/model/checkout/order.addHistory/after in 4.1. This event fires for the customer, the administrator, and the API alike.
  • The handler must not slow down checkout: write to the queue, make one quick attempt, and leave the rest to cron.
  • Build the payload when queuing it, with an explicit set of fields, and use event_id for deduplication.
  • Sign the body with HMAC including a timestamp, count only 2xx as success, and retry with increasing delays and a retry limit.
  • In 4.1, retries can be hooked to the built-in cron (no more often than once an hour); in 3.0, a system cron is required.
  • Deleting an order in the 4.1 admin requires a separate event on the admin model.

Other materials on data exchange with external systems, including the custom JSON endpoint, are collected in the "API and integrations" section.

FAQ

Can I send a webhook when a product is added to the cart or a customer registers?
Yes, using the same approach: an after event on the corresponding model method, for example addCustomer in the account/customer model. The cart has no model events because it is a library, so look at the checkout/cart controller instead.
What should I do if webhooks stop arriving after moving to another server?
Check whether outbound connections are allowed and whether the curl extension is enabled in PHP. Also look at the last_error column in the queue, since it shows the response code or the connection error.
Can I send webhooks to multiple addresses?
Yes, add a recipient address or id column to the queue and create a separate record for each one. That way, a failure in one system won't delay delivery to the others.
Do I need to clean up the queue table?
Yes, sent records older than a few weeks can be deleted by the same cron job. Otherwise, the table with payloads grows by the size of every order.
Was this article helpful?
Thanks for your feedback!

Related articles

Didn't find the answer?

Ask the community: OpenCart developers answer on the forum.

Ask on the forum
We use cookies

We use cookies and similar technologies to improve your experience, analyse traffic, and show personalised ads. Read our Cookie Policy for details.