Summary
Payage should own the payment lifecycle and tell applications about real status transitions, rather than handing them a transaction ID and leaving each application to work out what happened. Today every application has to re-implement locking, idempotency and transition rules; UserPoints' PurchasePaymentSync is about 370 lines, of which roughly a fifth is UserPoints-specific.
Problems with the current contract:
app_update_pathstores an absolute file path in the database. Payagerequire_onces it and calls a global functionpayment_update($tid). Paths break on site moves, every application shares one function name, and the code executed is whatever a DB row names.- The callback receives only a tid. The application must call
PayageApi::get_payment_data()to learn anything, and that call silently takes a semaphore which is never released explicitly. That hidden lock is what currently stops the IPN and the browser return racing each other. - No transition tracking. Payage calls the application on every callback, including duplicates and out-of-order ones, so each application must detect "already credited", "SUCCESS after REFUNDED" and duplicate refunds itself.
- The return page under-reports state. A user returning from the gateway sees a single status word; pending payments look like a dead end.
- No recurring payments. Each payment is a one-off transaction; subscriptions are not modelled (see Recurring subscriptions).
Goal: a small, typed contract where an application registers a handler class, receives a snapshot of the payment and the previous status, and only has to say what that transition means for its own data.
Payment lifecycle
A payment is not one event, and only the gateway's server-to-server confirmation means "paid". The browser coming back to the site proves nothing: it is the user's browser carrying a tid.
|
Event |
Who says so |
Trust |
Payage today |
|---|---|---|---|
|
Button created |
Payage |
n/a |
|
|
User returns to site |
User's browser |
None |
|
|
Payment accepted, not yet cleared |
Gateway (IPN / webhook) |
Authoritative |
|
|
Payment settled |
Gateway (IPN / webhook / API check) |
Authoritative |
|
|
Failed or cancelled |
Gateway or user |
Authoritative / informational |
|
|
Refund |
Gateway or Payage admin |
Authoritative |
|
|
Dispute / chargeback |
Gateway |
Authoritative |
Not modelled |
Card authorise-then-capture is a separate two-step that Payage does not currently use: PayPal Checkout sends intent = CAPTURE and Stripe Checkout captures immediately, so for cards SUCCESS normally arrives within seconds. The long gap comes from asynchronous methods (bank debits, eCheck), which sit in PENDING for days.
The MembershipPro problem. Telling the user "your subscription has been processed" on the browser return, before the webhook has arrived, is exactly the failure described above: the message is driven by the untrusted event, while access is driven by the trusted one. Users then find membership features missing and raise support tickets. The cure is to word every message by the authoritative status and to show the gap honestly:
- NONE or PENDING on return: "Payment submitted, waiting for confirmation from PayPal. Your points / membership will be activated when it arrives."
- SUCCESS: "Payment confirmed" and the thing bought is already usable.
- FAILED / CANCELLED: say so, with a way to try again.
A dispute (chargeback) status should be added to Payage, since it is where money is most often lost after an apparent success.
Proposed contract
Applications register a handler class name, not a callable or a file path. A closure cannot be stored in the database and revived in the later request where the webhook arrives; a fully-qualified class name can, and Joomla's namespace autoloader finds it without a path.
A Joomla plugin event (onPayageStatusChange) was considered and rejected: it would add another plugin to install and manage on every site, and the handler class gives a stricter one-to-one link between payment and application.
namespace BlackSheepResearch\Component\Payage\Site\Api;
interface PaymentHandlerInterface
{
/**
* Called once per real status transition, inside Payage's lock.
* Must be idempotent: delivery is at-least-once.
* Throwing marks the delivery failed; Payage retries later.
*/
public function onStatusChange(PaymentSnapshot $payment, int $previousStatus): void;
}
final class PaymentSnapshot
{
public function __construct(
public readonly string $tid, // pg_transaction_id
public readonly string $appName,
public readonly int $status, // LAPG_STATUS_*
public readonly string $currency,
public readonly float $grossAmount,
public readonly array $appTransactionDetails,
public readonly ?string $pendingReason,
public readonly ?string $gatewayTransactionId,
public readonly ?string $subscriptionId, // see Recurring subscriptions
public readonly string $statusChangedAt,
) {}
}
Registration in get_buttons:
$parmlist['app_handler'] = \BlackSheepResearch\Component\UserPoints\Site\Payment\PurchaseHandler::class;
$parmlist['app_return_url'] = Uri::root(true) . '/index.php?option=com_userpoints&view=purchase&task=complete';
app_return_url stays a URL because it is where the browser is sent. Before calling a handler Payage checks class_exists() and is_subclass_of($class, PaymentHandlerInterface::class), so a database row can only name a class that deliberately opted in.
Locking becomes explicit. get_payment_data() currently acquires a semaphore and never releases it; PHP frees it at request end, which is what serialises the IPN and browser-return paths today. The new flow is: Payage takes a named lock per tid (GET_LOCK('payage_<tid>') in MySQL works on shared hosting where SysV semaphores often do not), reloads the row, builds the snapshot, calls the handler, records the outcome, releases the lock. get_payment_data() keeps its current behaviour for existing callers but gains a lock-free variant for display-only use.
What moves into Payage
Payage takes over everything that is true of any application; the handler keeps only what the transition means for its own data.
|
Responsibility |
Today (UserPoints) |
Proposed owner |
|---|---|---|
|
Validate tid, check API installed |
|
Payage |
|
Serialise concurrent callbacks |
Hidden semaphore in |
Payage, explicit lock |
|
Skip duplicate deliveries of the same status |
|
Payage ( |
|
Forbid illegal transitions (SUCCESS after REFUNDED) |
|
Payage transition table |
|
Duplicate refund detection |
|
Payage (refund delivered once) |
|
Log old/new state per callback |
Own log file |
Payage payment history |
|
Check |
|
Handler |
|
Create the negative refund row |
|
Handler |
New columns on the payment table:
app_handler— the class name.app_delivered_status— the last status the handler accepted without throwing.app_delivery_attempts,app_delivery_error— for retry and the admin view.
Delivery rule: after any gateway update, if pg_status_code != app_delivered_status and the transition is allowed, call the handler with previousStatus = app_delivered_status. On success, store the new delivered status. On exception, record the error and leave it undelivered. Undelivered payments are retried on the next callback for that tid, by a Joomla Scheduled Task, and by a "Redeliver" button in the Payage admin payment view.
Allowed transitions (anything else is logged and not delivered):
- NONE → PENDING, SUCCESS, FAILED, CANCELLED
- PENDING → SUCCESS, FAILED, CANCELLED
- FAILED / CANCELLED → SUCCESS (late success is real; PayPal does this)
- SUCCESS → REFUNDED, DISPUTED
- DISPUTED → SUCCESS (dispute won), REFUNDED (dispute lost)
- REFUNDED → nothing
Resulting UserPoints handler, replacing about 300 lines:
final class PurchaseHandler implements PaymentHandlerInterface
{
public function onStatusChange(PaymentSnapshot $p, int $previous): void
{
[$referreid, $detailId] = $p->appTransactionDetails;
$detail = new PointsDetails((int) $detailId);
if (!$detail->id || $detail->rule_id !== 'sysplgup_buypoints') {
throw new \RuntimeException("Purchase detail $detailId missing");
}
$detail->keyreference = $p->tid;
match ($p->status) {
LAPG_STATUS_SUCCESS => $detail->credit(),
LAPG_STATUS_REFUNDED => $detail->reverse($p->tid), // only reached from SUCCESS/DISPUTED
default => $detail->markUncredited($p->status, $p->pendingReason),
};
}
}
The handler must still be idempotent, because a crash between the handler finishing and Payage recording app_delivered_status causes a redelivery. Keying on the Payage tid (already bound to keyreference) is enough.
Return page
The return page should never mutate application state; it only shows the authoritative status and waits briefly for it to settle. Today UserPoints' complete() calls PurchasePaymentSync::sync(), which writes. That is safe only because the sync re-reads Payage, but under the new contract the handler is the single writer.
Some gateways verify the payment server-side during the return request itself (PayPal Standard's PDT _notify-synch, Stripe's success task). That still works: delivery is triggered by Payage whenever a gateway update changes the status, in whichever request that happens, so a missing webhook does not leave the application uninformed.
Payage supplies two pieces any application can use:
- Status endpoint —
index.php?option=com_payage&task=status&format=json&tid=…returns{status, label, pendingReason, delivered}.deliveredis true when the application handler has accepted the current status, so "Payment confirmed" is shown only when the points or membership actually exist. - Waiting widget —
PayageApi::status_widget($tid, $messages)renders the current message and, while the status is NONE or PENDING-and-undelivered, polls the endpoint every 3 seconds for up to 60 seconds, then swaps the message in place. Applications pass their own wording per status.
If the status is still NONE or PENDING after the polling window, the page says so plainly and points to where the user will see the outcome (the UserPoints activity list, the membership page). The application's own history view shows pending entries as "Awaiting confirmation" with the gateway's pending reason, distinct from failed or cancelled.
Optionally, the handler sends a notification when a payment moves from PENDING to SUCCESS after the user has left, since that is the case where users otherwise assume something went wrong.
Recurring subscriptions
Payage cannot handle recurring payments today, and adding them needs a new subscription record rather than more payment statuses. Every gateway builds one-off charges: Stripe uses mode = 'payment' (StripeNCGatewayModel.php:737), PayPal Standard cmd = _xclick (PayPalGatewayModel.php:689), PayPal Checkout intent = CAPTURE with vault = false (PayPalCheckoutModel.php:170, 416). The Stripe webhook subscribes to four events only, none of them for subscriptions.
In a subscription the gateway holds the schedule and charges the customer itself, then tells the site by webhook. The site never initiates renewals. Gateway mechanisms (event names from memory; check against current API docs before building):
|
Gateway |
Create |
Renewal paid |
Renewal failed |
Ended |
|---|---|---|---|---|
|
Stripe |
Checkout |
|
|
|
|
PayPal (current) |
Subscriptions API, billing plan |
|
|
|
|
PayPal Standard (legacy) |
|
IPN |
IPN |
IPN |
|
Offline |
Not possible |
|
|
|
What Payage needs:
- A
#__payage_subscriptionstable:pg_subscription_id,app_name,app_handler,app_transaction_details,account_id,gw_subscription_id,status(PENDING, ACTIVE, PAST_DUE, CANCELLED, EXPIRED),interval,amount,currency,paid_through. - Each renewal becomes an ordinary payment row with a
pg_subscription_id, so invoices, reports and refunds keep working. Renewals arrive with no Payage tid, so the webhook looks them up bygw_subscription_id; Stripe'stid=0webhook routing already has this shape. get_buttonsgainsinterval(month / year) andinterval_count; gateways that cannot do subscriptions (Offline, possibly PayPal Standard) simply produce no button.SubscriptionHandlerInterface::onSubscriptionChange(SubscriptionSnapshot $s, string $previousStatus), delivered with the same once-per-transition rule.PayageApi::cancel_subscription($pgSubscriptionId)so an application can cancel at the gateway, and a link to the gateway's customer portal (Stripe offers one) for card updates.
The key design rule for membership-type applications: grant access by paid_through (plus a grace period of a few days), not by reacting to each event. If a renewal webhook is late or lost, access continues until the date passes, instead of being cut off or never extended. This is also the MembershipPro lesson in another form: drive access from the authoritative date, and show the user that date.
Suggested order: Stripe first (webhooks are already managed automatically by Payage and its subscription model is the cleanest), then the PayPal Subscriptions API in the PayPal Checkout plugin. Leave PayPal Standard subscriptions out unless an existing site needs them.
Migration
The change can ship without breaking any existing application: app_update_path keeps working, and app_handler takes precedence when both are given.
- Payage: delivery core. Add
app_handler,app_delivered_status,app_delivery_attempts,app_delivery_error. Add the interfaces,PaymentSnapshot, the per-tid lock and the transition table. Move the "call the application" step out ofPaymentController::application_update()into onePaymentDelivery::deliverIfChanged($tid)that runs after every gateway update, includingLAPG_CALLBACK_USER. - Payage: legacy adapter. When only
app_update_pathis set,deliverIfChangedcalls the oldpayment_update($tid)exactly as now, so existing applications see no difference except fewer duplicate calls. - Payage: status endpoint, widget, Redeliver button, Scheduled Task.
- UserPoints: first adopter. Add
PurchaseHandlerand the smallPointsDetailshelpers it uses (credit(),reverse(),markUncredited(); these names are illustrative). Passapp_handlerfromPurchaseHTML::getPayageButtons(). ChangePurchaseControl::complete()to use the status widget and stop writing. - UserPoints: remove
PurchaseUpdate.phpand most ofPurchasePaymentSync. Keep it one release for purchases created before the upgrade, whose rows have onlyapp_update_path. - Payage: DISPUTED status, wired into the Stripe (
charge.dispute.*) and PayPal webhook handlers. - Payage: subscriptions, Stripe first.
Ordering caution for step 4. Today UserPoints' browser-return sync is load-bearing. The Stripe success task verifies the payment with Stripe's API but returns LAPG_CALLBACK_USER, and Payage does not call the application hook for that callback type. If the webhook is lost, the only thing that credits the points is complete() calling PurchasePaymentSync::sync(). complete() must not stop writing until step 1 delivers on LAPG_CALLBACK_USER too.
Open questions
- Lock mechanism: MySQL
GET_LOCKeverywhere, or keep SysV semaphores where available?GET_LOCKis portable but holds a DB connection for the duration. - Which other applications use Payage today, and do any rely on
payment_update()being called repeatedly for the same status? - Subscriptions: which application would be the first consumer, and does it need PayPal as well as Stripe from day one?
- Grace period after
paid_through: fixed in Payage, or set by each application?