Integration
WHMCS gateway module
Let WHMCS clients pay invoices on PaymentHooks hosted checkout, with refunds and recurring billing reconciled from signed webhooks.
How it works
- The client clicks Pay Now on an unpaid WHMCS invoice.
- The module creates a checkout session for the invoice balance, in the client's WHMCS currency, and redirects to it.
- PaymentHooks takes the payment through your connected gateway.
- A signed
checkout.session.completedwebhook marks the invoice paid, with the PaymentHooks payment id as the transaction id.
Requires WHMCS 8.x (gateway API 1.1), PHP 7.4 to 8.x with the cURL and JSON extensions, outbound HTTPS to paymenthooks.com, a WHMCS site reachable over HTTPS for webhooks, and a gateway connected under Gateways in PaymentHooks that supports your WHMCS currencies. Cards are entered only on the PaymentHooks page; the module stores no card tokens.
Install and upgrade
Copy the contents of the module's modules/gateways/ folder into your WHMCS modules/gateways/ directory, keeping the structure. There is no hooks file and nothing outside this folder.
modules/gateways/paymenthooks.php gateway module (settings, Pay button, refund, cancel)
modules/gateways/callback/paymenthooks.php Pay Now handler and webhook receiver
modules/gateways/paymenthooks/lib/bootstrap.php loads the library
modules/gateways/paymenthooks/lib/Config.php settings and validation
modules/gateways/paymenthooks/lib/Client.php PaymentHooks API client
modules/gateways/paymenthooks/lib/CheckoutBuilder.php checkout session request
modules/gateways/paymenthooks/lib/InvoiceMapper.php invoice balance, line items, amounts
modules/gateways/paymenthooks/lib/PriceResolver.php billing cycle to interval
modules/gateways/paymenthooks/lib/RecurringPlanner.php what Subscribe & Auto-pay subscribes and charges once
modules/gateways/paymenthooks/lib/SubscriptionMatcher.php subscriptions of one checkout to their items
modules/gateways/paymenthooks/lib/InvoicePlan.php reads an invoice's hosting, domains and addons
modules/gateways/paymenthooks/lib/PayButton.php Pay Now and Subscribe buttons
modules/gateways/paymenthooks/lib/SubscriptionMap.php subscription to services, domains and addons
modules/gateways/paymenthooks/lib/RenewalInvoice.php finds or raises the renewal invoice
modules/gateways/paymenthooks/lib/RefundSync.php records PaymentHooks refunds in WHMCS
modules/gateways/paymenthooks/lib/EventParser.php webhook event fields
modules/gateways/paymenthooks/lib/WebhookRouter.php applies events to WHMCS
modules/gateways/paymenthooks/lib/SubscriptionSync.php renewals and cancellations
modules/gateways/paymenthooks/lib/Signature.php webhook signature check
modules/gateways/paymenthooks/lib/GatewayLog.php Gateway Log entries
modules/gateways/paymenthooks/lib/Logger.php Module and Activity Log
modules/gateways/paymenthooks/lib/Schema.php the module's tables
modules/gateways/paymenthooks/templates/pay_button.tpl
modules/gateways/paymenthooks/whmcs.json
modules/gateways/paymenthooks/logo.pngIn WHMCS admin open Configuration > System Settings > Payment Gateways, activate PaymentHooks, and fill in the settings below. The module creates its tables on first use; there is no SQL to run.
Upgrading to 3.1.5:replace all files; settings are kept and tables are upgraded on the next request. 3.1.5 sends each hosting line's WHMCS product group as productCategory, so the PaymentHooks product is named after the category and item (Web Hosting - Starter, .com domain registration, the addon name) and its price web_hosting_starter(category and item; no currency or amount, because one price holds an amount per currency and keeps its name across versions). The price is found inside that product first and created in your default currency only when missing; a client invoiced in another currency is still charged the exact WHMCS invoice amount, stored as that price's currency option. Subscribe & Auto-pay checkouts no longer show a Pay once choice, because WHMCS already offers Pay Now. 3.1.4 makes Subscribe & Auto-pay always open the subscription checkout: each button has its own form with the mode as a hidden field, so a double tap on a phone or a theme that submits the form by script no longer opens the one-time checkout. 3.1.3 files every client under one catalog product per item: each recurring line carries a productKey (hosting_<product id>, addon_<addon id>, com_domain_renewal, ...) and PaymentHooks keeps one price per item and billing cycle (named e.g. com_domain_renewal since 3.1.5) in your default currency, with each client invoice currency as a currency option holding the exact invoice amount; 3.1.2 and earlier created a product per client line. Every charge and renewal equals the WHMCS invoice, in the invoice currency, never converted. A changed WHMCS price creates a new price version for new clients; existing subscribers keep their amount until you move them from the price page. 3.1.2 checks phones worldwide; 3.1.1 added Subscribe & Auto-pay on discounted first periods and mixed billing cycles in one checkout. Versions that asked for sk_/pk_ test and live keys need your phk_live_ secret key and the endpoint's whsec_ secret entered again.
| Table | Holds | Added on upgrade |
|---|---|---|
mod_paymenthooks_events | Webhook event ids already processed | status (existing rows become done) |
mod_paymenthooks_sessions | Invoice to checkout session, payment and subscription | fee_minor, plan_json |
mod_paymenthooks_subscriptions | Subscription to each service, domain and addon it renews | new table |
mod_paymenthooks_refunds | Refunds known per payment, so none is booked twice | new table |
mod_paymenthooks_price_map | Earlier versions' product/price cache; no longer written | currency, amount_minor |
mod_paymenthooks_install | A random id for this install, used in idempotency keys | new table |
PaymentHooks setup
- API key. Under Developers > API Keys, create a secret key (
phk_live_) withpayments:read,payments:write,customers:read,customers:write. For subscriptions also addsubscriptions:write. - Webhook endpoint. Under Developers > Webhooks, add the module's Webhook URL (
https://your-whmcs/modules/gateways/callback/paymenthooks.php), subscribe it to these events and copy itswhsec_signing secret into the module. Other events are accepted and logged as Ignored.checkout.session.completedcheckout.session.payment_failedpayment.refundedsubscription.renewedsubscription.renewal_failedsubscription.cancelledsubscription.deletedinvoice.paid
- Test, then live. PaymentHooks has one key type; payments are simulated or real according to your business's Platform Mode. Test with Platform Mode on Test, then switch it to Live; nothing changes in WHMCS.
Module settings
| Field | Value |
|---|---|
| Secret Key | phk_live_... from Developers > API Keys. Required. |
| Publishable Key | phk_pub_... Optional; not used by the redirect checkout. |
| Webhook Signing Secret | whsec_... of the webhook endpoint. Required. |
| Webhook URL | Read-only. Register it as the webhook endpoint. |
| Custom Checkout Domain | Optional, e.g. payments.example.com. Clients pay on it; API calls stay on paymenthooks.com. |
| Convenience Fee % | Optional, 0 to 100, charged as balance x %. The invoice is credited with its balance; the surcharge is noted in the Gateway Log, not booked as a gateway fee. |
| Description Template | Stored on the checkout session as metadata.description. {invoiceid} is replaced. Default "Invoice {invoiceid}". |
| Checkout Heading | Shown above the Pay button. Default "Pay securely with PaymentHooks". |
| Checkout Description | Shown under the heading. Blank hides it. |
| Logo URL | Image above the Pay button; blank uses modules/gateways/paymenthooks/logo.png when present. |
| Enable Subscriptions | Shows Subscribe & Auto-pay next to Pay Now on invoices with hosting, domains or addons that can renew. The client chooses. |
| Subscribe Button Text | Label of that button. Default "Subscribe & Auto-pay". |
| Debug Logging | Logs every API call to the Module Log. Errors always go to the Activity Log. |
If the Secret Key or Webhook Signing Secret is missing or has the wrong prefix, or the fee is out of range, the invoice shows "Online payment is unavailable. Please contact us." and the reason is in the Activity Log.
Custom checkout domain
With a verified domain under Settings > Branding & domains in PaymentHooks, set Custom Checkout Domain (for example payments.example.com). Clients then pay at https://payments.example.com/checkout/... and return to WHMCS from there. A checkout from another PaymentHooks account cannot be opened on your domain. Leave the field blank to use paymenthooks.com.
Paying an invoice
| When the client clicks Pay Now | Result |
|---|---|
| Not logged in, or not the invoice owner | Back to the invoice with paymentfailed. |
| Subscribe pressed but subscriptions are off, or the invoice cannot be subscribed | Back to the invoice with paymentfailed; nothing is charged. |
| Invoice already Paid | Back to the invoice with paymentsuccess. |
| Invoice Cancelled, Refunded, Collections or Draft | Back to the invoice with paymentfailed. |
| A payment is complete or in progress at PaymentHooks, webhook not yet received | Back with paymentsuccess; no second checkout is created. |
| An open session for the same balance and mode, expiring in more than a minute | The client is sent back to it. |
| Otherwise | A new session is created; older ones are marked stale. |
The session is for the invoice balance(total less payments and credit, as WHMCS reports it), in the client's WHMCS currency, with WHMCS tax included; the module tells PaymentHooks not to add tax. Invoice rows are shown as line items when they add up to the balance, otherwise one line for the balance is sent. Line items are sent without adjustableQuantity, so the client cannot change quantities or remove items on the checkout page.
- Checkout stops with an error instead of charging a different amount when the client has no email or currency, the balance is zero, a subscription cannot be priced (no recurring service, unsupported cycle, zero amount, or PaymentHooks refused the product or price), or PaymentHooks rejects the request or cannot be reached.
- The client returns to the invoice with
paymentfailed; the Gateway Log showsCheckout Errorwith the reason and the Activity Log hasPaymentHooks error [checkout-click].
Webhook handling
The callback verifies X-PaymentHooks-Signature (HMAC-SHA256, 5-minute window, secret rotation supported) and processes each event id once.
| Event | Action | Gateway Log |
|---|---|---|
checkout.session.completed | Records the payment on the invoice, minus any convenience fee | Successful |
(payment already recorded) | Nothing | Duplicate |
(currency differs from the invoice, invoice missing, or event incomplete) | Not applied; record it by hand | Needs Attention |
(checkout not created by this WHMCS) | Nothing | Ignored |
checkout.session.payment_failed | Nothing; the invoice stays unpaid | Failure |
payment.refunded | A refund made in PaymentHooks is recorded on the invoice (only the part WHMCS does not know yet) | Refund Notification |
(refund in another currency, or more than WHMCS credited) | What can be recorded is; the rest is flagged | Needs Attention |
subscription.renewed, invoice.paid | Records the charge on the renewal invoice(s) of the subscribed items | Subscription Renewal Paid |
(both events for one renewal) | The second is a duplicate | Duplicate |
(no renewal invoice yet, item due) | WHMCS raises it (GenInvoices), then the charge is recorded | Subscription Renewal Paid |
(item due, still no invoice) | Asks PaymentHooks to redeliver | Retry Requested |
(WHMCS shows the period paid, nothing due) | Not applied; add credit or refund | Needs Attention |
(charge differs from the balance) | Recorded, flagged for review | Needs Attention |
(covered by credit) | Nothing to record | Ignored |
subscription.renewal_failed | Note on the renewal invoice; WHMCS overdue handling applies; PaymentHooks retries | Failure |
subscription.cancelled, subscription.deleted | The items stop auto-renewing (unbound) | Subscription Cancelled |
Any other event type | Nothing | Ignored |
The callback answers 200 when an event is handled (including duplicates and events it cannot apply, so they are not redelivered), 401 for a bad signature, 400 for a body that is not an event, and 500 to ask for redelivery, which PaymentHooks does after 1 minute, 5 minutes, 30 minutes and 2 hours.
Recurring billing
- PaymentHooks does all the billing; WHMCS never charges. The client subscribes once and PaymentHooks charges every renewal through your connected gateway, sends the merchant webhooks, and the module records each charge on the WHMCS renewal invoice.
- Hosting renews at the service's recurring amount on its billing cycle, a domain at its recurring amount every registration-period years, an addon at its recurring amount on its cycle. Setup fees and one-off items are charged once.
- Each item and cycle is one PaymentHooks price in your default currency (Profile); every client invoice currency is a currency option on it holding the exact WHMCS amount, so a USD client and an INR client of the same domain share one price and each is charged exactly their invoice. When the WHMCS price of an item changes, the next checkout creates a new version of that price for new clients; existing subscribers keep renewing at their amount. To move them, open the price in PaymentHooks and use Versions > Apply to existing subscriptions: each customer is emailed the current and new amount and the renewal it applies from, and can cancel before then. Indian mandates whose maximum the new amount exceeds are skipped and listed.
- Every eligible recurring item is subscribed in one checkout. PaymentHooks groups the recurring lines by billing cycle and start date and opens one subscription per group, with one payment now and one mandate: monthly hosting and a yearly domain become a monthly and a yearly subscription.
- Full price: the line has no start date and the subscription's first charge, today, pays this period; a first period dearer than renewal adds the difference as a one-time line. Discounted first period (first-year domain price, promotion): this period's actual amount with its tax is a one-time line, and the item renews at full price from recurring.startsAt. Part-paid invoices or invoices with credit applied are not offered Subscribe.
- startsAt is the item's next due date after this invoice is paid: tblhosting / tbldomains / tblhostingaddons nextduedate plus one cycle. Until payment WHMCS keeps nextduedate on the first day of the period being paid (the invoice line's duedate; for a new order the order date) and moves it on by one cycle when the invoice is paid. Dates that disagree (edited by hand), a period already over, or no due date: the discounted item is not guessed and Subscribe is not offered.
- The session uses mode subscription with lineItems[].recurring { interval, intervalCount, startsAt? }. If the created session did not keep a recurring or a startsAt, or has several billing groups but no subscriptions list, the module refuses it (RECURRING_LINE_ITEMS_UNSUPPORTED, logged) and the client can use Pay Now.
- On checkout.session.completed each subscription is bound to its group's items, matched through the event's subscriptions list by cycle, start date and items. Anything ambiguous is left unbound and logged Needs Attention; the payment is always recorded.
- On subscription.renewed or invoice.paid the charge is recorded on the oldest unpaid renewal invoice of that subscription's own items: the hosting subscription pays the hosting invoice, the domain subscription the domain invoice; on one invoice holding both, each pays its own lines' share. When none exists and the item is due within 7 days, WHMCS raises it (GenInvoices, no emails); if none can be raised the event is redelivered.
- subscription.renewal_failed adds a note to the unpaid renewal invoice; WHMCS's own overdue reminders and suspension apply while PaymentHooks retries. Nothing is charged from WHMCS.
- subscription.cancelled or subscription.deleted (including a revoked mandate) unbinds every item. Cancelling a WHMCS service cancels its subscription at PaymentHooks for every item it renewed.
- Keep WHMCS's invoice generation on (Automation Settings > Invoice Generation) and do not set up another gateway's automatic capture for these clients.
"payOnceOption": "off",
"lineItems": [
{ "description": "Starter Hosting", "quantity": 1, "unitPrice": 100000, "recurring": { "interval": "month", "intervalCount": 1 },
"productKey": "hosting_3", "productName": "Starter", "productCategory": "Web Hosting" },
{ "description": "Setup Fee", "quantity": 1, "unitPrice": 15000 },
{ "description": "Domain Registration - example.com - 1 Year/s", "quantity": 1, "unitPrice": 80000,
"recurring": { "interval": "year", "intervalCount": 1, "startsAt": "2027-11-07" },
"productKey": "com_domain_registration", "productName": ".com domain registration" },
{ "description": "This period: Domain Registration - example.com - 1 Year/s", "quantity": 1, "unitPrice": 50000 },
{ "description": "Backups", "quantity": 1, "unitPrice": 20000, "recurring": { "interval": "month", "intervalCount": 1 },
"productKey": "addon_5", "productName": "Backups" }
]| WHMCS cycle | Interval | intervalCount |
|---|---|---|
| Weekly | week | 1 |
| Monthly | month | 1 |
| Quarterly | month | 3 |
| Semi-Annually | month | 6 |
| Annually | year | 1 |
| Biennially | year | 2 |
| Triennially | year | 3 |
| Domain, N-year registration | year | N |
One Time and Free products are never subscriptions.
Refunds
Refundon a PaymentHooks transaction in WHMCS refunds it at PaymentHooks, full or partial, in the payment's currency. A refund made in the PaymentHooks dashboard arrives as payment.refunded and is noted in the Gateway Log for you to reflect in WHMCS.
Logs and troubleshooting
| Where | What |
|---|---|
| Billing > Gateway Log | One entry per webhook delivery (the statuses above, plus Invalid Signature, Invalid Payload and Error) with the event id, type, HTTP status returned and a plain result. Checkout errors appear as Checkout Error. |
| Utilities > Logs > Activity Log | Every error, and anything to fix by hand. Always on. |
| Utilities > Logs > Module Log | Raw API requests and responses, with Debug Logging ticked and WHMCS module debugging on. |
Secrets are masked in every log.
| Symptom | Check |
|---|---|
| Gateway Log stays empty after a payment | PaymentHooks is not reaching WHMCS: check the endpoint URL and its delivery log under Developers > Webhooks. |
| Invalid Signature | Use this endpoint's whsec_ secret; the server clock must be within 5 minutes. |
| "Online payment is unavailable" on the invoice | A setting is missing or invalid; see the Activity Log. |
| Checkout Error | The reason is in the entry; INSUFFICIENT_SCOPE means the key lacks a scope. |
| Renewal Retry Requested | The item is due but WHMCS raised no renewal invoice for it; check the product's invoice generation and that the item is Active. |
| No Subscribe button | With Enable Subscriptions on, the note under Pay Now (paymenthooks_pay_subscribe_unavailable) says why, and the Activity Log has PaymentHooks info [subscribe-unavailable] with the reason code, or [subscribe-plan] when the invoice could not be read. No note: Enable Subscriptions is off. |
| RECURRING_LINE_ITEMS_UNSUPPORTED | PaymentHooks did not keep lineItems[].recurring or recurring.startsAt, or returned no subscriptions list for several billing groups; the entry says which. Nothing is charged; clients can use Pay Now. |
| Completed checkout Needs Attention (webhook-subscriptions-unmatched) | The payment is recorded, but a billing group could not be matched to exactly one subscription; check the subscriptions in PaymentHooks. |
| Needs Attention | Read the entry; it says what to record by hand. |
Testing
Without WHMCS or a network (PHP 7.4+); both exit 0 when every check passes:
php tests/run.php # signature, settings, amounts, the checkout request, event parsing, cycles
php tests/webhook-harness.php # the full webhook path: invoices and Gateway Log for every eventThen on your WHMCS, with Platform Mode on Test:
| Scenario | Expected |
|---|---|
| Pay an invoice | Invoice marked Paid; the transaction id is the PaymentHooks payment id; Gateway Log shows Successful. |
| Cancel on the checkout page | Invoice stays Unpaid. |
| Resend the event from Developers > Webhooks | Gateway Log shows Duplicate; the payment is applied once. |
| Wrong signing secret | Callback answers 401; Gateway Log shows Invalid Signature. |
| Refund in WHMCS, full and partial | Refund recorded in WHMCS and shown in PaymentHooks. |
| Subscribe & Auto-pay on hosting + addon | Both show the subscription id; the next renewal is charged by PaymentHooks and marks the renewal invoice Paid. |
| Hosting monthly + domain yearly | One checkout; hosting and domain each get their own subscription id; each renewal pays its own WHMCS invoice. |
| New domain at a first-year discount | Subscribe offered; the first year is charged once and the domain renews at full price from its next due date. |
| Part-paid invoice | Only Pay Now, with the reason in a note under it. |
| Renewal before WHMCS raised the invoice | The invoice is raised and paid; Gateway Log shows Subscription Renewal Paid. |
| Failed renewal | The invoice stays Unpaid with a note; WHMCS reminders run. |
| Refund in the PaymentHooks dashboard | Refund recorded on the WHMCS invoice. |
| Cancel the service | Subscription cancelled in PaymentHooks for every item it renewed. |