Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 30 ยท Projects

Project: A Simple Payment Gateway Module

Build a redirect-style PrestaShop payment module: a payment option, redirect and return, signed webhook verification and safe order creation, with runnable stand-ins.

A payment module is where a PrestaShop module becomes serious. It shows a payment option at checkout, sends the customer to an external payment page, receives the result, and only then creates the order. Mistakes here cost real money: orders marked as paid that were not, or customers charged twice. This project builds a redirect-style gateway called acmepay and concentrates on the rules that keep it correct.

You should know payment modules and the shared theory in Payments Overview, Webhooks and Signatures and Idempotency. PrestaShop and a real payment provider cannot run on this site, so the PrestaShop code below is read-only. The runnable parts are plain-PHP stand-ins: a fake gateway, a fake shop and the same signature and idempotency logic you would use for real. "Acme Pay" is an invented provider, so its API is made up for teaching.

The flow

sequenceDiagram
    participant C as Customer
    participant S as Shop (module)
    participant G as Gateway
    C->>S: Chooses Acme Pay at checkout
    S->>G: Create payment (cart id, amount, return URL)
    G-->>S: Payment id + hosted page URL
    S-->>C: Redirect to hosted page
    C->>G: Pays
    G->>S: Webhook: payment.succeeded (signed)
    S->>S: Verify signature, create order once
    G-->>C: Redirect back to shop
    C->>S: Return page shows the order

The webhook, not the browser return, decides whether the order is paid: customers close tabs.

The design choices behind the diagram:

  • The browser return is not proof of payment. Anyone can open the return URL. Only the signed server-to-server webhook counts.
  • The order is created after confirmed payment (or in a "waiting for payment" state, if you want a record earlier). Choose one policy and keep it consistent.
  • Everything the webhook does must be safe to repeat, because providers resend webhooks.

Step 1: the module and the payment option

The module class extends PaymentModule, not Module. It registers two hooks. paymentOptions returns the choices shown at checkout, and paymentReturn renders the confirmation block.

PHP
<?php
use PrestaShop\PrestaShop\Core\Payment\PaymentOption;

if (!defined('_PS_VERSION_')) {
    exit;
}

class AcmePay extends PaymentModule
{
    public function __construct()
    {
        $this->name = 'acmepay';
        $this->tab = 'payments_gateways';
        $this->version = '1.0.0';
        $this->author = 'Acme';
        $this->need_instance = 0;
        $this->ps_versions_compliance = ['min' => '8.0.0', 'max' => _PS_VERSION_];
        $this->currencies = true;
        $this->currencies_mode = 'checkbox';
        parent::__construct();

        $this->displayName = $this->trans('Acme Pay', [], 'Modules.Acmepay.Admin');
        $this->description = $this->trans('Pay on the Acme Pay hosted page.', [], 'Modules.Acmepay.Admin');
    }

    public function install(): bool
    {
        return parent::install()
            && $this->registerHook('paymentOptions')
            && $this->registerHook('paymentReturn')
            && Db::getInstance()->execute(
                'CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'acmepay_payment` (
                    `payment_id` VARCHAR(64) NOT NULL,
                    `id_cart` INT UNSIGNED NOT NULL,
                    `status` VARCHAR(16) NOT NULL,
                    `id_order` INT UNSIGNED NULL,
                    PRIMARY KEY (`payment_id`)
                ) ENGINE=' . _MYSQL_ENGINE_ . ' DEFAULT CHARSET=utf8mb4'
            );
    }

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

        $option = new PaymentOption();
        $option->setModuleName($this->name)
            ->setCallToActionText($this->trans('Pay with Acme Pay', [], 'Modules.Acmepay.Shop'))
            ->setAction($this->context->link->getModuleLink($this->name, 'redirect', [], true))
            ->setAdditionalInformation(
                '<p>' . $this->trans('You will be redirected to a secure payment page.', [], 'Modules.Acmepay.Shop') . '</p>'
            );

        return [$option];
    }

    private function checkCurrency(Cart $cart): bool
    {
        $currency = new Currency((int) $cart->id_currency);
        foreach ($this->getCurrency((int) $cart->id_currency) as $allowed) {
            if ($currency->id == $allowed['id_currency']) {
                return true;
            }
        }
        return false;
    }
}

Returning an empty array hides the option, which is how you respect the module's enabled state and its currency restrictions. The table acmepay_payment is the module's memory: one row per payment attempt, keyed by the provider's payment id. It is what makes the webhook idempotent later.

Step 2: redirect to the hosted page

The option's action points at a front controller. It validates the cart, asks the provider to create a payment, stores the attempt, and redirects.

PHP
<?php
class AcmePayRedirectModuleFrontController extends ModuleFrontController
{
    public function postProcess(): void
    {
        $cart = $this->context->cart;
        if (!Validate::isLoadedObject($cart) || $cart->nbProducts() < 1
            || $cart->id_customer == 0 || $cart->id_address_delivery == 0) {
            Tools::redirect('index.php?controller=order&step=1');
        }

        $amountInCents = (int) round($cart->getOrderTotal(true, Cart::BOTH) * 100);
        $currency = new Currency((int) $cart->id_currency);

        $payment = $this->module->gatewayClient()->createPayment([
            'reference' => 'cart-' . (int) $cart->id,
            'amount' => $amountInCents,
            'currency' => $currency->iso_code,
            'return_url' => $this->context->link->getModuleLink($this->module->name, 'return', [
                'id_cart' => (int) $cart->id,
                'key' => $this->context->customer->secure_key,
            ], true),
        ]);

        Db::getInstance()->insert('acmepay_payment', [
            'payment_id' => pSQL($payment['id']),
            'id_cart' => (int) $cart->id,
            'status' => 'pending',
        ]);

        Tools::redirect($payment['hosted_url']);
    }
}

gatewayClient() is your own helper that wraps the provider's HTTP API; it is not part of PrestaShop. Two points to notice. The amount is sent as integer minor units (cents), which avoids floating point surprises (Money as Integers). And the amount comes from the cart on the server, never from a form field the customer could edit.

A stand-in for the gateway and the redirect

This first stand-in has a fake provider that creates payments and signs webhook bodies, plus a "shop" that handles the redirect step. Nothing here talks to a network.

PHP Creating a payment and redirecting

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.

Step 3: the webhook decides

The provider calls a second front controller, webhook. It must not use cookies or the customer session: the request comes from the provider's server, so there is no logged-in customer and no cart in the context. The controller reads the raw body, verifies the signature, ignores repeats and creates the order.

PHP
<?php
class AcmePayWebhookModuleFrontController extends ModuleFrontController
{
    public $auth = false;
    public $ssl = true;

    public function postProcess(): void
    {
        $body = (string) file_get_contents('php://input');
        $sent = (string) ($_SERVER['HTTP_X_ACMEPAY_SIGNATURE'] ?? '');
        $expected = hash_hmac('sha256', $body, Configuration::get('ACMEPAY_WEBHOOK_SECRET'));

        if (!hash_equals($expected, $sent)) {
            http_response_code(400);
            exit('invalid signature');
        }

        $event = json_decode($body, true);
        if (($event['type'] ?? '') !== 'payment.succeeded') {
            http_response_code(200);
            exit('ignored');
        }

        $db = Db::getInstance();
        $paymentId = pSQL($event['payment_id']);
        $row = $db->getRow(
            'SELECT * FROM `' . _DB_PREFIX_ . 'acmepay_payment` WHERE payment_id = "' . $paymentId . '"'
        );

        if (!$row) {
            http_response_code(404);
            exit('unknown payment');
        }
        if ($row['status'] === 'paid') {
            http_response_code(200);
            exit('already processed');
        }

        $cart = new Cart((int) $row['id_cart']);
        $expectedCents = (int) round($cart->getOrderTotal(true, Cart::BOTH) * 100);
        if ($expectedCents !== (int) $event['amount']) {
            http_response_code(409);
            exit('amount mismatch');
        }

        $customer = new Customer((int) $cart->id_customer);
        $this->module->validateOrder(
            (int) $cart->id,
            (int) Configuration::get('PS_OS_PAYMENT'),
            $cart->getOrderTotal(true, Cart::BOTH),
            $this->module->displayName,
            null,
            ['transaction_id' => $event['payment_id']],
            (int) $cart->id_currency,
            false,
            $customer->secure_key
        );

        $db->update('acmepay_payment', [
            'status' => 'paid',
            'id_order' => (int) $this->module->currentOrder,
        ], 'payment_id = "' . $paymentId . '"');

        http_response_code(200);
        exit('ok');
    }
}

Each guard answers a real danger:

Guard What it stops
Signature with hash_equals Anyone on the internet posting a fake "paid" message
Event type check Failure or refund events creating orders
Lookup of our own payment row Webhooks for payments this shop never started
status === 'paid' Duplicate deliveries creating two orders
Amount comparison A cart changed after payment started, or a tampered amount

validateOrder is the PrestaShop method of PaymentModule that creates the order, sends the confirmation email and moves stock. It takes the cart id, an order state id, the paid amount, the payment name, an optional message, extra variables (the transaction_id shows on the order's payment), the currency id, a flag about amounts, and the customer's secure key. Always confirm the parameter order in your version. A production module also needs a lock or a unique constraint so two simultaneous deliveries cannot both pass the "not paid yet" check; the unique payment_id key and an UPDATE ... WHERE status = 'pending' that checks the affected row count are common ways to do that.

A stand-in webhook handler

The second stand-in runs the same guards against SQLite. It sends a valid event, the same event again, a forged one, and one with the wrong amount, then prints how each was handled and how many orders exist.

PHP Verifying and applying webhooks safely

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.

Six deliveries, exactly one order. The conditional UPDATE ... WHERE status = 'pending' inside a transaction is the "claim": whichever request changes the row owns the work, which is the pattern from Idempotency.

Step 4: the return page

When the customer comes back, the module's return controller must not trust the URL. It only looks up what the webhook already did.

PHP
<?php
class AcmePayReturnModuleFrontController extends ModuleFrontController
{
    public function postProcess(): void
    {
        $idCart = (int) Tools::getValue('id_cart');
        $key = (string) Tools::getValue('key');

        $row = Db::getInstance()->getRow(
            'SELECT id_order FROM `' . _DB_PREFIX_ . 'acmepay_payment`
             WHERE id_cart = ' . $idCart . ' AND status = "paid"'
        );
        $customer = new Customer((int) $this->context->cart->id_customer);

        if ($row && $row['id_order'] && hash_equals((string) $customer->secure_key, $key)) {
            Tools::redirect('index.php?controller=order-confirmation&id_cart=' . $idCart
                . '&id_module=' . (int) $this->module->id
                . '&id_order=' . (int) $row['id_order']
                . '&key=' . urlencode($key));
        }

        // webhook not processed yet, or payment failed: show a waiting or failed page
        Tools::redirect('index.php?controller=order&step=1');
    }
}

The webhook can arrive a moment after the browser. A friendly module shows a "we are confirming your payment" page that checks again in a few seconds instead of sending the customer back to checkout, which would look like a failure. The stand-in below sketches that decision.

PHP Return page: paid, waiting or failed

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.

Production checklist

  • Store the webhook secret and API keys in Configuration values edited on the configuration page, never in the code. Mask the secret when it is displayed again.
  • Offer a test mode that points to the provider's sandbox, and show it clearly in the back office.
  • Handle refunds: a back office action or a payment.refunded webhook that moves the order to the refunded state. See Authorize, Capture and Refund.
  • Log every webhook with its event id and result, but never log card data or secrets. Card details must never reach your server in a redirect design; see PCI and 3-D Secure.
  • Test the unhappy paths from the tables above in a test shop before going live.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is the signed webhook, not the browser return page, the source of truth for payment?

    A return URL proves nothing about money. A signed server-to-server message from the provider does.
  2. 2. What makes handling the same webhook twice safe in the stand-in?

    Only the request that changes the status owns the work, so repeats see "paid" and do nothing.
  3. 3. Why compare the webhook amount with the cart total?

    If the amounts differ, something is wrong, so the order is not created automatically.
  4. 4. Why send the amount in cents?

    Integer minor units make both sides compare exact values.

Summary

  • A payment module extends PaymentModule, returns PaymentOption objects from hookPaymentOptions and creates orders with validateOrder.
  • In the redirect design, the amount comes from the server-side cart and is sent as integer cents.
  • A webhook controller verifies an HMAC signature with hash_equals, checks the event type, finds its own payment row, compares the amount and creates the order exactly once.
  • The return page only reads what the webhook did and handles the "not confirmed yet" case kindly.
  • Keep secrets in configuration, support a test mode and test failure paths before going live.

Now test what you have learned: Practice Exercises with Solutions.