PHP API, Hooks & CLI
Core PHP Entry Points
Section titled “Core PHP Entry Points”<?php namespace ProcessWire;
$payments = Payments::requireInstance($wire);
// One-time transactions & payable queries$payments->authorize($intent);$payments->purchase($intent);$payments->capture($transactionId, $optionalAmount);$payments->refund($transactionId, $optionalAmount, $reason);$payments->void($transactionId, $reason);$payments->isPaid($payableType, $payableId);$payments->summaryForPayable($payableType, $payableId);$payments->getTransaction($transactionId);$payments->getTransactionsFor($payableType, $payableId);$payments->setHttpTransport($customTransport);
// Payment links & saved sources$payments->createPaymentLink($options);$payments->listSavedSources($userId);$payments->sources()->saveSource($options);$payments->revokeSavedSource($sourceId, $userId);
// Subscriptions, usage, portal & invoices$payments->subscribe($options);$payments->switchPlan($subscriptionId, $newPlanHandle);$payments->updateSubscriptionQuantity($subscriptionId, $quantity);$payments->pauseSubscription($subscriptionId);$payments->resumeSubscription($subscriptionId);$payments->cancelSubscription($subscriptionId, $immediately);$payments->hasActiveSubscription($userId, $planHandle);$payments->recordUsage($subscriptionId, $quantity, $metadata);$payments->getUsageSummary($subscriptionId);$payments->customerPortalUrl($subscriptionId, $returnUrl);$payments->customerPortalUrlForUser($userId, $returnUrl);$payments->listInvoicesForUser($userId);$payments->resolveInvoicePdfUrl($invoiceId, $userId);
// Marketplace$payments->createSubMerchantAccount($gatewayHandle, $payload);$payments->createMarketplaceTransfer($gatewayHandle, $payload);Hookable Methods (21)
Section titled “Hookable Methods (21)”| Hook | Arguments & Return | Timing | What It Does |
|---|---|---|---|
Payments::afterAuthorize |
(TransactionRecord $tx, TransactionOutcome $outcome): void |
After | Fires after an authorization hold succeeds. |
Payments::afterCapture |
(TransactionRecord $tx, TransactionOutcome $outcome): void |
After | Fires after a held authorization is captured (full or partial). |
Payments::afterPurchase |
(TransactionRecord $tx, TransactionOutcome $outcome): void |
After | Fires after an immediate purchase settles. |
Payments::afterRefund |
(TransactionRecord $tx, TransactionOutcome $outcome): void |
After | Fires after a full or partial refund completes. |
Payments::afterDisputeOpened |
(TransactionRecord $disputeTx, TransactionRecord $parentTx, WebhookEvent $event): void |
After | Fires when a provider webhook reports a new chargeback or dispute. |
Payments::afterDisputeResolved |
(TransactionRecord $disputeTx, TransactionRecord $parentTx, string $resolution, WebhookEvent $event): void |
After | Fires when a dispute is won, lost, or closed. |
Payments::afterVoid |
(TransactionRecord $tx, TransactionOutcome $outcome): void |
After | Fires after an uncaptured authorization is voided. |
Payments::afterFailure |
(TransactionRecord $tx, TransactionOutcome $outcome): void |
After | Fires when a payment attempt fails or is declined. |
Payments::afterPaymentLinkPaid |
(PaymentLinkRecord $link, TransactionRecord $tx): void |
After | Fires when a /pay/{token} hosted payment link settles. |
Payments::afterSubscribe |
(SubscriptionRecord $subscription, array $gatewayResult = []): void |
After | Fires when a new recurring subscription is created. |
Payments::afterStatusChange |
(SubscriptionRecord $subscription, SubscriptionStatus $previousStatus, SubscriptionStatus $newStatus, string $reason = ''): void |
After | Fires on every subscription state transition (trialing, active, past_due, paused, canceled). |
Payments::afterPlanSwitch |
(SubscriptionRecord $subscription, SubscriptionPlan $previousPlan, SubscriptionPlan $newPlan, array $proration = []): void |
After | Fires after a subscription switches to a new plan handle. |
Payments::afterCancel |
(SubscriptionRecord $subscription, bool $immediately): void |
After | Fires after a subscription is canceled immediately or at period end. |
Payments::afterInvoicePaid |
(SubscriptionRecord $subscription, SubscriptionInvoiceRecord $invoice, ?TransactionRecord $tx = null): void |
After | Fires when a recurring invoice is marked paid. |
Payments::afterPaymentFailed |
(SubscriptionRecord $subscription, ?SubscriptionInvoiceRecord $invoice = null, string $reason = ''): void |
After | Fires when a recurring renewal charge fails. |
Payments::afterUsageRecorded |
(SubscriptionRecord $subscription, string $meterKey, int $quantity, array $result = []): void |
After | Fires after metered usage is recorded via recordUsage(). |
Payments::onWebhookEvent |
(WebhookEvent $event, ?TransactionRecord $tx = null): void |
After | Fires for every verified, normalized inbound webhook event. |
Payments::registerDrivers |
(DriverRegistry $registry): void |
After | Fires during lazy driver discovery so paymentsDriver modules register custom gateway classes. |
Payments::resolveBlueprint |
(string $type, array $schema): array |
After | Fires when resolving internal PaymentsBlueprints schemas. |
Payments::clearCache |
(): void |
After | Fires when Payments clears request-scoped gateway and settings caches. |
ProcessPayments::translations |
(): array |
After | Returns localized UI strings for the Setup -> Payments React workspace. |
Hook Examples (site/ready.php)
Section titled “Hook Examples (site/ready.php)”<?php
declare(strict_types=1);
namespace ProcessWire;
use Totoglu\Payments\Domain\SubscriptionRecord;use Totoglu\Payments\Domain\SubscriptionStatus;use Totoglu\Payments\Domain\TransactionRecord;use Totoglu\Payments\Domain\WebhookEvent;
// 1. Mark a charter deposit paid immediately after purchase settles$wire->addHookAfter('Payments::afterPurchase', function (HookEvent $event): void { /** @var TransactionRecord $tx */ $tx = $event->arguments(0); if ($tx->payableType === 'charter_booking') { $event->wire()->log->save('charter-payments', "Settled booking {$tx->payableId} via tx {$tx->id}"); }});
// 2. React to subscription status transitions (for example past_due -> active)$wire->addHookAfter('Payments::afterStatusChange', function (HookEvent $event): void { /** @var SubscriptionRecord $sub */ $sub = $event->arguments(0); /** @var SubscriptionStatus $prev */ $prev = $event->arguments(1); /** @var SubscriptionStatus $next */ $next = $event->arguments(2); $event->wire()->log->save('subscriptions', "Sub {$sub->id}: {$prev->value} -> {$next->value}");});
// 3. Audit every verified inbound provider webhook event$wire->addHookAfter('Payments::onWebhookEvent', function (HookEvent $event): void { /** @var WebhookEvent $webhook */ $webhook = $event->arguments(0); $event->wire()->log->save('payments-webhooks', "Verified {$webhook->gatewayHandle}:{$webhook->type}");});CLI Commands (5) & Scheduled Tasks (2)
Section titled “CLI Commands (5) & Scheduled Tasks (2)”| Command | Options & Arguments | Purpose |
|---|---|---|
payments:doctor |
--json |
Audits blueprints, managed SQL tables, gateways, SecretBox health, and webhook configuration. |
payments:gateways:list |
-a/--active-only, --json |
Lists configured gateway instances, drivers, currencies, priorities, and capabilities. |
payments:webhook:url |
<handle>, --json |
Outputs the canonical /_payments/webhook/{handle} endpoint URL for a configured gateway. |
payments:subscriptions:sync |
--dry-run, --json |
Reconciles subscription states against remote providers (automated by ReconcileSubscriptionsTask). |
payments:transactions:reconcile |
--older-than=30, --expire-after=1440, --limit=100, --dry-run, --json |
Polls pending transactions and expires stale intents (automated by ReconcileTransactionsTask). |
Run the background queue worker and system cron so queued webhook retries and reconciliation tasks run automatically:
php vendor/bin/wire queue:work --tries=3 --sleep=3# Crontab entry (runs ReconcileTransactionsTask & ReconcileSubscriptionsTask)* * * * * cd /var/www/aegeanvoyages.example && /usr/bin/php vendor/bin/wire schedule:run >> /var/log/pw-schedule.log 2>&1Return Route, Webhook Payload, Testing, Demo Mode & Localization
Section titled “Return Route, Webhook Payload, Testing, Demo Mode & Localization”- Hosted Return Route (
/_payments/return/{hash}): Gateway redirects (3DS / hosted checkout return) land on/_payments/return/{hash}to finalize transaction state before redirecting to your confirmation page. Exclude/pay/*and/_payments/*from full-page caches. - Webhook Payload & Signature (
X-Payments-Signature): Normalized webhook events forwarded viaPayments::onWebhookEventor custom receivers carry JSON payloads signed withX-Payments-Signature:
{ "event": "payments.purchase.succeeded", "timestamp": "2026-06-15T12:45:00Z", "data": { "transaction_id": "0196f8d2-3c1a-7b40-9e12-8a4c5d6e7f01", "gateway": "stripe", "amount_minor": 490000, "currency": "EUR" }}- Mocking Gateway HTTP Calls in Pest/PHPUnit: Inject a fake implementing
Totoglu\Payments\Contract\HttpTransportInterfacevia$payments->setHttpTransport($fakeTransport)so tests never hit live payment APIs. - Demo Mode (
$config->demo = true): Blocks live gateway charges, refunds, and credential mutations while keeping read-only ledger browsing available. - 6-Locale Translation Packs: Bundled CSV packs (
en,tr,de,fr,es,ru) live insite/modules/Payments/languages/for import under Setup -> Languages -> [Language] -> Site Translation Files.
Troubleshooting
Section titled “Troubleshooting”Idempotency Conflict Error on Retry
Section titled “Idempotency Conflict Error on Retry”- Reusing the same
idempotencyKeywith a different amount, currency, or payable reference throws a conflict error by design. Generate a new key whenever the customer modifies cart items or checkout totals.
Inbound Webhook Returns HTTP 400 or 401
Section titled “Inbound Webhook Returns HTTP 400 or 401”- Confirm the signing secret in Setup -> Payments -> Gateways matches the provider dashboard (and check
$env:VARresolution viaphp vendor/bin/wire payments:doctor --json). - Ensure reverse proxies do not mutate or re-encode the raw JSON request body before signature verification.
Pending Transactions Never Settle Automatically
Section titled “Pending Transactions Never Settle Automatically”- Verify your
trk/processwire-consolescheduler is runningReconcileTransactionsTask(or runphp vendor/bin/wire payments:transactions:reconcile --dry-run --json) and confirm the gateway driver implementsTransactionStatusGatewayInterface.
SecretBox Fails to Decrypt Stored Credentials After Server Migration
Section titled “SecretBox Fails to Decrypt Stored Credentials After Server Migration”enc:v1:secrets are encrypted with your ProcessWire installation salt. When moving between environments, store production credentials via$env:VARreferences so they remain portable across hosts.