Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 27 ยท Real-world projects

Project: A Hosted-Checkout Payment Extension

Build an OpenCart payment extension that redirects to a hosted gateway page, verifies a signed callback, maps order statuses, survives retries and supports admin refunds.

A hosted-checkout gateway takes the card details on its own page, so your store never sees them. That is the simplest way to accept cards safely, and it is how most OpenCart payment extensions work. The flow is easy to describe and hard to get right: send the customer to the gateway, wait for the gateway to tell your server what happened, update the order exactly once, and do all of that safely when messages arrive twice, late or forged.

In this project you build the extension Acme Hosted Pay for a made-up gateway. OpenCart and a real gateway cannot run on this site, so the extension files are read-only code, while the gateway and the signature logic are runnable stand-ins in plain PHP. They are not any real provider's API; they model the common pattern described in Payments Overview, Webhooks and Signatures, Idempotency and Authorize, Capture and Refund. The OpenCart side builds on Building a Payment Extension.

The flow

sequenceDiagram
    participant C as Customer
    participant S as OpenCart store
    participant G as Gateway
    C->>S: Confirm order
    S->>G: Create payment session (order id, amount)
    G-->>S: Session id and hosted URL
    S-->>C: Redirect to hosted URL
    C->>G: Enters card details
    G-->>C: Redirect back to the store
    G->>S: Signed callback (payment.paid)
    S->>S: Verify, de-duplicate, update order

The customer's return is only for display. The signed server-to-server callback is what changes the order.

Two rules shape everything that follows:

  1. Never trust the browser return. The customer can close the tab before returning, or open the return URL by hand. Only the signed callback marks an order paid.
  2. Assume every callback can arrive twice, in any order. Gateways retry on timeouts. Your handler must be idempotent.

Files

TEXT
extension/acme/
  install.json
  admin/controller/payment/hostedpay.php        settings and refund action
  admin/language/en-gb/payment/hostedpay.php
  admin/view/template/payment/hostedpay.twig
  catalog/controller/payment/hostedpay.php      confirm, return and callback
  catalog/model/payment/hostedpay.php           payment methods, event table
  catalog/view/template/payment/hostedpay.twig  the "Confirm" button

Step 1: offering the method (read-only)

The model tells checkout whether the method is available for this address and cart. The settings you store are: status, geo zone, minimum total, sort order, the gateway's API key and signing secret, and the mapping from gateway outcomes to order statuses. Keep the secret in settings and never print it in templates or logs (see Security for Extension Developers).

PHP
<?php
namespace Opencart\Catalog\Model\Extension\Acme\Payment;

class HostedPay extends \Opencart\System\Engine\Model {
    // Signature and method name differ between 4.0.x releases (getMethod vs getMethods): check the bundled payment extensions of your version.
    public function getMethods(array $address): array {
        $this->load->language('extension/acme/payment/hostedpay');

        $total = $this->cart->getTotal();
        if ($total < (float)$this->config->get('payment_hostedpay_total')) {
            return [];
        }

        $geoZoneId = (int)$this->config->get('payment_hostedpay_geo_zone_id');
        if ($geoZoneId) {
            $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone_to_geo_zone`
                WHERE `geo_zone_id` = '" . $geoZoneId . "'
                AND `country_id` = '" . (int)$address['country_id'] . "'
                AND (`zone_id` = '" . (int)$address['zone_id'] . "' OR `zone_id` = '0')");
            if (!$query->num_rows) {
                return [];
            }
        }

        return [
            'code'       => 'hostedpay',
            'name'       => $this->language->get('heading_title'),
            'option'     => [
                'hostedpay' => [
                    'code' => 'hostedpay.hostedpay',
                    'name' => $this->language->get('text_title')
                ]
            ],
            'sort_order' => (int)$this->config->get('payment_hostedpay_sort_order')
        ];
    }
}

Step 2: the signature (runnable)

The gateway signs each callback body with a shared secret. Your handler recomputes the signature and compares it with a constant-time function. The header format here is t=<unix time>,v1=<hex HMAC>, and the signed text is the timestamp, a dot, and the raw body exactly as received. Including the timestamp lets you reject old messages that an attacker recorded and replays later.

PHP Signing and verifying a callback

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.

Two details matter in real code. Read the body with file_get_contents('php://input') and verify before decoding, because re-encoded JSON may differ byte for byte. And compare with hash_equals(), never ===, so the comparison time does not leak how many characters matched.

Step 3: the callback handler (runnable stand-in)

The handler does six things in order:

  1. Verify the signature. If it fails, answer 400 and change nothing.
  2. Decode the body and load the order.
  3. Check the amount (and currency) against the order total. A valid signature on the wrong amount is still a problem, for example from a partial payment.
  4. Insert the gateway's event_id into a table with a unique key. If it already exists, the event is a duplicate: answer 200 and do nothing.
  5. Map the event to an order status, and apply it only if the transition makes sense.
  6. Do steps 4 and 5 in one database transaction, so a crash cannot record the event without updating the order.

Answer 200 quickly for anything you have understood (including duplicates and ignored events), so the gateway stops retrying. Answer an error status only when you want a retry, such as a temporary database failure.

PHP A callback handler with de-duplication and status rules

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.

Look at what the table of results teaches. Case 2 shows idempotency; case 3 shows that a forged amount never reaches the database; case 5 shows that a late "paid" cannot undo a refund; case 6 shows why the amount is checked separately from the signature; and cases 7 and 8 show that a failed attempt can still be followed by a successful retry.

Step 4: the real controller (read-only)

In OpenCart the callback becomes a method of the catalog controller. It must work without a session or user token, because the gateway's server has neither; the signature replaces both. The route format (a dot before the method name in recent 4.0.x releases, a pipe in the earliest ones) is explained in Routing and Controllers.

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

class HostedPay extends \Opencart\System\Engine\Controller {
    public function index(): string {
        $this->load->language('extension/acme/payment/hostedpay');
        $data['language'] = $this->config->get('config_language');
        return $this->load->view('extension/acme/payment/hostedpay', $data);
    }

    public function confirm(): void {
        $this->load->language('extension/acme/payment/hostedpay');
        $json = [];

        if (!isset($this->session->data['order_id']) || ($this->session->data['payment_method']['code'] ?? '') !== 'hostedpay.hostedpay') {
            $json['error'] = $this->language->get('error_order');
        }

        if (!$json) {
            $this->load->model('checkout/order');
            $order = $this->model_checkout_order->getOrder((int)$this->session->data['order_id']);

            $session = $this->createGatewaySession(
                (int)$order['order_id'],
                (int)round($order['total'] * $order['currency_value'] * 100),
                $order['currency_code'],
                $this->url->link('extension/acme/payment/hostedpay.returned', 'language=' . $this->config->get('config_language'), true)
            );

            if ($session) {
                $json['redirect'] = $session['url'];
            } else {
                $json['error'] = $this->language->get('error_gateway');
            }
        }

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

    public function callback(): void {
        $body   = file_get_contents('php://input');
        $header = $_SERVER['HTTP_X_GATEWAY_SIGNATURE'] ?? '';

        if (!$this->isValidSignature($body, $header)) {
            http_response_code(400);
            return;
        }

        $event = json_decode($body, true);
        // Order lookup, amount check, event table insert and the status map follow the runnable handler above.
        // $statusId is the order status chosen in settings for this event type.
        $statusId = (int)$this->config->get('payment_hostedpay_paid_status_id');
        $this->load->model('checkout/order');
        $this->model_checkout_order->addHistory((int)$event['order_id'], (int)$statusId, 'Gateway event ' . $event['event_id'], true);

        http_response_code(200);
    }
}

Order of operations inside callback() follows the runnable handler line by line. The database part uses a table created at install time:

SQL
CREATE TABLE IF NOT EXISTS `oc_acme_hostedpay_event` (
  `event_id` VARCHAR(64) NOT NULL,
  `order_id` INT(11) NOT NULL,
  `date_added` DATETIME NOT NULL,
  PRIMARY KEY (`event_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

The PRIMARY KEY on event_id is what makes the de-duplication race-proof: two simultaneous deliveries cannot both insert the row, so only one continues. Create the table in the admin controller's install() and drop it in uninstall() as in Install, Uninstall and Permissions.

The order status mapping

Merchants name their statuses differently ("Processing", "Paid", "Awaiting shipment"), so the extension lets them choose in settings: payment_hostedpay_paid_status_id, ..._failed_status_id and ..._refunded_status_id, each a dropdown of the store's order statuses (loaded with the localisation/order_status model). The handler maps the gateway event to the setting, then calls addHistory() with that id. The allowed-transition table in the runnable handler is a guard against late and duplicate events; in OpenCart you would compare the order's current order_status_id with the target.

Step 5: refunds from the admin (read-only)

A refund starts with a person, in the admin order screen, so it goes through the admin controller with a permission check, a CSRF-style user_token and an idempotency key so a double click does not refund twice. The idempotency key is derived from the order id and the number of refunds already made.

PHP
<?php
public function refund(): void {
    $this->load->language('extension/acme/payment/hostedpay');
    $json = [];

    if (!$this->user->hasPermission('modify', 'extension/acme/payment/hostedpay')) {
        $json['error'] = $this->language->get('error_permission');
    }

    $orderId = (int)($this->request->post['order_id'] ?? 0);
    $amount  = (int)round((float)($this->request->post['amount'] ?? 0) * 100);

    if (!$json) {
        $this->load->model('extension/acme/payment/hostedpay');
        $refunded = $this->model_extension_acme_payment_hostedpay->getRefundedCents($orderId);
        $paid     = $this->model_extension_acme_payment_hostedpay->getPaidCents($orderId);

        if ($amount <= 0 || $refunded + $amount > $paid) {
            $json['error'] = $this->language->get('error_amount');
        }
    }

    if (!$json) {
        $key    = 'refund-' . $orderId . '-' . $this->model_extension_acme_payment_hostedpay->countRefunds($orderId);
        $result = $this->callGatewayRefund($orderId, $amount, $key);   // sends an Idempotency-Key header

        $json = $result ? ['success' => $this->language->get('text_refunded')] : ['error' => $this->language->get('error_gateway')];
    }

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

The order status itself still changes only when the signed payment.refunded callback arrives, so there is one place that updates orders. The admin only asks for the refund.

Testing a payment extension

  • Unit-test the handler logic (signature, amount, transitions) as shown, with no OpenCart.
  • Use the gateway's sandbox for the end-to-end flow, including cancelled and failed payments, and deliver each callback twice.
  • Test an unreachable gateway. Confirm should show a friendly error, not a blank page, and use timeouts as in Performance in Extensions.
  • Check the logs for secrets and card-like data. There should be none.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the extension update the order only from the signed callback and not from the customer's return to the store?

    The browser return is under the customer's control. Only a message signed with the shared secret proves the gateway sent it.
  2. 2. What makes a duplicate callback harmless in the handler?

    Storing each event id with a unique key means the second delivery finds the row and does nothing, so the order is updated once.
  3. 3. A callback has a valid signature but an amount of 1.00 for an order totalling 49.90. What should happen?

    A valid signature proves who sent the message, not that the amount is right. Compare the paid amount with the order total before marking the order paid.
  4. 4. Why is hash_equals() used to compare signatures?

    A normal comparison can stop at the first difference, and the timing may help an attacker guess a signature. hash_equals() takes the same time regardless.

Summary

  • A hosted checkout keeps card data off your server: create a session, redirect, and wait for the callback.
  • Never trust the browser return; trust only a verified server-to-server callback.
  • Verify the HMAC of the raw body with hash_equals(), include a timestamp, and reject old messages.
  • Check the amount, de-duplicate with a unique event id inside one transaction, and answer 200 for anything understood.
  • Map gateway outcomes to configurable order statuses, and ignore transitions that do not make sense.
  • Start refunds from the admin with permission checks and an idempotency key, and let the signed callback change the status.

Next: Project: Product Badge Module with Events