# OpenCart Payment Module: Form, Callback and Payment Confirmation in 3.0 and 4.1

> How to Write an OpenCart 3.0 and 4.1 Payment Module: getMethod/getMethods, a controller with a button or form, confirm, bank callback, signature and amount verification, and idempotency.

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

**The OpenCart payment module** consists of three parts: the model, which decides whether to show the [payment method](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#payment-method) at checkout (`getMethod()` in 3.0, `getMethods()` in 4.1), the [controller](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#controller), which renders the payment button or form at the confirmation step, and the response handler: `confirm()` for offline methods or `callback()` for online payment. In all cases the result is the same: a call to `addOrderHistory()` (in 4.1, `addHistory()`) with the status from the module settings.

Below is how this is organized in OpenCart 3.0 (3.0.4.1 and 3.0.5.1) and 4.1 (4.1.0.4), using core modules as examples, and which callback checks you must not skip. The examples are for OpenCart 4.1; in 4.0.x, model triggers and event handling differ.

## Which files make up a payment module?

The simplest example in both branches is the core module `cod` ([cash on delivery](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#cash-on-delivery)). For online payment, 3.0 also has modules with a callback, for example `liqpay`; in 4.1, the core still includes only `bank_transfer`, `cheque`, `cod`, and `free_checkout`.

| Part | OpenCart 3.0 | OpenCart 4.1 |
| --- | --- | --- |
| Admin settings | `admin/controller/extension/payment/{code}.php` | `extension/{ext}/admin/controller/payment/{code}.php` (methods `index`, `save`) |
| Storefront model | `catalog/model/extension/payment/{code}.php`, method `getMethod($address, $total)` | `extension/{ext}/catalog/model/payment/{code}.php`, method `getMethods(array $address = []): array` |
| Storefront controller | `catalog/controller/extension/payment/{code}.php` | `extension/{ext}/catalog/controller/payment/{code}.php` |
| Button template | `catalog/view/theme/default/template/extension/payment/{code}.twig` | `extension/{ext}/catalog/view/template/payment/{code}.twig` |
| Callback route | `extension/payment/{code}/callback` | `extension/{ext}/payment/{code}.callback` |

Settings are stored in the `setting` table with the `payment_{code}_` prefix: `payment_{code}_status`, `payment_{code}_sort_order`, `payment_{code}_geo_zone_id`, `payment_{code}_order_status_id`, and your own keys (merchant, secret). How to build the form and save these values is described in the articles [OpenCart extension anatomy](https://opencartcode.com/en/wiki/dev-extensions/opencart-module-structure) and [module settings form](https://opencartcode.com/en/wiki/dev-extensions/module-settings-form-opencart).

Extensions → Payments: module installation, status and sort order · OpenCart 4.1.0.4

## How does the model decide whether to show the payment method?

At the payment selection step, the core goes through all enabled payment [extensions](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#extensions) (`payment_{code}_status`) and calls their model. An empty array means "this method is currently unavailable."

**OpenCart 3.0:** `getMethod($address, $total)` receives the payment address and the order total already calculated by the chain of total modules, and returns a single array with the keys `code`, `title`, `terms`, `sort_order`. If the cart contains items with recurring payments, the core additionally requires the model to have the method `recurringPayments()`, which returns `true`.

**OpenCart 4.1:** `getMethods(array $address = [])` does not receive the total; it returns the method with nested options under the key `option`. The option code has the form `{code}.{підкод}`, and this is exactly what the core then places into `session->data['payment_method']['code']`.

Example: getMethods for online payment · OpenCart 4.1

```php
namespace Opencart\Catalog\Model\Extension\Mypay\Payment;
class Mypay extends \Opencart\System\Engine\Model {
	public function getMethods(array $address = []): array {
		$this->load->language('extension/mypay/payment/mypay');

		$status = true;

		if ($this->cart->hasSubscription()) {
			$status = false;
		}

		$min = (float)$this->config->get('payment_mypay_total');

		if ($min > 0 && $this->cart->getTotal() < $min) {
			$status = false;
		}

		if (!$status) {
			return [];
		}

		return [
			'code'       => 'mypay',
			'name'       => $this->language->get('heading_title'),
			'option'     => [
				'mypay' => [
					'code' => 'mypay.mypay',
					'name' => $this->language->get('text_card')
				]
			],
			'sort_order' => $this->config->get('payment_mypay_sort_order')
		];
	}
}
```

Here `cart->getTotal()` is the sum of products with taxes, without shipping or discounts; if the threshold should account for totals, calculate them via the `checkout/cart` model. In 4.1, geo zone restrictions are handled via `model_localisation_geo_zone->getGeoZone()`, as in the `cod` module. Note that in 4.1 the payment address can be disabled (`config_checkout_payment_address`), in which case `$address` is empty.

## Payment form at the confirmation step

When the checkout session is complete, `checkout/confirm` creates an order with status 0 and embeds the output of the selected payment module's controller: `$this->load->controller('extension/payment/' . $code)` in 3.0, `'extension/' . $extension . '/payment/' . $code` in 4.1. Your controller's `index()` method must *return* HTML, not output it. How the order is created, and why the number must be taken from the session at that exact moment, is covered in the article [checkout in code](https://opencartcode.com/en/wiki/dev-flows/checkout-opencart-kod).

There are two typical scenarios:

- **Offline or "confirm and pay later"** (cash on delivery, bank transfer): the button makes an AJAX request to `confirm()`, which checks the session, calls the history method with the module status, and returns `redirect` to `checkout/success`.
- **Online payment**: `index()` takes the order from `session->data['order_id']`, builds a request to the [payment system](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#payment-system) (amount, currency, number, return URL, and callback URL), and renders a form with a redirect or a widget. The status is not set by this page but by the callback.

The `cod` module in 4.1 shows a full check in `confirm()`: the order exists, the payment method in the session is exactly `cod.cod`, and only then `addHistory()` with the status `payment_cod_order_status_id`. Checking the payment method code is mandatory: without it, anyone can call `confirm` of your module, choose a different method at checkout, and get an order in "paid" status. Format controller responses as JSON following the rules from [AJAX in OpenCart](https://opencartcode.com/en/wiki/dev-mvc/ajax-opencart).

Example: calculating the amount for the payment system · both branches

```php
$order_info = $this->model_checkout_order->getOrder((int)$this->session->data['order_id']);

// Сума у валюті замовлення, без форматування
$amount = $this->currency->format($order_info['total'], $order_info['currency_code'], $order_info['currency_value'], false);
```

`order.total` is stored in the store's base currency, so before sending it you must convert it to the order currency using the rate fixed at checkout (`currency_value`). The fourth argument of `false` disables formatting and returns a number. If the payment system accepts only hryvnias and the store allows other currencies, convert explicitly to UAH and show the customer how much will be charged.

## How to write a secure callback

A callback is a request from the payment system's server, not from the customer's browser. It has **no customer session**, so the order number is taken only from the request data, and that data can be trusted only after the signature is verified. Look at the core 3.0 module `liqpay`: its `callback()` verifies the signature and calls `addOrderHistory()` with the status `config_order_status_id`, but it does not check the payment status in the response or the amount. For your own module, this is not enough.

1. **Read the raw request body.** The `Request` class in both branches passes `$_POST` through `htmlspecialchars()`, so `$this->request->post` may differ from what the payment system signed. For signature verification, take `file_get_contents('php://input')` or `$_POST` directly.
2. **Verify the signature** using the secret from the settings and `hash_equals()`, not `==`.
3. **Find the order** by the number from the request. `getOrder()` returns `false` in 3.0 and `[]` in 4.1 if the order does not exist.
4. **Check the payment status** in the response: success, refusal, pending, refund. These are different order statuses, or none at all.
5. **Match the amount and currency** against the order (taking `currency_value` into account), and match the order's payment method against your module.
6. **Be idempotent.** If the order is already in a paid status, change nothing. The callback often arrives more than once.
7. **Call the history method** with the status from the module settings, and respond to the payment system as it requires (usually HTTP 200 with a short body).

Example: callback · OpenCart 4.1

```php
public function callback(): void {
	$raw  = (string)file_get_contents('php://input');
	$data = json_decode($raw, true) ?: [];

	$secret    = (string)$this->config->get('payment_mypay_secret');
	$signature = (string)($this->request->server['HTTP_X_SIGNATURE'] ?? '');

	if (!$secret || !hash_equals(hash_hmac('sha256', $raw, $secret), $signature)) {
		http_response_code(403);
		return;
	}

	$this->load->model('checkout/order');

	$order_info = $this->model_checkout_order->getOrder((int)($data['order_id'] ?? 0));

	if (!$order_info || ($order_info['payment_method']['code'] ?? '') != 'mypay.mypay') {
		http_response_code(404);
		return;
	}

	$expected = $this->currency->format($order_info['total'], $order_info['currency_code'], $order_info['currency_value'], false);

	$paid_status_id = (int)$this->config->get('payment_mypay_order_status_id');

	if (($data['status'] ?? '') == 'success'
		&& abs((float)($data['amount'] ?? 0) - (float)$expected) < 0.01
		&& ($data['currency'] ?? '') == $order_info['currency_code']
		&& (int)$order_info['order_status_id'] != $paid_status_id) {
		$this->model_checkout_order->addHistory((int)$order_info['order_id'], $paid_status_id, 'Transaction ' . ($data['transaction_id'] ?? ''), true);
	}

	$this->response->setOutput('OK');
}
```

The signature format, field names, and expected response are made up for this example; take them from your payment system's documentation. In 3.0 the structure is the same, but `payment_method` in the order is a string with the name, the code is in `$order_info['payment_code']`, the route is `extension/payment/mypay/callback`, and the history method is `addOrderHistory()`.

> The callback URL must open without authorization and without redirects. Check that it is not blocked by maintenance mode, bot protection, Basic Auth on a test domain, or a redirect from `http` to `https`: many payment systems do not follow redirects and simply treat the callback as failed.

## What happens after the callback

The history method does the rest: when moving to a status from the processing group, it deducts stock and confirms coupons and rewards, and the event handler sends the customer a confirmation email at the first non-zero status. For details, see the article about [addOrderHistory](https://opencartcode.com/en/wiki/dev-flows/addorderhistory-opencart).

Meanwhile, the customer returns from the payment page to the return URL. This is usually `checkout/success`, which clears the cart and the checkout session, but only if `order_id` is in the session. Two consequences:

- Do not change the status on the return page. The customer may not return, and URL parameters are easy to forge. The status comes only from a verified callback.
- If the customer returns before the callback arrives, the success page will show "thank you," but the order will still be in status 0. This is normal. If the callback never arrives, the order will remain in "Missing Orders."

For a payment refusal, send the customer to `checkout/failure` or back to checkout: the cart is not cleared, so they can try again. If the payment went through but the status did not change, the diagnostic steps are described in the article [order status after payment](https://opencartcode.com/en/wiki/payments/order-status-not-updating-after-payment). For an overview of Ukrainian payment solutions, see the blog: [card payment in OpenCart](https://opencartcode.com/en/blog/oplata-kartkoiu-v-opencart-moduli-dlia-ukrayini).

## Summary

- The module consists of a model (`getMethod` in 3.0, `getMethods` with `option` and the code `code.підкод` in 4.1), a controller with a button or form, and a handler `confirm` or `callback`.
- The controller's `index()` returns HTML; take the amount for the payment system from `order.total`, recalculated via `currency_value`.
- In `confirm()`, check that the session has your payment method selected.
- There is no session in the callback: verify the signature over the raw body, the payment status, the amount, the currency, and the order's payment method, and do not change an order that is already paid.
- Set the status only through the history method of the catalog model, never with a direct `UPDATE`, and never on the return page.

Other materials on the cart, checkout, and orders are on the section page [Cart, checkout and orders in code](https://opencartcode.com/en/wiki/dev-flows).

## FAQ

**How do I test a callback on my local machine?**

The payment system must reach your server, so you need a public URL: a test domain or a tunnel to your local server. Additionally, save a few real callback bodies from test mode and replay them with curl using the same signature.

**Can I accept a partial payment for an order?**

OpenCart does not track the paid amount separately from order.total by default. If the payment system confirmed a smaller amount, do not set the payment status automatically. Instead, add a comment to the history and leave the decision to the manager.

**Why does the module settings need a separate order status?**

The module passes this status to the history method after a successful payment. It must be in the processing status group, otherwise stock will not be deducted and the coupon will not be marked as used.

**What should I do about a refund initiated in the payment system's dashboard?**

If the system sends a refund callback, move the order to the refund or cancellation status via the history method. A status outside the processing groups will return stock and cancel the coupon usage.
