Custom WHMCS Payment Gateway Modules: PayU and MamoPay Integration
How I architected custom PayU and MamoPay payment gateway modules for WHMCS in PHP, covering hosted checkout signing, constant-time HMAC webhook validation, idempotency, and currency reconciliation.
Online payments sit right on the fault line of a web hosting company's billing automation. When a customer selects a VPS or shared hosting plan in a custom WHMCS order form, completes payment, and lands back on the invoice screen, WHMCS must verify authenticity, record the exact settled amount, fire AutoRelease or cPanel/Proxmox module provisioning, and email the receipt without human intervention. While WHMCS ships built-in gateways for Stripe and PayPal, regional hosting businesses across India and the Middle East frequently rely on PayU (UPI, NetBanking, RuPay, domestic/international cards) and MamoPay (UAE/MENA hosted payment links) with merchant-specific callback and currency rules that off-the-shelf plugins fail to handle cleanly.
I built two production WHMCS gateway modules from scratch in PHP: modules/gateways/payucheckout.php and modules/gateways/mamopay.php, paired with dedicated webhook listeners under modules/gateways/callback/. Below is the architecture behind both integrations, including the PHP patterns that prevent spoofed "paid" redirects, duplicate webhook credits, and multi-currency rounding bugs.
Architectural Rule #1: Browser Redirects Never Mark an Invoice Paid
The single most dangerous mistake I see when auditing custom WHMCS payment modules is trusting query parameters on the customer's browser return_url (viewinvoice.php?id=1042&status=success). Users close mobile tabs mid-redirect during UPI app switches, refresh stale URLs hours later, or tamper with GET/POST parameters intentionally.
Both of my modules enforce strict separation between UI redirection and ledger settlement:
- Checkout generation (
_linkfunction): Builds a signed hosted-checkout payload (PayU form POST with SHA-512 hash) or server-to-server payment-link session viacurl(MamoPay REST API), keeping raw card and UPI credentials completely off the WHMCS server to minimize PCI-DSS scope. - Return URL landing: Displays a clean confirmation or "Confirming payment with bank..." status banner in the WHMCS client area without mutating
tblinvoices. - Asynchronous server-to-server callback (
modules/gateways/callback/*.php): Verifies cryptographic HMAC/SHA-512 signatures, cross-checks transaction state, currency, and amount against the WHMCS invoice record, enforces idempotency on the gateway transaction ID, and only then invokesaddInvoicePayment().
| Integration Layer | PayU Hosted Checkout Module | MamoPay Payment Link Module |
|---|---|---|
| Checkout handoff | Auto-submitted HTML POST form with server-generated SHA-512 request hash | Server-side POST /manage_api/v1/links creating a single-use hosted checkout URL |
| Primary regional methods | UPI, NetBanking, wallets, Indian & international cards | UAE/GCC cards, Apple Pay, Google Pay |
| Authenticity check | Reverse SHA-512 salt verification (hash_equals) + server status verify API | Webhook signature header validation + GET charge verification against MamoPay API |
| Idempotency key | PayU mihpayid | MamoPay charge_id / transaction identifier |
Structuring the WHMCS Gateway Module (_config and _link)
Every third-party WHMCS gateway lives in modules/gateways/<modulename>.php and exposes <modulename>_MetaData(), <modulename>_config(), and <modulename>_link($params). Storing live and sandbox keys via _config() ensures WHMCS encrypts Password-type fields inside tblpaymentgateways rather than leaving API secrets hardcoded in PHP files on disk:
<?php
if (!defined("WHMCS")) {
die("This file cannot be accessed directly");
}
function payucheckout_MetaData(): array
{
return [
"DisplayName" => "PayU Hosted Checkout (UPI / Cards / NetBanking)",
"APIVersion" => "1.1",
"DisableLocalCreditCardInput" => true,
"TokenisedStorage" => false,
];
}
function payucheckout_config(): array
{
return [
"FriendlyName" => [
"Type" => "System",
"Value" => "PayU Secure Checkout",
],
"merchantKey" => [
"FriendlyName" => "Merchant Key",
"Type" => "text",
"Size" => "32",
],
"merchantSalt" => [
"FriendlyName" => "Merchant Salt (v1 / SHA-512)",
"Type" => "password",
"Size" => "48",
],
"testMode" => [
"FriendlyName" => "Sandbox Mode",
"Type" => "yesno",
"Description" => "Route checkouts to test.payu.in instead of secure.payu.in",
],
];
}
Inside payucheckout_link($params), two subtle details prevent broken checkouts in production:
- Unique merchant
txnidper attempt: If a customer opens an invoice, clicks PayU, cancels on the bank OTP screen, and clicks PayU a second time ten minutes later, PayU rejects duplicatetxnidvalues. Generating a deterministic-yet-unique attempt reference such asINV{$invoiceId}T" . time()while passing the clean integer$invoiceIdinside the signedudf1user-defined field lets repeated payment attempts succeed while tying callbacks cleanly back to the exact WHMCS invoice! - Strict
number_format($params['amount'], 2, '.', ''): Never let PHP locale settings or float formatting inject thousands separators (1,250.00) into hash strings, or your SHA-512 digest will mismatch PayU's validator on every invoice above 999.
For MamoPay, mamopay_link($params) calls MamoPay's link-creation endpoint server-side with timeouts capped (CURLOPT_CONNECTTIMEOUT => 5, CURLOPT_TIMEOUT => 10) so a slow external API never stalls PHP-FPM workers on the WHMCS invoice page, caching the short-lived checkout link briefly in session state if the user reloads the page.
Hardening the Callback Handler: Signatures, Amounts, and Idempotency
The callback script (modules/gateways/callback/payucheckout.php or mamopay.php) is an unauthenticated public HTTPS endpoint on your billing server. Anyone on the internet can send crafted POST requests to it. Look at the five defensive checks every production WHMCS callback must enforce in sequence:
<?php
require_once __DIR__ . "/../../../init.php";
require_once __DIR__ . "/../../../includes/gatewayfunctions.php";
require_once __DIR__ . "/../../../includes/invoicefunctions.php";
use WHMCS\Database\Capsule;
$gatewayModuleName = "payucheckout";
$gatewayParams = getGatewayVariables($gatewayModuleName);
if (empty($gatewayParams["type"])) {
http_response_code(503);
exit("Module Not Activated");
}
// 1. Extract untrusted POST fields safely
$status = (string) ($_POST["status"] ?? "");
$txnid = (string) ($_POST["txnid"] ?? "");
$mihpayid = (string) ($_POST["mihpayid"] ?? "");
$amountRaw = (string) ($_POST["amount"] ?? "0.00");
$invoiceId = (int) ($_POST["udf1"] ?? 0);
$postedHash = strtolower((string) ($_POST["hash"] ?? ""));
$email = (string) ($_POST["email"] ?? "");
$firstname = (string) ($_POST["firstname"] ?? "");
$productinfo = (string) ($_POST["productinfo"] ?? "");
// 2. Recompute PayU reverse SHA-512 digest (Salt|status||||||udf5..udf1|email|firstname|productinfo|amount|txnid|key)
$salt = $gatewayParams["merchantSalt"];
$key = $gatewayParams["merchantKey"];
$additionalCharges = (string) ($_POST["additionalCharges"] ?? "");
$reverseFormula = implode("|", [
$salt,
$status,
"", "", "", "", "",
(string) ($_POST["udf5"] ?? ""),
(string) ($_POST["udf4"] ?? ""),
(string) ($_POST["udf3"] ?? ""),
(string) ($_POST["udf2"] ?? ""),
(string) $invoiceId,
$email,
$firstname,
$productinfo,
$amountRaw,
$txnid,
$key,
]);
if ($additionalCharges !== "") {
$reverseFormula = $additionalCharges . "|" . $reverseFormula;
}
$expectedHash = strtolower(hash("sha512", $reverseFormula));
// Constant-time comparison prevents timing side-channel leaks
if ($postedHash === "" || !hash_equals($expectedHash, $postedHash)) {
logTransaction($gatewayParams["name"], ["txnid" => $txnid, "invoiceId" => $invoiceId], "Invalid Hash Signature");
http_response_code(400);
exit("Signature verification failed");
}
// 3. Validate invoice existence (halts execution if invoiceId does not exist in tblinvoices)
$invoiceId = checkCbInvoiceID($invoiceId, $gatewayParams["name"]);
// 4. Enforce idempotency (halts if mihpayid is already recorded in tblaccounts)
checkCbTransID($mihpayid);
// 5. Verify settled status and reconcile currency/amount when WHMCS Convert-To is active
if ($status !== "success") {
logTransaction($gatewayParams["name"], ["txnid" => $txnid, "mihpayid" => $mihpayid, "status" => $status], "Unsuccessful");
http_response_code(200);
exit("Logged non-success status");
}
$paidAmount = (float) $amountRaw;
$feeAmount = 0.00;
// Handle WHMCS multi-currency "Convert To For Processing" (e.g. USD invoice settled in INR or AED)
$invoiceRow = Capsule::table("tblinvoices")->where("id", $invoiceId)->first();
if ($invoiceRow && !empty($gatewayParams["convertto"])) {
$clientCurrencyId = (int) Capsule::table("tblclients")
->where("id", $invoiceRow->userid)
->value("currency");
if ($clientCurrencyId > 0 && $clientCurrencyId !== (int) $gatewayParams["convertto"]) {
$paidAmount = convertCurrency($paidAmount, (int) $gatewayParams["convertto"], $clientCurrencyId);
}
}
logTransaction(
$gatewayParams["name"],
["invoiceId" => $invoiceId, "txnid" => $txnid, "mihpayid" => $mihpayid, "settled" => $amountRaw],
"Success"
);
addInvoicePayment($invoiceId, $mihpayid, $paidAmount, $feeAmount, $gatewayModuleName);
http_response_code(200);
echo "OK";
Look closely at step 5 in that callback code: WHMCS convertto multi-currency reconciliation. Many hosting providers bill international clients in USD while their PayU account settles in INR or their MamoPay account settles in AED. When WHMCS's "Convert To For Processing" setting is enabled on a gateway, WHMCS passes the converted INR or AED figure into $params['amount'] during checkout, yet addInvoicePayment() expects $paidAmount in the client's base invoice currency (USD)! If you pass 4200.00 (INR) directly into addInvoicePayment() on a 50.00 USD invoice without calling convertCurrency(), WHMCS marks the 50 USD invoice paid and credits the customer 4,150.00 USD in overpayment account credit. Explicitly converting back when $gatewayParams['convertto'] differs from the client's currency eliminates that catastrophic accounting bug.
CDN / WAF Rules and Full Lifecycle QA Testing
Even rock-solid PHP gateway code fails if an upstream proxy blocks the payment provider's webhook bot. Before switching either module from sandbox to live merchant keys, run through this infrastructure and QA checklist:
- Exempt callback endpoints from Bot Fight Mode and CSRF challenges: As detailed in my guide on moving to a CDN without overwhelming your origin or blocking automated crawlers, Cloudflare JavaScript Managed Challenges on
/modules/gateways/callback/*will returnHTTP 403HTML pages to PayU and MamoPay webhook servers, leaving paid customer orders stuck inUnpaidstatus. Scope a WAF custom rule allowingPOSTrequests to/modules/gateways/callback/while keeping signature verification strict in PHP. - Test all eight edge states in Sandbox: Never stop QA after one happy-path card payment. Explicitly test: (a) approved payment, (b) declined card/UPI timeout, (c) user clicking "Cancel" mid-checkout and retrying the same invoice, (d) tampered
hashsignature (HTTP 400), (e) replayed webhookPOSTwith the samemihpayid/charge_id(confirmingcheckCbTransIDblocks double-crediting), (f) partial amount tampering, (g)Convert Toforeign-currency checkout, and (h) masked Gateway Log inspection under WHMCS Billing -> Gateway Log confirming zero salt keys or PII leaked intotblgatewaylog. - Decouple outbound receipt mail from webhook response latency: WHMCS triggers
Invoice Payment Confirmationemails and moduleCreateAccounthooks insideaddInvoicePayment(). Ensure your local Postfix or Exim queue accepts mail asynchronously in milliseconds so slow remote MX servers (such as during upstream cloud email outages) never cause your webhook endpoint to exceed PayU or MamoPay's 10-second HTTP timeout and trigger duplicate retries.
Project Outcome
Deploying these two custom WHMCS modules gave the billing platform native PayU and MamoPay hosted checkouts with zero card data touching the hosting servers, constant-time HMAC/SHA-512 verification, automatic multi-currency conversion handling, and idempotent invoice settlement. Every verified payment now transitions invoices cleanly from Unpaid to Paid and provisions hosting accounts within seconds of bank authorization.