Checkout attempts¶
A customer can start checkout more than once on the same order — abandon Apple Pay, then pay by card. Each attempt is a row in paymenthub_payments, and the webhook that reports the outcome has to land on the right one. This describes how attempts are created, how an old one is closed, and what the webhook has to work with.
Why an attempt is hard to identify¶
A provider may hold one record per order and several attempts against it, rather than one record per attempt. Our table is per attempt, so several rows can point at the same ext_payment_id, and only ext_transaction_id tells them apart — set by the webhook, so an attempt that was never carried through never gets one. Two pending rows with no transaction between them look identical to the webhook handler.
That is Frisbii's shape; see Frisbii → One invoice, many transactions for the model and the rule that makes it dangerous to close an attempt at the wrong level.
Creating an attempt¶
PaymentService::createPayment():
$startedAt = now fixed before anything else runs
findPendingPayment( order, provider, gateway ) same gateway → reuse, or cancel if the amount changed
apiService->createPayment() the provider call
save( payment ) PENDING, created_at = $startedAt
findSupersededAttempts( request, $startedAt ) other gateways, started earlier
closeSupersededAttempts() best effort, never fails the checkout
findPendingPayment() keys on gateway, so another payment method gets a row of its own rather than reusing one. The superseded set is therefore read separately, on order_id + provider + PENDING, minus the new gateway.
Ordering by when an attempt began¶
An attempt may only close attempts that began before it did, and created_at is what records that — taken as the first statement of createPayment(), before any lookup or provider call.
Nothing recorded later will do. Ids are handed out at insert, which is after the provider has answered, so of two overlapping checkouts the one whose call returned first takes the lower id whichever the customer started later.
With created_at fixed up front, when the set is read stops mattering, and the set is read late — once this attempt's own row exists. Both directions need that:
- A checkout that started later is filtered out by its own timestamp however early it saved.
- A checkout that started earlier is caught however late it saved. Its row does not exist while it is waiting on a provider call of its own, and a set read before our own call could not hold a row that is not there — so neither attempt would close the other and both would be left pending.
The comparison is made at the precision the column keeps. created_at is a plain datetime, so a row that has been through the database comes back without its microseconds while $startedAt still has its own — and truncation only ever rounds down, so an attempt that began later in the same second would read as earlier and be closed. $startedAt is cut to the same precision first, which makes those a tie.
A tie is excluded, so neither attempt closes the other. That is the safe way round for the session — closing the one the customer just chose cannot be undone — but it is not a fix, and it is worth being plain about what is left:
Known residual. Two cases leave both attempts pending, and
findAdoptablePaymentForHandle()then falls back to the oldest adoptable row — so the first transaction on the invoice can still be attributed to the attempt the customer abandoned:
- Both began within the same second, so the comparison ties.
- The earlier attempt is still waiting on its provider call when we read, so its row does not exist yet. Its call has to outlast our whole round trip for that, which is why the set is read late rather than early.
This is the behaviour that existed before attempts were superseded at all; supersession removes it everywhere else.
Finer timestamps do not close either case — the second one is not about precision but about a row that has not been written yet, so
datetime(6)would buy nothing. Closing them means making the attempt visible before its provider call (a reserved row, which then has to be cleaned up when the call fails, and is adoptable by the webhook in the meantime) or serialising checkouts per order (a lock held across a provider round trip, with no good answer when it times out). Both trade this residual for a new failure class, which is why neither is here.
The old attempt is closed after the new session exists, so a failed creation leaves the customer with the link they already had.
Closing a superseded attempt¶
sequenceDiagram
participant C as createPayment()
participant DB as paymenthub_payments
participant F as Frisbii
participant W as Webhook (separate process)
C->>F: POST /v1/session/charge
F-->>C: new session
C->>DB: INSERT the new attempt (PENDING)
C->>DB: SELECT pending attempts (other gateways, started earlier)
loop each superseded attempt
C->>DB: SELECT the row again
Note over C,DB: not PENDING, or another session → skip
C->>F: DELETE /v1/session/{id}
Note over C,F: fails → row stays PENDING, logged
C->>DB: SELECT the row again
Note over C,DB: the provider call is a round trip of its own
C->>DB: UPDATE status = CANCELED
end
W->>DB: invoice_authorized → the one remaining candidate The provider is asked first and the row only follows when that succeeded. A row closed while its link still works would leave an authorization with no row to land on, and the one the webhook then creates has no gateway to take — a one-off order has no agreement to read one from.
Reads cannot carry across I/O¶
The attempts were collected before the new session was created. A customer who completes the old checkout in either window has it authorized by a webhook holding its own entity, and save() updates on the id alone and sends every mapped column — so writing our entity back would undo the status and drop the transaction the webhook recorded.
The row is therefore read again on both sides of the provider call, and only a still-pending attempt on the same session is closed:
| Read | Why |
|---|---|
| before the provider call | do not delete the session of an attempt that already succeeded |
| after the provider call | the delete is a round trip; the check before it cannot speak for what happened during it |
Known residual. A read only speaks for the moment it ran, so a webhook committing between the second read and the save would still be overwritten. That gap holds no I/O — a null check, a status check and three setters — so the webhook would have to complete its own read and write inside it.
Closing it would take a status-qualified
UPDATE, andORMModel::update()writes on the id alone. Doing that from this package means duplicating the column mapping and the model's update hooks in a subclass, which then silently diverges when the base class changes. It belongs in the ORM, not here, and is tracked there instead.
What the webhook is left with¶
With the superseded attempt closed there is one pending candidate per provider record, which is what the webhook handler needs to attribute an outcome without guessing.
Two cases still reach it with more than one candidate: rows created before this behaviour existed, and an attempt whose session could not be closed. Which row wins then is the handler's rule — Frisbii → Which row an event lands on.
An attempt that leaves no row of its own¶
Supersession only reaches attempts that have a row. AgreementService::createAgreement() writes one only when the provider answers with a payment id, so a customer who leaves the payment window and pays for the same order from somewhere else — the pay-order flow, a new checkout — usually leaves an agreement and nothing else. There is then a single row on the invoice, it is the abandoned attempt's, and the authorization is adopted onto it because nothing else can hold it.
Adopting it is right: the invoice really was paid and the row really was waiting for an outcome. What it must not keep is the gateway — that names the method the customer walked away from, and PaymentEventHandler copies it to the order when the payment is authorized, so the order says Apple Pay for a charge made by card. The payment code Business Central posts it under follows from there.
The gateway is therefore corrected to the one the charge was actually made on — but only ever from the agreement the invoice names in recurring_payment_method. Several attempts can be open at once (maybeReusePendingAgreement() keys on the gateway, so each method gets its own) and a customer can go back and finish an older one, so the newest agreement is not evidence about which of them paid. Only creating a row may fall back to it, because the alternative there is a row — and an order — with no gateway at all.
That id reaches the agreement through customer_payment_method_added, which is a separate Action Scheduler action, so the two webhooks can be processed in either order. Each order is covered from its own side:
| Processed first | What corrects the row |
|---|---|
customer_payment_method_added | invoice_authorized finds the agreement by the id the invoice names, and corrects the row before the transition that writes the order |
invoice_authorized | the row already holds the id — validateInvoiceStatusAndProcess() reads it off the invoice — so the agreement finds what it charged when the id reaches it, and fires payments-hub/payment/gateway-corrected |
PaymentEventHandler listens for that event and moves the correction on to the order, which by then has been paid and has taken its payment method from the row as it was. Only a payment the money was taken on may speak for the order — Payment::isPaid(), the same question the handler asks of a row before keeping it, so a refunded payment still counts: it is the one the order was paid by, and the payment method is what the accounting integration posts it under. A failed or canceled attempt is a row on the same order, not the one that paid it, and a pending one has its authorization still to come — that transition writes the order itself.
Only authorizations correct anything. A failure says nothing about which of several open attempts it belongs to, so a failed row keeps the gateway it was made on.
Known residual. The abandoned agreement stays
PENDINGwith a live checkout session — only payment attempts are superseded, not agreements — so the customer can still complete it. Nothing attributes that to the wrong method, but it is a link that should have been closed.
Cancelling an attempt directly¶
PaymentService::cancelPayment() takes the session path when the payment names a session, and the charge endpoint otherwise. session_id and payment_link are read before paymentCanceling(), because updatePaymentStatus() clears both on the same instance for every status but PENDING — reading afterwards always answered "no session", and the payment fell through to the charge endpoint instead of the session it was written for.
The provider decides what each path may safely touch, and answers its own error codes — the service holds no opinion about either. For Frisbii that means cancelling the charge and never deleting it, and reading 106 as "there was nothing to void": see Frisbii → Cancel, never delete and Frisbii → Error codes.
When cancellation fails, restoreSession() puts the status, the session and the link back, so the payment stays payable. rollback() alone restores only the status. The session fields are set before the rollback so that all three go back in one write: rollbackPaymentStatus() saves and then fires its hooks, and a write placed after it would be separated from the rollback by everything the listeners do.
Both outcomes of the provider call are applied only while the row still holds the status it was left in — CANCELING, or whatever it already was when it could not be moved there:
| Outcome | Without the check |
|---|---|
| the call succeeds | a row a webhook has just authorized is recorded CANCELED, while the reservation at the provider still stands — deleting a checkout session does not undo an authorization |
| the call fails | the restore writes the entity in hand, putting the payment back to PENDING over that authorization and dropping the transaction with it |
The status is captured before the call rather than read off the entity afterwards, because the entity is the thing that may be stale.
Related¶
- Frisbii — the provider model this was written against
- Webhooks — how an outcome reaches the handler
- Database schema —
paymenthub_paymentsand its columns - Gateway integration — the session interface a gateway implements