Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 27 ยท Extension types

Building a Payment Extension

Build an OpenCart 4 payment extension: files, getMethods and the method array, the confirm step, order status updates, signed callbacks, geo zones and idempotency.

A payment extension is the most sensitive thing you can write for a store. It sits between the customer's cart and their money, it decides when an order counts as paid, and it receives messages from outside the shop that anybody on the internet could try to forge. It is also very regular: almost every payment extension has the same five parts, and once you know them you can read any gateway integration.

This lesson walks through those parts: the files, the model that says whether the method is available for this cart, the confirm step, the order status updates, and the callback that the gateway sends when a payment finishes. Real OpenCart code is read-only here because it needs a running store. The runnable stand-ins are plain PHP: one checks availability the way a payment model does, the other simulates a gateway that sends signed callbacks. The money-handling ideas are shared with every shop, so see Payments Overview, Webhooks and Signature Verification and Idempotency for the theory.

The files

A payment extension from vendor acme named gateway has these parts:

TEXT
extension/acme/admin/controller/payment/gateway.php       settings form, install
extension/acme/admin/view/template/payment/gateway.twig
extension/acme/admin/language/en-gb/payment/gateway.php
extension/acme/catalog/controller/payment/gateway.php     checkout button, confirm, callback
extension/acme/catalog/model/payment/gateway.php          getMethods()
extension/acme/catalog/view/template/payment/gateway.twig
extension/acme/catalog/language/en-gb/payment/gateway.php

The admin side is a normal settings form whose keys start with payment_gateway_: status, sort order, geo zone, minimum total, the order status to use, and secrets such as an API key and a webhook secret. The settings page appears under Extensions, Payments after install.

getMethods: is this method available?

At checkout, OpenCart asks every enabled payment extension whether it can serve the current cart and address. In 4.0.2 and later the question is the model method getMethods(array $address): array. Earlier 4.0.x releases used a method with a different name and signature, so check the shipped payment extensions of your version (for example the bank transfer one) and mirror them.

The method returns an empty array when the extension is not available, or an array describing the method:

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

class Gateway extends \Opencart\System\Engine\Model {
    public function getMethods(array $address = []): array {
        $this->load->language('extension/acme/payment/gateway');

        $status = true;
        $minimum = (float)$this->config->get('payment_gateway_total');

        if ($minimum > 0 && $this->cart->getSubTotal() < $minimum) {
            $status = false;
        } elseif ($this->cart->hasSubscription()) {
            $status = false;
        } elseif ($this->config->get('payment_gateway_geo_zone_id')) {
            $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone_to_geo_zone`
                WHERE `geo_zone_id` = '" . (int)$this->config->get('payment_gateway_geo_zone_id') . "'
                AND `country_id` = '" . (int)$address['country_id'] . "'
                AND (`zone_id` = '" . (int)$address['zone_id'] . "' OR `zone_id` = '0')");

            $status = (bool)$query->num_rows;
        }

        $method_data = [];

        if ($status) {
            $option_data['gateway'] = [
                'code' => 'gateway.gateway',
                'name' => $this->language->get('heading_title')
            ];

            $method_data = [
                'code'       => 'gateway',
                'name'       => $this->language->get('heading_title'),
                'option'     => $option_data,
                'sort_order' => $this->config->get('payment_gateway_sort_order')
            ];
        }

        return $method_data;
    }
}

Three rules sit in this method: a minimum total (hide the method for small carts), a geo zone (zone 0 means everywhere; otherwise the shipping or payment address must fall into the zone, with zone_id = 0 meaning "all regions of that country"), and unsupported cart contents such as subscriptions. The returned option array lets one extension offer several choices (card and wallet, for example), each with its own code in the form extension_code.option_code. The customer's choice is stored in the session and later saved with the order. Note the (int) casts: the address values come from the customer, so they must never go into SQL as they are (see Security for Extension Developers).

Redirect or on-site

There are two common integration styles.

  • Redirect (hosted checkout). The confirm step sends the customer to the gateway's page, where they enter card details. Your shop never sees the card number, which keeps PCI scope small. The gateway later sends the customer back and also sends a server-to-server callback.
  • On-site. Card fields are rendered on your page, usually by scripts provided by the gateway so that the card data goes straight to the gateway. Your server receives only a token.

Both styles end the same way: the gateway tells your server, with a signed message, that the payment succeeded or failed. See PCI and 3-D Secure for why card data should stay off your server.

The confirm step

At the last checkout step, OpenCart loads the chosen payment method's index controller method and shows the HTML it returns, normally a Confirm button. Pressing it calls confirm:

PHP
public function index(): string {
    $this->load->language('extension/acme/payment/gateway');
    $data['confirm'] = $this->url->link('extension/acme/payment/gateway.confirm', 'language=' . $this->config->get('config_language'));
    return $this->load->view('extension/acme/payment/gateway', $data);
}

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

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

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

        // create a payment at the gateway for $order['total'] and get a redirect URL
        $json['redirect'] = $this->createPayment($order);
    }

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

For a redirect gateway, confirm creates a payment at the gateway (an API call from your server, with a timeout) and answers with the URL to send the customer to. The order already exists in the database at this point, with order status 0 ("missing order"), so it does not show in the admin order list or consume stock.

Order status updates: only from trusted events

An order moves forward with $this->model_checkout_order->addHistory($order_id, $order_status_id, $comment, $notify). That one call writes a history row, changes the status, and, depending on which statuses the store treats as processing or complete, updates stock and sends mail. Map gateway outcomes to the store's statuses in your settings page: pending, processing (paid), failed, canceled, refunded. Read the numeric ids from settings rather than hard-coding them, because merchants can create their own.

The golden rule: the customer returning to your site is not proof of payment. The browser can be sent to your "success" URL by anyone. Only a verified server-to-server callback, or a status you fetched yourself from the gateway's API, may mark an order as paid. The return page should just show a friendly message and, if the callback has not arrived yet, say that the payment is being confirmed. Read Order Lifecycle for the states involved.

sequenceDiagram
    participant C as Customer
    participant S as Shop (confirm)
    participant G as Gateway
    participant W as Shop (callback)
    C->>S: Press Confirm
    S->>G: Create payment (order 120, 49.90)
    G-->>S: Redirect URL
    S-->>C: Redirect
    C->>G: Pays on the hosted page
    G->>W: Signed callback "payment.succeeded"
    W->>W: Verify signature, amount, duplicate?
    W->>W: addHistory(paid status)
    G-->>C: Redirect back to the shop

The shop trusts the signed callback, not the customer's return. The two can arrive in either order.

The callback

The gateway calls a URL on your shop, for example index.php?route=extension/acme/payment/gateway.callback. Such a request has no session, no cookies and no user_token; it is an API call from another server. A safe callback does these things in this order:

  1. Read the raw body with file_get_contents('php://input') and the signature header. Do not decode it first, because you must hash the exact bytes.
  2. Verify the signature: compute an HMAC of the body (and a timestamp) with the shared secret, and compare with hash_equals to avoid timing leaks. Reject old timestamps to stop replays. If anything fails, answer with a 4xx and do nothing else.
  3. Find the order by your own reference and check the amount and currency match the order. A callback for a different amount must not mark the order as paid.
  4. Deduplicate by event id. Gateways retry on timeouts, so the same event can arrive twice. Record each processed event id in a table with a unique key and ignore repeats. This is the idea from Idempotency.
  5. Check the transition. A late "pending" event must not move an order that is already paid backwards.
  6. Answer quickly with a 2xx once the event is stored, and do slow work later.

Keep the secret in settings, never in the Twig template or in JavaScript, and do not log it.

Try it: availability rules

This stand-in imitates the getMethods logic: minimum total, geo zone rows with zone_id = 0 as "whole country", and the method array. It is not OpenCart's model class, but the decision order is the same.

PHP getMethods: minimum total and geo zones

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.

Only carts that meet the minimum and whose address falls in the geo zone get a method array. An empty array means "not available", and OpenCart simply leaves the method out of the list.

The second stand-in is a gateway simulator and a callback handler. The gateway signs each event with HMAC-SHA256 and a timestamp; the shop verifies, checks the amount, ignores duplicates and refuses to move an order backwards. Time is passed in as a number so the run is repeatable.

PHP Signed callbacks, duplicates and order status

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.

Only one callback changes the order. The retry is a duplicate, the tampered body and wrong secret fail the signature, the replay fails the timestamp, the late "pending" event cannot undo the payment, and the wrong amount is flagged instead of trusted. The whsec_demo_only secret is a made-up demo value; real secrets belong in the extension settings.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What should getMethods return when the payment method is not available for the cart?

    An empty array means the method is left out of the list shown to the customer. Otherwise it returns the method array with code, name, option and sort_order.
  2. 2. A customer is redirected to your success URL after paying. May you mark the order as paid at that moment?

    Anybody can open the success URL. The order status may change only after a signed callback or your own authenticated API check confirms the payment.
  3. 3. Why is hash_equals used to compare the signatures?

    A normal comparison can stop at the first different character. hash_equals takes the same time regardless, which prevents timing attacks on the signature.
  4. 4. The gateway retries a callback because your server was slow. What protects you from processing the payment twice?

    Retries are normal. Deduplicating on the event id makes the handler idempotent, so the second delivery changes nothing.
  5. 5. What does zone_id = 0 in a zone_to_geo_zone row mean?

    A zero zone id acts as a wildcard for the whole country, which is why the query accepts either the customer's zone or 0.

Summary

  • A payment extension has an admin settings form, a catalog controller (button, confirm, callback), a catalog model with getMethods, and Twig and language files.
  • getMethods returns an empty array when the method is unavailable: below the minimum total, outside the geo zone, or unsupported cart content.
  • Hosted checkout redirects the customer and keeps card data away from your server; on-site checkout only handles tokens.
  • Only a verified callback or your own API check may change an order to paid, using addHistory with a configurable status.
  • A safe callback verifies an HMAC over the raw body with a timestamp, checks amount and order, deduplicates by event id and refuses backward status moves.
  • Keep secrets in settings and out of templates and logs.

Next, see how shipping methods quote prices in Building a Shipping Extension.