Dashboard

Sales from search

Connect paid orders from your store to the searches that helped shoppers buy.

Before you start

You need SearchX running on your storefront, access to your store's backend, and a full application API key from the SearchX dashboard. Start with a staging store so you can check order delivery before enabling it on your live store.


What it shows

The Sales from search card on your store's Analytics tab compares orders and revenue from search with all paid orders your store posted to SearchX. The Sessions page also shows orders linked to a session.

Which orders count?

An order counts as a sale from search when, before the order was placed, its session on that store included a search, a click on a result, a sort change, or an add to cart.

Send the checkout time in created_at. Without it, SearchX uses when it first received the order. Products on the order do not have to match products clicked in search.

Every other paid order stays in the total. That includes orders from shoppers who did not allow the SearchX cookies, so if your store asks for cookie consent, the share is a minimum. An order with no session does not appear under a session. Cancelled and refunded orders are not included once your store posts that status.

Dates and revenue

An order counts in the period SearchX first received it as paid, not its checkout date. Repeating a paid post keeps that period.

Revenue is the total the store sent, in the currency it sent. SearchX does not add or remove tax, convert currencies, or rebuild a missing total from the lines. An order without a total still counts as an order, but contributes no revenue.


How it works

  1. At checkout, on the shopper's own request, read the cookie and save its session ID on the order. Prefer the last-search cookie, then the live cookie.
  2. When the order is paid, post the complete order with that saved ID, whether payment was confirmed at checkout, by a gateway callback, or by an administrator.
CookieRead priorityLifetime
_sx_last_sid_{app_id}First: last session with search, result-click, sort-change or add-to-cart activity7 days from that activity
_sx_sid_{app_id}Fallback: live session30 minutes, sliding with activity

Use the same host for checkout

Checkout must run on the same host as the storefront. www.example.com, example.com and checkout.example.com are different hosts, so they do not share these cookies.

Both cookies are host-only, path /, SameSite=Lax, and Secure on HTTPS. The SDK does not need to be mounted on checkout for its cookies to reach that host.

✅ Post every paid order, using session_id: null when there is no permitted session cookie. This keeps total orders and revenue meaningful.

❌ Do not read cookies for the first time in a payment callback. A gateway's server has no shopper cookies; a bank's cross-site POST back to the store also omits SameSite=Lax cookies.

Keep customer details out of the request

Send only order identifiers, product lines, totals, currency and status. Do not include customer names, email addresses, postal addresses, phone numbers, payment details, or customer identifiers in the body or in order_id.


Which key

Open your store in the SearchX dashboard, go to API Keys, and copy a full application API key into your server configuration.

Keep the full key on your server

Never put this key in browser JavaScript, a theme, a public repository, or a NEXT_PUBLIC_ environment variable. The key marked Public browser key is for the storefront SDK and cannot send orders: the endpoint returns HTTP 403, error code 4036.


Endpoint

POST /api/v1/applications/{app_id}/orders

  • Production: https://admin.searchxengine.ai
  • Staging: https://staging.searchxengine.ai
  • Authentication: Authorization: Bearer YOUR_APPLICATION_API_KEY
  • {app_id}: the store's 10-character application ID. Use keys and IDs from the same environment.
  • Rate limit: 120 requests per minute per client per organization, with an additional organization-wide ceiling. Respect Retry-After on HTTP 429.
curl -i -X POST "https://staging.searchxengine.ai/api/v1/applications/YOUR_APP_ID/orders" \
  -H "Authorization: Bearer YOUR_APPLICATION_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  --data '{"order_id":"setup-test-1001","session_id":null,"status":"paid","currency":"EUR","total":49.90,"items":[{"product_id":"42","sku":"SHOE","name":"Shoe","qty":1,"price":49.90}],"created_at":"2026-11-16T12:00:00Z"}'

For an attributed test, replace null with the session cookie captured during that checkout and created_at with the actual checkout time.

FieldRules
order_idRequired string or number, normalized to a string; maximum 255 characters. Stable and unique within this application.
itemsRequired, non-empty array, at most 500 lines. Each line is an object.
items[].product_id, items[].skuOptional strings or null, at most 255 characters each.
items[].nameOptional string or null, at most 500 characters. Product name only.
items[].qty, items[].priceOptional numbers or null.
session_idOptional string, at most 255 characters, or null.
statusOptional: placed, paid, cancelled, refunded, or null. Always send an explicit status in a new integration.
currencyOptional string or null, at most 10 characters; use the order's currency code, for example EUR.
totalOptional number or null; send the final order total in that currency.
created_atOptional date or null; send the checkout time in ISO 8601 with a timezone, not the draft-cart creation time or retry time.

Order status

The JSON-encoded body is limited to 256 KB. SearchX stores the posted body; do not add customer fields. placed does not count as paid. An omitted or null status is treated as paid for compatibility, so explicitly use placed for an unpaid order. cancelled and refunded remove the order from paid figures.

Responses and repeat posts

The first post for an order_id returns 201. Posting the same ID to the same application again updates that order and returns 200. Both return:

{ "order_id": "setup-test-1001" }

A repeat replaces the body: resend the full current order, not just its status. The saved session ID is kept if the repeat omits session_id or sends null or an empty string. This does not clear earlier attribution.

Check the latest order status before retrying

A paid post after a cancellation makes the order a sale again, counted when that new paid post arrives. Process one delivery job at a time for each order, and do not resend an old paid update after the order has been cancelled.

HTTP responseMeaning / next step
201, 200Created, or updated successfully.
401Missing, invalid or revoked API key.
403 / 4031Key belongs to another application.
403 / 4034Application is suspended. Resolve its status in the dashboard.
403 / 4036Public browser key cannot post orders; use a full key on the server.
404 / 4041Resource not found: check application ID, organization and environment.
422Invalid payload; inspect field errors and fix the body before retrying.
429Rate limited; queue the post and wait for Retry-After.

Retry connection failures, timeouts and server errors with bounded backoff. Do not repeatedly retry authentication or validation errors without fixing them. See Error Codes.


Start with cookieConsent: false when your consent tool requires consent before statistics cookies. Report the choice using SearchXSDK.setCookieConsent(true) or SearchXSDK.setCookieConsent(false).

SearchXSDK.init({
  app_id: 'YOUR_APP_ID',
  api_key: 'YOUR_PUBLIC_BROWSER_KEY',
  components: { SearchBar: { root: 'search-bar' } },
  cookieConsent: false,
});
// In your consent tool's statistics-consent callback:
// SearchXSDK.setCookieConsent(statisticsAllowed);

With Cookiebot, run this after the SearchX SDK has loaded:

const searchxConsent = () =>
  SearchXSDK.setCookieConsent(Boolean(window.Cookiebot?.consent?.statistics));
window.addEventListener('CookiebotOnAccept', searchxConsent);
window.addEventListener('CookiebotOnDecline', searchxConsent);
SearchXSDK.init({
  app_id: 'YOUR_APP_ID',
  api_key: 'YOUR_PUBLIC_BROWSER_KEY',
  components: { SearchBar: { root: 'search-bar' } },
  cookieConsent: Boolean(window.Cookiebot?.consent?.statistics),
});

Without consent, search and analytics still work with an in-memory session, but no session cookie is read or written. Post the order with a null session so it counts in the total only. Revoking consent deletes both cookies. Granting consent persists the session. setCookieConsent() can run before or after init(); a choice made before initialization takes precedence over its option.

getSessionId() returns the live session, even when it is only in memory. Do not use it to bypass cookie consent or replace the last-search-cookie-first lookup. Make sure your checkout also respects consent and does not forward a stale ID when consent has been withdrawn, including if the SDK fails to load.


Choose your platform

The PHP hooks below are separate from the SearchX search extensions. Install one order integration only, and test it on staging before using it in your store.


WooCommerce

Use your theme's functions.php or a small custom plugin. The hook saves the session at checkout and uses it when a payment gateway or administrator changes the order status. It supports both classic and block checkout.

Cash on delivery

Most orders are posted at Processing or Completed. Cash on delivery is posted only at Completed, when the money has been collected. Cancellation and refund status changes are also sent to SearchX.

Step 1: Add the order hook

Copy the code below into your custom plugin or functions.php. Replace YOUR_APPLICATION_API_KEY and YOUR_APP_ID, and use the staging API host while testing. If the file already starts with <?php, do not add a second opening tag.

<?php
if (!defined('SEARCHX_API_KEY')) {
    define('SEARCHX_API_KEY', 'YOUR_APPLICATION_API_KEY');
    define('SEARCHX_APP_ID', 'YOUR_APP_ID');
    define('SEARCHX_API_BASE', 'https://admin.searchxengine.ai');
}

if (!function_exists('searchx_cookie_session_id')) {
    function searchx_cookie_session_id()
    {
        foreach (['_sx_last_sid_', '_sx_sid_'] as $prefix) {
            $name = $prefix . SEARCHX_APP_ID;
            if (!empty($_COOKIE[$name])) {
                return substr(sanitize_text_field(wp_unslash($_COOKIE[$name])), 0, 255);
            }
        }

        return '';
    }

    // Step 1: checkout, on the shopper's request.
    function searchx_remember_session($order)
    {
        $session_id = searchx_cookie_session_id();
        if ($session_id !== '' && !$order->get_meta('_searchx_session_id')) {
            $order->update_meta_data('_searchx_session_id', $session_id);
        }
    }

    // Classic checkout. The order is saved right after this hook.
    add_action('woocommerce_checkout_create_order', 'searchx_remember_session');

    // Block checkout.
    add_action('woocommerce_store_api_checkout_update_order_meta', function ($order) {
        searchx_remember_session($order);
        $order->save_meta_data();
    });

    // Step 2: the order is paid, cancelled or refunded.
    function searchx_post_order($order_id, $status)
    {
        $order = wc_get_order($order_id);
        if (!$order) {
            return;
        }

        $items = [];
        foreach ($order->get_items() as $item) {
            $product = $item->get_product();
            $qty = (float) $item->get_quantity();
            $items[] = [
                'product_id' => (string) $item->get_product_id(),
                'sku' => $product ? (string) $product->get_sku() : '',
                'name' => $item->get_name(),
                'qty' => $qty,
                'price' => $qty > 0 ? round((float) $item->get_total() / $qty, 2) : 0.0,
            ];
        }

        $session_id = (string) $order->get_meta('_searchx_session_id');
        $created = $order->get_date_created();

        wp_remote_post(
            SEARCHX_API_BASE . '/api/v1/applications/' . rawurlencode(SEARCHX_APP_ID) . '/orders',
            [
                'timeout' => 3,
                'blocking' => false,
                'headers' => [
                    'Authorization' => 'Bearer ' . SEARCHX_API_KEY,
                    'Content-Type' => 'application/json',
                    'Accept' => 'application/json',
                ],
                'body' => wp_json_encode([
                    'session_id' => $session_id !== '' ? $session_id : null,
                    'order_id' => (string) $order->get_id(),
                    'status' => $status,
                    'currency' => $order->get_currency(),
                    'total' => (float) $order->get_total(),
                    'items' => $items,
                    'created_at' => $created ? $created->date('c') : gmdate('c'),
                ]),
            ]
        );
    }

    // Cash on delivery moves to Processing at checkout, before any money is
    // collected, so it counts as paid only once the order is Completed.
    add_action('woocommerce_order_status_processing', function ($order_id) {
        $order = wc_get_order($order_id);
        if ($order && $order->get_payment_method() !== 'cod') {
            searchx_post_order($order_id, 'paid');
        }
    });
    add_action('woocommerce_order_status_completed', function ($order_id) {
        searchx_post_order($order_id, 'paid');
    });
    add_action('woocommerce_order_status_cancelled', function ($order_id) {
        searchx_post_order($order_id, 'cancelled');
    });
    add_action('woocommerce_order_status_refunded', function ($order_id) {
        searchx_post_order($order_id, 'refunded');
    });
}

price is the line total divided by the quantity.

Step 2: Check order delivery

Follow Check it works for both classic and block checkout.

The request is non-blocking, so its return value cannot confirm SearchX returned 201 or 200. During a staging test only, temporarily set blocking to true and inspect wp_remote_retrieve_response_code() on the returned response (or inspect SearchX server logs). Restore blocking: false afterwards. Never log the key or customer data.

Delivery and retries

The hook uses a three-second timeout and does not wait for the response body, although connection setup can still take time. It does not automatically retry failed requests. For reliable retries, use your store's background job runner to resend the complete current order. Do not resend an old paid update after cancellation.


OpenCart 3

The hook saves the session at checkout, then reads it when a payment callback or administrator updates the order.

Requirements

Enable PHP cURL. The hook creates a small table for order IDs and session IDs, so the database user needs CREATE TABLE permission on first use. Alternatively, ask your database administrator to create the table first.

Step 1: Configure and save the controller

  1. Replace the application ID, full server API key and API host in the code below. Keep the key on the server and out of source control.
  2. In your store settings, check that Processing and Complete status groups represent payments received. Cash on delivery is posted only at Complete.
  3. Fill cancelled_status_ids and refunded_status_ids with integer IDs from your store's order statuses. Keep these groups separate from paid statuses. Full cancellations and refunds remove orders from Sales from search; partial refunds do not have a separate status.
  4. Save the file as catalog/controller/event/searchx.php.

Prices and totals use the order's saved currency_value to convert from the store's base currency to the order currency. Check that PHP uses the same timezone as date_added.

<?php
class ControllerEventSearchx extends Controller
{
    private $api_key = 'YOUR_APPLICATION_API_KEY';
    private $app_id = 'YOUR_APP_ID';
    private $api_base = 'https://admin.searchxengine.ai';
    // Fill these with YOUR store's cancelled/refunded status IDs.
    private $cancelled_status_ids = [];
    private $refunded_status_ids = [];

    // Trigger: catalog/model/checkout/order/addOrder/after
    public function remember(&$route, &$args, &$output)
    {
        try {
            $order_id = (int) $output;
            $session_id = $this->cookieSessionId();
            if (!$order_id || $session_id === '') {
                return;
            }

            $this->ensureTable();
            $this->db->query(
                "INSERT INTO `" . DB_PREFIX . "searchx_order_session` (`order_id`, `session_id`)"
                . " VALUES ('" . $order_id . "', '" . $this->db->escape($session_id) . "')"
                . " ON DUPLICATE KEY UPDATE `session_id` = VALUES(`session_id`)"
            );
        } catch (\Throwable $error) {
            $this->log->write('SearchX order hook failed; check configuration and retry delivery.');
        }
    }

    // Trigger: catalog/model/checkout/order/addOrderHistory/after
    public function history(&$route, &$args, &$output)
    {
        try {
            $order_id = isset($args[0]) ? (int) $args[0] : 0;
            if (!$order_id) {
                return;
            }
            $this->load->model('checkout/order');
            $order = $this->model_checkout_order->getOrder($order_id);
            if (!$order) {
                return;
            }
            // Fraud checks can change the requested status inside addHistory.
            // Use the saved status, not the callback argument.
            $status_id = (int) $order['order_status_id'];
            $status = in_array($status_id, $this->refunded_status_ids, true) ? 'refunded'
                : (in_array($status_id, $this->cancelled_status_ids, true) ? 'cancelled'
                : (in_array($status_id, $this->paidStatusIds(), true) ? 'paid' : null));
            if (!$order_id || $status === null) {
                return;
            }

            // Cash on delivery can be given a processing status at checkout,
            // before the money is collected. Count it only once it is complete.
            $complete = array_map('intval', (array) $this->config->get('config_complete_status'));
            if ($status === 'paid' && $order['payment_code'] === 'cod' && !in_array($status_id, $complete, true)) {
                return;
            }

            $items = [];
            foreach ($this->model_checkout_order->getOrderProducts($order_id) as $product) {
                $items[] = [
                    'product_id' => (string) $product['product_id'],
                    'sku' => (string) $product['model'],
                    'name' => (string) $product['name'],
                    'qty' => (float) $product['quantity'],
                    'price' => (float) $product['price'] * (float) $order['currency_value'],
                ];
            }

            $this->ensureTable();
            $row = $this->db->query(
                "SELECT `session_id` FROM `" . DB_PREFIX . "searchx_order_session`"
                . " WHERE `order_id` = '" . $order_id . "'"
            )->row;

            $this->post([
                'session_id' => !empty($row['session_id']) ? (string) $row['session_id'] : null,
                'order_id' => (string) $order_id,
                'status' => $status,
                'currency' => (string) $order['currency_code'],
                'total' => (float) $order['total'] * (float) $order['currency_value'],
                'items' => $items,
                'created_at' => date('c', strtotime($order['date_added'])),
            ]);
        } catch (\Throwable $error) {
            $this->log->write('SearchX order hook failed; check configuration and retry delivery.');
        }
    }

    private function cookieSessionId()
    {
        foreach (['_sx_last_sid_', '_sx_sid_'] as $prefix) {
            $name = $prefix . $this->app_id;
            if (!empty($_COOKIE[$name])) {
                return substr((string) $_COOKIE[$name], 0, 255);
            }
        }

        return '';
    }

    private function paidStatusIds()
    {
        $ids = array_merge(
            (array) $this->config->get('config_processing_status'),
            (array) $this->config->get('config_complete_status')
        );

        return array_map('intval', $ids);
    }

    private function ensureTable()
    {
        $this->db->query(
            "CREATE TABLE IF NOT EXISTS `" . DB_PREFIX . "searchx_order_session` ("
            . " `order_id` INT(11) NOT NULL,"
            . " `session_id` VARCHAR(255) NOT NULL,"
            . " PRIMARY KEY (`order_id`)"
            . ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"
        );
    }

    private function post(array $payload)
    {
        $url = rtrim($this->api_base, '/')
            . '/api/v1/applications/' . rawurlencode($this->app_id) . '/orders';
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode($payload),
            CURLOPT_HTTPHEADER => [
                'Authorization: Bearer ' . $this->api_key,
                'Content-Type: application/json',
                'Accept: application/json',
            ],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CONNECTTIMEOUT => 2,
            CURLOPT_TIMEOUT => 3,
        ]);
        curl_exec($ch);
        $http_status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        // No key, cookies, customer fields or response body in the log.
        $this->log->write('SearchX order ' . $payload['order_id'] . ' HTTP ' . $http_status);
        // On HTTP 0, 408, 429 or 5xx, schedule a retry through your store's
        // job runner. This minimal hook does not provide a retry queue.
    }
}

Step 2: Register the events

  1. In your database administration tool, select the store database. Replace every oc_ below with your configured DB_PREFIX, then run this SQL once. It replaces only these two SearchX event registrations. The standard Events screen does not offer an Add button.
DELETE FROM `oc_event` WHERE `code` IN ('searchx_order_remember', 'searchx_order_paid');
INSERT INTO `oc_event` (`code`, `trigger`, `action`, `status`, `sort_order`) VALUES
('searchx_order_remember', 'catalog/model/checkout/order/addOrder/after', 'event/searchx/remember', 1, 0),
('searchx_order_paid', 'catalog/model/checkout/order/addOrderHistory/after', 'event/searchx/history', 1, 0);
  1. Open Extensions → Events and confirm both entries are Enabled, sort order 0.

Step 3: Test an order

Follow Check it works, including a payment callback with no cookies and a cancellation. Inspect the OpenCart error log for the SearchX HTTP status.

Delivery and retries

The hook waits at most three seconds for each post (two seconds to connect). It logs delivery results but has no durable retry queue. Recover failed posts through a queued integration or resend the complete order after fixing the error. Repeated paid posts are safe. If you retry, read the order's current status first: a delayed paid post must not overwrite a cancellation or refund.


OpenCart 4

This version targets OpenCart 4.1.0.4. Its model events and controller actions use a dot before the method name. Do not install the OpenCart 3 controller here. Verify the route syntax and payment code if you use a different OpenCart 4 release.

The hook saves the session at checkout, then reads it when a payment callback or administrator updates the order.

Requirements

Enable PHP cURL. The hook creates a small table for order IDs and session IDs, so the database user needs CREATE TABLE permission on first use. Alternatively, ask your database administrator to create the table first.

Step 1: Configure and save the controller

  1. Replace the application ID, full server API key and API host in the code below. Keep the key on the server and out of source control.
  2. In your store settings, check that Processing and Complete status groups represent payments received. Cash on delivery is posted only at Complete.
  3. Fill cancelled_status_ids and refunded_status_ids with integer IDs from your store's order statuses. Keep these groups separate from paid statuses. Full cancellations and refunds remove orders from Sales from search; partial refunds do not have a separate status.
  4. Save the file as catalog/controller/event/searchx.php.

Prices and totals use the order's saved currency_value to convert from the store's base currency to the order currency. Check that PHP uses the same timezone as date_added.

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

class Searchx extends \Opencart\System\Engine\Controller
{
    private $api_key = 'YOUR_APPLICATION_API_KEY';
    private $app_id = 'YOUR_APP_ID';
    private $api_base = 'https://admin.searchxengine.ai';
    // Fill these with YOUR store's cancelled/refunded status IDs.
    private $cancelled_status_ids = [];
    private $refunded_status_ids = [];

    // Trigger: catalog/model/checkout/order.addOrder/after
    public function remember(&$route, &$args, &$output)
    {
        try {
            $order_id = (int) $output;
            $session_id = $this->cookieSessionId();
            if (!$order_id || $session_id === '') {
                return;
            }

            $this->ensureTable();
            $this->db->query(
                "INSERT INTO `" . DB_PREFIX . "searchx_order_session` (`order_id`, `session_id`)"
                . " VALUES ('" . $order_id . "', '" . $this->db->escape($session_id) . "')"
                . " ON DUPLICATE KEY UPDATE `session_id` = VALUES(`session_id`)"
            );
        } catch (\Throwable $error) {
            $this->log->write('SearchX order hook failed; check configuration and retry delivery.');
        }
    }

    // Trigger: catalog/model/checkout/order.addHistory/after
    public function history(&$route, &$args, &$output)
    {
        try {
            $order_id = isset($args[0]) ? (int) $args[0] : 0;
            if (!$order_id) {
                return;
            }
            $this->load->model('checkout/order');
            $order = $this->model_checkout_order->getOrder($order_id);
            if (!$order) {
                return;
            }
            // Fraud checks can change the requested status inside addHistory.
            // Use the saved status, not the callback argument.
            $status_id = (int) $order['order_status_id'];
            $status = in_array($status_id, $this->refunded_status_ids, true) ? 'refunded'
                : (in_array($status_id, $this->cancelled_status_ids, true) ? 'cancelled'
                : (in_array($status_id, $this->paidStatusIds(), true) ? 'paid' : null));
            if (!$order_id || $status === null) {
                return;
            }

            // Cash on delivery can be given a processing status at checkout,
            // before the money is collected. Count it only once it is complete.
            $complete = array_map('intval', (array) $this->config->get('config_complete_status'));
            if ($status === 'paid' && ($order['payment_method']['code'] ?? '') === 'cod.cod' && !in_array($status_id, $complete, true)) {
                return;
            }

            $items = [];
            foreach ($this->model_checkout_order->getProducts($order_id) as $product) {
                $items[] = [
                    'product_id' => (string) $product['product_id'],
                    'sku' => (string) $product['model'],
                    'name' => (string) $product['name'],
                    'qty' => (float) $product['quantity'],
                    'price' => (float) $product['price'] * (float) $order['currency_value'],
                ];
            }

            $this->ensureTable();
            $row = $this->db->query(
                "SELECT `session_id` FROM `" . DB_PREFIX . "searchx_order_session`"
                . " WHERE `order_id` = '" . $order_id . "'"
            )->row;

            $this->post([
                'session_id' => !empty($row['session_id']) ? (string) $row['session_id'] : null,
                'order_id' => (string) $order_id,
                'status' => $status,
                'currency' => (string) $order['currency_code'],
                'total' => (float) $order['total'] * (float) $order['currency_value'],
                'items' => $items,
                'created_at' => date('c', strtotime($order['date_added'])),
            ]);
        } catch (\Throwable $error) {
            $this->log->write('SearchX order hook failed; check configuration and retry delivery.');
        }
    }

    private function cookieSessionId()
    {
        foreach (['_sx_last_sid_', '_sx_sid_'] as $prefix) {
            $name = $prefix . $this->app_id;
            if (!empty($_COOKIE[$name])) {
                return substr((string) $_COOKIE[$name], 0, 255);
            }
        }

        return '';
    }

    private function paidStatusIds()
    {
        $ids = array_merge(
            (array) $this->config->get('config_processing_status'),
            (array) $this->config->get('config_complete_status')
        );

        return array_map('intval', $ids);
    }

    private function ensureTable()
    {
        $this->db->query(
            "CREATE TABLE IF NOT EXISTS `" . DB_PREFIX . "searchx_order_session` ("
            . " `order_id` INT(11) NOT NULL,"
            . " `session_id` VARCHAR(255) NOT NULL,"
            . " PRIMARY KEY (`order_id`)"
            . ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"
        );
    }

    private function post(array $payload)
    {
        $url = rtrim($this->api_base, '/')
            . '/api/v1/applications/' . rawurlencode($this->app_id) . '/orders';
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode($payload),
            CURLOPT_HTTPHEADER => [
                'Authorization: Bearer ' . $this->api_key,
                'Content-Type: application/json',
                'Accept: application/json',
            ],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CONNECTTIMEOUT => 2,
            CURLOPT_TIMEOUT => 3,
        ]);
        curl_exec($ch);
        $http_status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        // No key, cookies, customer fields or response body in the log.
        $this->log->write('SearchX order ' . $payload['order_id'] . ' HTTP ' . $http_status);
        // On HTTP 0, 408, 429 or 5xx, schedule a retry through your store's
        // job runner. This minimal hook does not provide a retry queue.
    }
}

Step 2: Register the events

  1. In your database administration tool, select the store database. Replace every oc_ below with your configured DB_PREFIX, then run this SQL once. It replaces only these two SearchX event registrations. The standard Events screen does not offer an Add button.
DELETE FROM `oc_event` WHERE `code` IN ('searchx_order_remember', 'searchx_order_paid');
INSERT INTO `oc_event` (`code`, `trigger`, `action`, `status`, `sort_order`, `description`) VALUES
('searchx_order_remember', 'catalog/model/checkout/order.addOrder/after', 'event/searchx.remember', 1, 0, 'SearchX order notification'),
('searchx_order_paid', 'catalog/model/checkout/order.addHistory/after', 'event/searchx.history', 1, 0, 'SearchX order notification');
  1. Open Extensions → Events and confirm both entries are Enabled, sort order 0.

Step 3: Test an order

Follow Check it works, including a payment callback with no cookies and a cancellation. Inspect the OpenCart error log for the SearchX HTTP status.

Delivery and retries

The hook waits at most three seconds for each post (two seconds to connect). It logs delivery results but has no durable retry queue. Recover failed posts through a queued integration or resend the complete order after fixing the error. Repeated paid posts are safe. If you retry, read the order's current status first: a delayed paid post must not overwrite a cancellation or refund.


Custom store / headless

Use this approach for Next.js, React or HTML stores with your own backend.

Step 1: Save the session and queue order updates

  1. Read the last-search cookie, then the live cookie on the shopper's checkout request. Read it server-side on the storefront host, or pass it from that host's frontend as part of the authenticated checkout request to your backend. Respect the shopper's consent. A backend on another host cannot read storefront cookies from its own cookie header.
  2. Validate and store the session on the order. Keep the checkout timestamp stable across retries. Persist once, rather than replacing it during gateway callbacks.
  3. When payment is confirmed, enqueue delivery after the order transaction commits. Do this for all payment paths, including administrator actions. A submitted unpaid order is not a payment; cash on delivery needs confirmation of collection.
  4. Let a worker send the complete payload with a short timeout. Process one delivery job at a time per order, check its current payment or cancellation status, and retry temporary failures with a limit on attempts and a delay between them. Log failed enqueue operations for recovery; a queue outage or SearchX error must never fail checkout. A transactional outbox can make recovery durable.
  5. Send cancellation/refund updates using the same order ID. Never let a delayed paid job overwrite a newer cancellation.

Step 2: Connect the Node.js example

This Node.js 22 example reads the checkout cookie and sends orders to SearchX. Wire these functions to your own checkout transaction, database and durable queue; the HTTP function belongs in a worker, not a browser or a checkout request.

// searchx-orders.mjs — server only; never import into a client bundle.
export function checkoutSession(cookieHeader, appId, statisticsAllowed) {
  if (!statisticsAllowed) return null;
  const cookies = new Map(
    (cookieHeader || '').split(';').map((part) => {
      const separator = part.indexOf('=');
      return separator < 0
        ? [part.trim(), '']
        : [part.slice(0, separator).trim(), part.slice(separator + 1).trim()];
    }),
  );
  for (const prefix of ['_sx_last_sid_', '_sx_sid_']) {
    const raw = cookies.get(prefix + appId);
    if (!raw) continue;
    try {
      const value = decodeURIComponent(raw);
      if (value && value.length <= 255) return value;
    } catch {
      /* Ignore a malformed cookie and try the fallback. */
    }
  }
  return null;
}

export async function postOrder(payload, config) {
  const response = await fetch(
    `${config.baseUrl}/api/v1/applications/${encodeURIComponent(config.appId)}/orders`,
    {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${config.apiKey}`,
        'Content-Type': 'application/json',
        Accept: 'application/json',
      },
      body: JSON.stringify(payload),
      signal: AbortSignal.timeout(3000),
    },
  );
  if (response.status === 200 || response.status === 201) return response.status;
  const error = new Error(`SearchX returned HTTP ${response.status}`);
  error.retryable = response.status === 408 || response.status === 429 || response.status >= 500;
  error.retryAfter = response.headers.get('retry-after');
  throw error;
}

// In your worker, after acquiring a per-order lock and loading CURRENT state:
// const status = await postOrder({
//   order_id: String(order.id),
//   session_id: order.searchxSessionId ?? null,
//   status: order.searchxStatus, // paid, cancelled or refunded from current state
//   currency: order.currency,
//   total: order.total,
//   items: order.items.map(item => ({
//     product_id: String(item.productId), sku: item.sku, name: item.name,
//     qty: item.quantity, price: item.unitPrice,
//   })),
//   created_at: order.checkoutAt.toISOString(),
// }, {
//   baseUrl: process.env.SEARCHX_API_BASE,
//   appId: process.env.SEARCHX_APP_ID,
//   apiKey: process.env.SEARCHX_API_KEY,
// });

At checkout, pass the shopper's cookie header and the consent decision to checkoutSession(), then persist its result with the order. If passing the value from the frontend instead, send only the consent-permitted cookie value (or null), validate it as a string up to 255 characters, and tie the request to that shopper's checkout. Never accept totals or paid status from the browser; use server records.

Step 3: Configure retries

Configure your worker for at most five attempts with increasing delays (for example 5, 30, 120 and 300 seconds). Network/timeout exceptions and errors with retryable: true may retry. Honour retryAfter if present; it can be seconds or an HTTP date. Other HTTP errors require intervention. Log order ID, attempt and HTTP status, never the key, cookie header, payload or customer information.


Shopify

Sales from search for Shopify is not available yet. It will have a separate integration. Do not put a full application API key in a theme, Custom Liquid, checkout script, or browser request. The public browser key cannot send orders.


Check it works

  1. Use a test store on staging with its own full key and matching SDK application ID. Accept statistics cookies, search and click a result before checking out.
  2. In DevTools → Application → Cookies, verify _sx_last_sid_{app_id} or _sx_sid_{app_id} exists on the checkout host before checkout. Confirm the backend saves that ID on the order.
  3. Pay the test order. Inspect the store's server response/log: the first POST returns 201, and repeating the same complete payload returns 200.
  4. Select the period containing the receipt of the paid POST. Check the store's Analytics card for the order/revenue increase and its session on Sessions.
  5. Repeat with no consent: no _sx_ cookies, null session, total-only order. Test your gateway callback without shopper cookies and COD completion too.
  6. Cancel the test order afterwards and verify a cancelled POST with the same order ID returns 200 and removes it from paid figures. If your hook does not map that status yet, post the complete cancellation manually from the server. Cancel every test order after recording results.

Record the store/platform version, order ID, HTTP codes, card changes and Sessions result. A successful search alone does not verify order delivery.


Troubleshooting

SymptomCheck
Cookies exist on the storefront but not at checkoutCompare the exact hosts, including www. and checkout.. Use one storefront/checkout host. For headless backends, pass the consent-permitted value in the checkout request.
Payment callback has no cookieExpected for gateway server callbacks and cross-site POSTs. Save the session on the shopper's checkout request and load it from the order.
401Check the server's Bearer key is present, valid and not revoked; do not expose it in logs.
4031Use the key issued for this application.
4034Resolve the application's suspended status.
4036Replace the public browser key with a full server key in backend configuration only.
404Verify the application ID, key's organization and production/staging host match.
422Inspect field errors, maximum lengths, non-empty items, allowed statuses and the 256 KB limit.
429Queue delivery, honour Retry-After, and stay within 120 requests per minute.
Card still says “Not set up yet”SearchX has received no order for this store yet. Check the actual POST response, app ID and environment. A store with posts but no paid orders in the selected period instead shows “No paid orders in this period.”
Order appears in a later periodThe period is when SearchX first received it as paid, not the store's created_at. Check delayed jobs and the dashboard date range.
Total-only order despite searchCheck consent, cookie expiry, saved session, application ID and whether the search happened before the posted checkout time.
Cancelled order still countedSend a complete cancelled or refunded update with the original order ID; check status mappings and stale paid retries.

Previous
Analytics & Statistics