Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 30 ยท APIs and Integrations

Payment Modules

Build a PrestaShop payment module the right way: PaymentModule, hookPaymentOptions, PaymentOption, validateOrder, return pages and idempotent webhooks, with a runnable stand-in.

A payment module is the part of a PrestaShop store that decides how a customer pays and, just as important, when an order is allowed to exist. It offers one or more payment choices on the checkout page, sends the customer to a payment provider (or collects the payment details itself), and finally turns the cart into an order with the right order state. Get this wrong and you create unpaid orders, double orders, or orders with the wrong amount.

This lesson walks through the moving parts of a payment module: the PaymentModule base class, the PaymentOption objects returned by a hook, the validation controller that calls validateOrder(), the return page, and the webhook that confirms payment from the provider's server. The theory behind payments (authorize and capture, 3-D Secure, retries) lives in the e-commerce track, see Payments Overview and Idempotency; here we focus on how PrestaShop wires it together.

Real PrestaShop code needs a running shop, so it is shown in read-only blocks. The runnable examples are stand-ins: small plain-PHP classes with the same names and shape, so you can watch the flow work. They are not PrestaShop itself, and the lesson says which is which.

The flow at a glance

sequenceDiagram
    participant C as Customer
    participant S as Shop (your module)
    participant P as Payment provider
    C->>S: Checkout page (hookPaymentOptions)
    C->>S: Click "Pay" (validation or redirect controller)
    S->>P: Create payment for the cart
    P-->>C: Hosted payment page
    C->>S: Return URL (customer is back)
    P->>S: Webhook "payment succeeded"
    S->>S: validateOrder() once

The customer returning to your site is not proof of payment; the signed webhook is.

The module class

A payment module extends PaymentModule instead of Module. PaymentModule extends Module, so everything from Anatomy of a Module still applies, and it adds payment features such as validateOrder(), the list of allowed currencies and per-module country, group and carrier restrictions that the back office manages on the Payment preferences pages.

PHP
<?php
if (!defined('_PS_VERSION_')) {
    exit;
}

use PrestaShop\PrestaShop\Core\Payment\PaymentOption;

class Demopay extends PaymentModule
{
    public function __construct()
    {
        $this->name = 'demopay';
        $this->tab = 'payments_gateways';
        $this->version = '1.0.0';
        $this->author = 'Acme';
        $this->ps_versions_compliance = ['min' => '8.0.0', 'max' => _PS_VERSION_];
        $this->currencies = true;
        $this->currencies_mode = 'checkbox';
        $this->bootstrap = true;

        parent::__construct();

        $this->displayName = $this->trans('Demo Pay', [], 'Modules.Demopay.Admin');
        $this->description = $this->trans('Accept payments through Demo Pay.', [], 'Modules.Demopay.Admin');
    }

    public function install()
    {
        return parent::install()
            && $this->registerHook('paymentOptions')
            && $this->registerHook('paymentReturn');
    }
}

The two lines currencies = true and currencies_mode = 'checkbox' tell PrestaShop that this module has a per-currency setting, so the shop owner can choose which currencies it accepts. The payments_gateways tab places the module in the payment category of the module manager.

Offering payment options

The hook paymentOptions runs on the checkout payment step. Your hook method returns an array of PaymentOption objects, one per choice you want to show, or an empty array to show nothing. Always return early when the module is inactive or the cart currency is not allowed. checkCurrency() is a small helper that most payment modules copy from the example modules: it compares the cart's currency with the currencies enabled for the module.

PHP
public function hookPaymentOptions($params)
{
    if (!$this->active || !$this->checkCurrency($params['cart'])) {
        return [];
    }

    $option = new PaymentOption();
    $option->setModuleName($this->name)
        ->setCallToActionText($this->trans('Pay by card', [], 'Modules.Demopay.Shop'))
        ->setAction($this->context->link->getModuleLink($this->name, 'redirect', [], true))
        ->setAdditionalInformation($this->fetch('module:demopay/views/templates/hook/info.tpl'));

    return [$option];
}

The setters you will use most:

Method Purpose
setCallToActionText() The label of the option on the checkout page
setAction() The URL the form posts to (usually a module front controller)
setForm() Extra HTML form markup, for fields shown in the option
setInputs() Hidden inputs added to the generated form
setAdditionalInformation() HTML shown when the option is selected
setLogo() A logo next to the label
setModuleName() Identifies which module the option belongs to

The true in getModuleLink() asks for an HTTPS URL, which payment steps should always use. Controllers are covered in Module Front Controllers.

Here is a stand-in that mimics the shape: a base class with checkCurrency(), a fluent PaymentOption, and a hook that returns options only when the cart can be paid in this module.

PHP Stand-in: building payment options

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.

What is real here: the hook name, PaymentOption and its setters, checkCurrency() as a pattern. What is a stand-in: the cart class, the currency list and the whole class hierarchy.

Creating the order with validateOrder

The order must be created by exactly one trusted code path. In a redirect-style module that is usually a front controller extending ModuleFrontController, and the call you make is validateOrder() on your module. Its first parameters are the cart id, the order state id, the amount paid, and a payment method name shown in the order. Further parameters carry a customer message, extra variables such as a transaction id, a currency override and the cart's secure key. Always pass the customer's secure_key, because the confirmation page uses it to verify access.

PHP
class DemopayValidationModuleFrontController extends ModuleFrontController
{
    public function postProcess()
    {
        $cart = $this->context->cart;

        if ($cart->id_customer == 0 || $cart->id_address_delivery == 0
            || $cart->id_address_invoice == 0 || !$this->module->active) {
            Tools::redirect('index.php?controller=order&step=1');
        }

        $customer = new Customer($cart->id_customer);
        if (!Validate::isLoadedObject($customer)) {
            Tools::redirect('index.php?controller=order&step=1');
        }

        $this->module->validateOrder(
            (int) $cart->id,
            (int) Configuration::get('PS_OS_PAYMENT'),
            (float) $cart->getOrderTotal(true, Cart::BOTH),
            $this->module->displayName,
            null,
            ['transaction_id' => Tools::getValue('txn')],
            (int) $this->context->currency->id,
            false,
            $customer->secure_key
        );

        Tools::redirect('index.php?controller=order-confirmation&id_cart=' . (int) $cart->id
            . '&id_module=' . (int) $this->module->id
            . '&id_order=' . (int) $this->module->currentOrder
            . '&key=' . $customer->secure_key);
    }
}

Choose the order state with care. PS_OS_PAYMENT means "payment accepted", PS_OS_ERROR means a payment error, and states such as awaiting bank wire or awaiting cheque payment exist for offline methods. Never mark an order as paid because the customer landed on a return URL; that URL can be opened by anyone. The amount you pass is what PrestaShop records as paid, so compute it from the cart on the server, never from a request parameter. PrestaShop also compares the cart total with the amount you pass and, if they differ, creates the order in a "payment error" state, which is a useful safety net but not a substitute for checking the provider's reported amount yourself. For order states and money rules in general see Order Lifecycle and Working with Products, Carts and Orders.

The return page

After the order exists, the confirmation page calls your paymentReturn hook so the module can add its own message, such as the bank details for a wire transfer. The order is in $params['order']; check that it belongs to your module before showing anything.

PHP
public function hookPaymentReturn($params)
{
    if (!$this->active) {
        return '';
    }

    $order = $params['order'];
    if ($order->module !== $this->name) {
        return '';
    }

    $this->smarty->assign('reference', $order->reference);

    return $this->fetch('module:demopay/views/templates/hook/payment_return.tpl');
}

Webhooks and idempotency

Most modern providers confirm payments with a server-to-server request. The customer may close the browser before returning, and networks fail, so the webhook is the reliable signal. Your webhook controller has no customer session, so it must find the cart from an identifier you sent to the provider (the cart id in the payment metadata is common), verify the signature, check the amount, and create the order only once.

Providers deliver webhooks at least once, so the same event will sometimes arrive twice, or arrive while the customer's return request is also trying to create the order. Build in two protections:

  1. Before calling validateOrder(), check whether the cart already has an order (the Cart class offers orderExists() for this).
  2. Treat the provider's event id or transaction id as a key you remember, so a duplicate is acknowledged with a success response and then ignored.

A database transaction or lock around the check and the create closes the race between two simultaneous requests. See Webhooks and Signatures for signing details and Idempotency for the pattern.

The stand-in below plays the whole story with SQLite: a signed webhook is verified with hash_hmac, the amount is compared with the cart, and a unique key on the cart makes duplicates harmless.

PHP Stand-in: signed webhook creates one order

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.

In real PrestaShop the equivalent of the orders unique key is the check for an existing order on the cart plus your own table of processed event ids. The signature check, the amount comparison and the early returns are exactly the habits to copy.

Never put API secrets in templates, JavaScript or the module's public files. Store them with Configuration::updateValue() on the module's configuration page, and keep card data off your server entirely by using the provider's hosted fields or payment page. Card handling rules are explained in PCI and 3-D Secure.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which hook does a module use to add payment choices to the checkout page?

    The paymentOptions hook returns an array of PaymentOption objects, one per choice. paymentReturn is the separate hook for the order confirmation page.
  2. 2. A customer lands on your module's return URL. What does that prove?

    Anyone can open a URL. Only a signed webhook or a server-side status check with the provider is proof of payment.
  3. 3. Why should the webhook handler check whether the cart already has an order?

    Webhooks are delivered at least once. An idempotent handler acknowledges duplicates and creates the order only the first time.
  4. 4. Where should the amount passed to validateOrder() come from?

    Request parameters can be changed by the customer. Compute the total from the cart on the server and compare it with what the provider says it charged.

Summary

  • A payment module extends PaymentModule, registers the paymentOptions and paymentReturn hooks, and declares which currencies it supports.
  • hookPaymentOptions() returns PaymentOption objects, or an empty array when the module is inactive or the currency is not allowed.
  • validateOrder() creates the order; pass a server-computed amount, a sensible order state and the customer's secure key.
  • The return page is for the customer; the signed webhook is the proof of payment.
  • Make webhook handling idempotent: verify the signature, check the amount, and create the order only once per cart.

Next: Translations and Multilingual Modules