Skip to content
Shahid Malla

How to Build a Custom WHMCS Payment Gateway Module

A build guide for a WHMCS custom payment gateway module, checked against the WHMCS developer documentation: the gateway types, _config, _link and _capture, the callback file, refunds, 3D Secure and sandbox testing.

· Published · 12 min read · 9 steps
How to Build a Custom WHMCS Payment Gateway Module

A WHMCS custom payment gateway is a PHP file in /modules/gateways/ that tells WHMCS how to take money through a provider WHMCS does not ship a module for. Pick the gateway type, write the _config function, add _link for a hosted checkout or _capture for a card charge, then let a callback file in /modules/gateways/callback/ apply the payment to the invoice.

A WHMCS payment gateway module is a set of named PHP functions that WHMCS calls at fixed points in the billing flow: when an invoice is shown, when a card is charged, and when the provider sends a notification. WHMCS never calls your file by its path: it calls yourgatewayname_config, yourgatewayname_link and the rest, so the file name and the function prefix must match.

Everything below is checked against the WHMCS developer documentation and the 9.1 admin documentation, read on 3 December 2026, when the documentation home page showed 9.1 as the General Availability release. Gateway files only exist on a self-hosted install: the Custom Gateway Modules page says WHMCS Cloud has no direct file access.

Five-step WHMCS gateway build order: pick the gateway type, write _config, add _link or _capture, write the callback file, then test with sandbox keys before going live
The order I build a gateway module in. Source: shahidmalla.com.

Which WHMCS payment gateway type should you build?

Decide before writing code: the type dictates which functions the module must define. The gateway getting started page names three primary types and splits the third in two.

The WHMCS developer documentation Getting Started page listing the three payment gateway types and the GitHub links for the third party and merchant sample modules
Screenshot of developers.whmcs.com/payment-gateways/getting-started, taken 3 December 2026.
TypeWhat the customer doesFunction beyond _configCard data in WHMCS
Third partyLeaves for the provider's checkout_linkNone
MerchantTypes the card inside WHMCS_captureIn the database
Tokenized, capture exchangeTypes the card once, then WHMCS reuses a token_capture returning gatewayidPurged for a token
Tokenized, remote storageTypes the card in WHMCS, which forwards it on_storeremoteNone
Remote inputTypes the card into the provider's iframe_remoteinput and _remoteupdate, on top of _captureNone

Two more shapes exist: the metadata parameters page says a bank module sets gatewayType to Bank in _MetaData, and the Payment Gateways page lists manual gateways such as Bank Transfer.

The type is not only a code decision. The same page documents two behaviors that follow from it: third party gateways send the Invoice Created email template while merchant and tokenization gateways send Credit Card Invoice Created, and Attempt Capture is deactivated for third party gateways, because the client has to click the payment button.

Decision flow choosing a WHMCS gateway type: an existing module wins, a hosted checkout means third party, a reusable token means tokenized, an iframe means remote input, otherwise merchant
How I pick the type on a scoping call. Source: shahidmalla.com.

In words: use the provider's own module if it has one, a hosted checkout means third party, a reusable token means tokenized, an iframe card form means remote input. Only when none applies do you build a plain merchant gateway, the one option that puts raw card numbers in your database. My WHMCS module types guide sets this against the other families.

Where do the gateway module files go?

The main file goes directly in /modules/gateways/. Its name must be lowercase and start with a letter, because every file in that folder has to be a valid gateway module. Return pages and libraries go in a subfolder named after the module.

modules/gateways/
  |- callback/yourgatewayname.php
  |- yourgatewayname/returnpage.php
  |  yourgatewayname.php

The documentation tells you to start from a sample on GitHub: sample-gateway-module, sample-merchant-gateway, plus remote input samples. Rename the file, replace every gatewaymodule_ with yourgatewayname_, and prefix every function with the module name.

The WHMCS sample-gateway-module repository on GitHub showing the modules/gateways folder, MIT license, 7 commits and a last commit dated six years ago
Screenshot of github.com/WHMCS/sample-gateway-module, taken 3 December 2026: MIT licensed, 7 commits, the last six years old. A skeleton, not a current reference.

What goes in the gateway _config function?

It names the module and declares its settings, and the configuration page says it is required in every gateway module. Whatever you define comes back in $params in every other function, with the admin's saved values filled in.

function yourgatewayname_config()
{
    return [
        'FriendlyName' => ['Type' => 'System', 'Value' => 'Your Gateway'],
        'UsageNotes' => ['Type' => 'System', 'Value' => 'Callback URL: ...'],
        'secretKey' => ['FriendlyName' => 'Secret Key', 'Type' => 'password', 'Size' => '40'],
        'testMode' => ['FriendlyName' => 'Test Mode', 'Type' => 'yesno', 'Default' => false],
    ];
}

The Custom Gateway Modules page documents which attributes each of the six field types needs.

Field typeRequired attributesOptional attributes
textFriendlyName, SizeDefault, Description
passwordFriendlyName, SizeDefault, Description
yesnoFriendlyNameDefault (true or false), Description
dropdownFriendlyName, OptionsDefault, Description
radioFriendlyName, OptionsDefault, Description
textareaFriendlyNameCols, Rows, Default, Description

FriendlyName with a Type of System is the module's display name, which _MetaData can override with DisplayName. UsageNotes, also a System type, holds the usage instructions and accepts HTML, which is where a signup link or the callback URL belongs. Do not name a field currency or invoiceid: the documentation warns those clash with standard variables.

The password type is documented as masked input, which is a display rule, not storage. No WHMCS page I read states that gateway settings are encrypted at rest in WHMCS 9, so treat the value as a live credential in your database and rotate it at the provider if the server is exposed.

_link returns an HTML block that WHMCS prints on the invoice, almost always a form posting to the provider. Delete _capture from the template first: the third party gateway page says it belongs only to merchant modules.

function yourgatewayname_link($params)
{
    $callback = $params['systemurl']
        . 'modules/gateways/callback/yourgatewayname.php';

    return '<form method="post" action="https://provider.example/checkout">
        <input type="hidden" name="reference" value="' . $params['invoiceid'] . '">
        <input type="hidden" name="amount" value="' . $params['amount'] . '">
        <input type="hidden" name="currency" value="' . $params['currency'] . '">
        <input type="hidden" name="notify_url" value="' . $callback . '">
        <input type="hidden" name="return_url" value="' . $params['returnurl'] . '">
        <button>' . $params['langpaynow'] . '</button>
    </form>';
}

WHMCS passes invoiceid, description, amount formatted as xxx.xx and currency, the client record under clientdetails, and system values including systemurl, returnurl, langpaynow, paymentmethod and whmcsVersion. Use langpaynow, not a hard coded label, or the button stays English on a translated client area.

Keep the two URLs apart. The callback files page calls the file under /modules/gateways/callback/ the Callback URL, and the page the customer lands on afterwards the Return URL. Some providers take both in the form post; others set the return address in their own control panel. Where one URL does both, send the customer to the callback file and output a link back from there.

If the provider creates a recurring agreement of its own, add _cancelSubscription. The subscription management page explains both halves: your callback writes the subscription ID into tblhosting.subscriptionid, and the function cancels it remotely. With Automatic Subscription Management enabled on the Invoices tab of General Settings, WHMCS also calls it on cancellations, fraud and upgrades.

How do you capture a card in a merchant gateway?

_capture receives the card and the invoice, calls the provider's API, and returns an array. The merchant gateway page documents the return keys.

Return keyWhat WHMCS does with it
statussuccess marks the invoice paid, pending suits a payment that needs no immediate charge in WHMCS, declined or error fail it
declinereasonThe reason shown for a failed attempt
transidThe provider's transaction ID
feeOptional processing fee for the transaction
rawdataWritten to the gateway log, string or array
gatewayidA token: WHMCS purges the stored card and keeps this

One parameter catches people out. The documentation says cccvv is only available for card holder present attempts, that is, the first payment a customer makes by hand. Renewals run from the cron with no CVV, so a provider that demands one on every charge cannot bill automatically.

Tokenized providers come in two shapes. If the token arrives with a capture, return it as gatewayid and WHMCS purges the locally stored card details and replaces them with the token. If tokens are managed separately, implement _storeremote: the Tokenised Remote Storage page passes an action of create, update or delete.

Remote input gateways never let the card touch your server. Per the remote input gateway page, they need two functions on top of the standard _capture: _remoteinput returns a form that auto-submits into the provider's iframe, and _remoteupdate handles edits to a stored pay method. The callback then calls createCardPayMethod or updateCardPayMethod, helpers available in WHMCS 7.9 and later.

How does the callback file mark the invoice paid?

The callback file is where money becomes a paid invoice, and the documented order is not optional. A sample ships as callback/gatewaymodule.php.

  1. Validate the request came from the provider: signature, shared secret, or a lookup call.
  2. checkCbInvoiceID() halts the script on an unknown invoice and returns a normalized ID.
  3. checkCbTransID() halts the script if that transaction ID is already recorded.
  4. logTransaction() writes the raw request to the gateway log.
  5. addInvoicePayment() applies the money.
require_once __DIR__ . '/../../../init.php';
require_once __DIR__ . '/../../../includes/gatewayfunctions.php';
require_once __DIR__ . '/../../../includes/invoicefunctions.php';

$gatewayModuleName = basename(__FILE__, '.php');
$gatewayParams = getGatewayVariables($gatewayModuleName);
if (!$gatewayParams['type']) {
    die('Module Not Activated');
}
$invoiceId = checkCbInvoiceID($_POST['reference'], $gatewayParams['name']);
checkCbTransID($_POST['transaction_id']);
logTransaction($gatewayParams['name'], $_POST, 'Success');
addInvoicePayment(
    $invoiceId,
    $_POST['transaction_id'],
    $_POST['amount'],
    $_POST['fee'],
    $gatewayModuleName
);

The sample takes the module name from basename(__FILE__, '.php'), so the callback file must carry the module's name too. getGatewayVariables() returns the settings declared in _config, which is how the callback gets its secret; a falsy type means the module is not activated. In addInvoicePayment(), an amount of zero or an empty string means the full balance due, and the fee is 0.00 when the provider reports none.

Those two halting helpers are the whole duplicate payment defense. A provider retrying a webhook, or a customer refreshing the return page, sends the same transaction twice; checkCbTransID() stops the second becoming a second credit.

How do you add refunds, 3D Secure and transaction details?

Each is a separate optional function with one rule: if the provider does not support the feature, do not define it. The refunds page says _refund works with every gateway type and runs when an admin requests a refund.

FunctionReceivesReturns
_refundinvoiceid, the original transid, amount, currencystatus, refund transid, rawdata, optional fees
_3dsecureThe same parameters as _captureHTML posting the customer to the authentication page
_TransactionInformationtransactionId and your settingsAn Information object for the admin modal

The refund return uses the plural key fees while the capture return uses fee, so copying one into the other silently drops the value. The 3D Secure page points that form's return_url at your own callback file, which must then handle both a notification and a returning customer. _TransactionInformation arrived in WHMCS 8.2 and fills the modal an admin opens from a transaction ID at Billing > Transactions, as the transaction information page describes.

How do you test the module before going live?

Upload, activate, then run payments through the sandbox. In WHMCS 9.1 you activate at Configuration > Apps & Integrations and configure at Configuration > System Settings > Payment Gateways; the developer documentation still writes the older Setup > Payment Gateways path.

Activation detects the module type, so deactivate and reactivate after changing which functions exist. A blank page on the gateways screen usually means a PHP syntax error: turn on Display Errors in the Other tab of General Settings to read it, then turn it off again.

The WHMCS documentation table of common test credit card numbers for Visa, MasterCard, American Express, Discover, JCB and Diners Club with any future expiry date
Screenshot of docs.whmcs.com/9-1/payments/payment-gateways, taken 3 December 2026.

That page lists common test card numbers, usable with any future expiry date: 4007000000027 for Visa, 5424000000000015 for MasterCard, 370000000000002 for American Express and 6011000000000012 for Discover. WHMCS says they vary by gateway, so check your provider's list first.

My checklist before a gateway goes live:

  • Pay a sandbox invoice end to end; confirm it shows Paid, not just a log line.
  • Send the same callback twice and confirm the second is rejected.
  • Send a callback with a bad invoice ID and confirm the script stops.
  • Check the gateway log holds enough raw data to answer a later dispute.
  • Test a partial payment and an overpayment, not only the exact amount.
  • Run one renewal from the cron, where no CVV is available.
  • Swap sandbox keys for live ones, untick Test Mode, pay one small real invoice.

When is a custom WHMCS payment gateway the wrong build?

When somebody has already built it, or when it would move card data somewhere you do not want it.

  • The provider already has a module. Stripe and PayPal ship with WHMCS: start with my WHMCS Stripe setup guide or the WHMCS PayPal guide.
  • A plain merchant gateway. It puts card numbers in your database and your PCI scope with them. If the provider offers tokens or an iframe, take that path.
  • WHMCS Cloud. No file access, no custom gateway module.
  • A provider with no notification mechanism. Without a callback, invoices get marked paid by hand.
  • A one-off need. To react to a payment WHMCS already recorded, a hook is smaller and safer, as my WHMCS hooks guide covers.

Budget for maintenance: a gateway module is code you own across WHMCS upgrades and the provider's API changes.

What else do people ask about WHMCS custom payment gateways?

Where can I find a WHMCS payment gateway module on GitHub?

WHMCS publishes its own samples: sample-gateway-module for third party and sample-merchant-gateway for merchant, both linked from the getting started page. The third party repository is MIT licensed, and on 3 December 2026 it showed 7 commits with the last dated six years earlier.

Can I add a custom payment gateway to WHMCS Cloud?

No. The Custom Gateway Modules page states that it applies only to self-hosted installations, because WHMCS Cloud does not currently support direct access to WHMCS files and databases. On Cloud you are limited to the gateways WHMCS provides.

Why does my new gateway module not show up in WHMCS?

Check the file name first: all lowercase, starting with a letter, directly in /modules/gateways/, with every function carrying that same prefix. If the list loads blank, the documentation points at a PHP syntax error. Deactivate and reactivate a module that activates but behaves oddly.

Does a custom WHMCS gateway handle recurring billing?

Yes, in one of two ways. A merchant or tokenized gateway is charged by the WHMCS cron on the renewal date using the stored card or token. A third party gateway with its own subscription needs _cancelSubscription and a callback that writes the subscription ID into tblhosting.subscriptionid, or WHMCS cannot stop it.

How much does a custom WHMCS payment gateway module cost?

It depends on the provider's API, the gateway type, and whether refunds and tokens are in scope. I work at $55 to $65 per hour or a fixed quote per scope, after a free scoping call of about 30 minutes and a written quote within one business day. My guide on WHMCS module development cost breaks down what drives the number.

If you would rather have this built, I do it as WHMCS payment gateway integration and broader WHMCS custom module development, in a staging copy with a written handover. One finished example is the Square payment gateway module for WHMCS, my own product rather than a neutral recommendation.

Last reviewed 3 December 2026. Disclosure: I am a freelance WHMCS developer and I sell WHMCS module development and payment gateway work, including my own gateway modules, so I am not neutral. I am CTO at ElySpace, a freelance developer for Marmaids LLC, and founder of WHMCSPilot and MagizAI. All sales of my modules and services are final, so ask your questions before you buy.

Share this article

Shahid Malla

Written by

Shahid Malla

Freelance WHMCS developer and web designer with 13+ years of client work. CTO at ElySpace, freelance developer for Marmaids LLC, and founder of WHMCSPilot and MagizAI.

Got a project like this?

Tell me what you need and I will send a written quote within one business day.