taler-typescript-core

Wallet core logic and WebUIs for various components
Log | Files | Refs | Submodules | README | LICENSE

commit 71b113f3632b77b8ccd3215fc211c4fbe0219180
parent 03005a3b9f4d252359ff5b0b77f3faf6e56e5998
Author: Florian Dold <dold@taler.net>
Date:   Thu, 26 Nov 2026 00:19:11 +0100

wallet web UI: return to the merchant after a handoff payment

Carry the checkout session into the QR code and payment confirmation.
Redirect the original tab once the merchant reports that its session is
paid.

Issue: https://bugs.taler.net/n/10644

Diffstat:
Mpackages/wallet-webui/src/routes/App.tsx | 33+++++++++++++++++++++++++++------
Mpackages/wallet-webui/src/routes/payment-actions.ts | 10++++++++--
Mpackages/wallet-webui/src/routes/payment-fulfillment.ts | 58+++++++++++++++++++++++++++++++++++-----------------------
Mpackages/wallet-webui/src/routes/payment-model.ts | 48++++++++++++++++++++++++++++++++++++++++++++++--
Mpackages/wallet-webui/src/routes/transaction-model.ts | 5++++-
Mpackages/wallet-webui/src/screens/PaymentScreen.tsx | 24++++++++++++++++++------
Mpackages/wallet-webui/test/payment-model.test.ts | 24++++++++++++++++++++++++
Mpackages/wallet-webui/test/transaction-observation-routes.test.tsx | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
8 files changed, 247 insertions(+), 40 deletions(-)

diff --git a/packages/wallet-webui/src/routes/App.tsx b/packages/wallet-webui/src/routes/App.tsx @@ -130,6 +130,7 @@ import { connectionStatus } from "../stores/ui.js"; import { paymentRepurchaseTarget, paymentResultState, + checkoutHandoffUri, safeWebUrl, } from "./payment-model.js"; import { usePaymentFulfillment } from "./payment-fulfillment.js"; @@ -4220,7 +4221,9 @@ function PaymentRoute({ const [, navigate] = useLocation(); const { fulfillmentTarget, + payUri, browserCheckout, + navigationFailed, complete: completePayment, } = usePaymentFulfillment(platform, actionId); const [actionError, setActionError] = useState<ErrorPresentation>(); @@ -4236,7 +4239,10 @@ function PaymentRoute({ contract, actionError, setActionError, - { automatic: fulfillmentTarget !== undefined }, + { + automatic: fulfillmentTarget !== undefined, + sessionId: payUri?.sessionId, + }, ); const repurchaseTransactionId = paymentRepurchaseTarget(payment); const repurchaseView = useTransactionObservation( @@ -4250,9 +4256,10 @@ function PaymentRoute({ const paymentActionTransactionId = replayPayment?.transactionId ?? transactionId; const resultState = payment - ? paymentResultState(payment, replayPayment) + ? paymentResultState(payment, replayPayment, payUri?.sessionId) : "pending"; - const paymentDone = !!payment && resultState === "done"; + const paymentDone = + !!payment && (resultState === "done" || resultState === "paid-elsewhere"); const fulfillmentUrl = payment?.info?.fulfillmentUrl; const completionReady = view.ready && @@ -4400,6 +4407,7 @@ function PaymentRoute({ } if ( transaction.txState.major === TransactionMajorState.Dialog && + !paymentDone && transaction.txState.minor === TransactionMinorState.WaitingForOtherWallet && transaction.unclaimedPayUri ) @@ -4408,7 +4416,7 @@ function PaymentRoute({ onRetryObservation={view.canRetry ? view.retry : undefined} state="handoff" merchantName={transaction.info.merchant.name} - talerPayUri={transaction.unclaimedPayUri} + talerPayUri={checkoutHandoffUri(transaction.unclaimedPayUri, payUri)} error={actionError} reclaiming={actions.reclaiming} onSelectChoice={() => {}} @@ -4420,7 +4428,7 @@ function PaymentRoute({ onReclaim={() => void actions.reclaim()} /> ); - if (transaction.txState.major === TransactionMajorState.Dialog) + if (transaction.txState.major === TransactionMajorState.Dialog && !paymentDone) return ( <PaymentDialog view={view} @@ -4434,6 +4442,12 @@ function PaymentRoute({ onBack={completeAndReturn} /> ); + const returning = + browserCheckout && + fulfillmentTarget === "current-tab" && + resultState === "paid-elsewhere" && + safeWebUrl(fulfillmentUrl) && + !navigationFailed; const statusTransaction = repurchaseTransactionId ? (replayPayment ?? transaction) : transaction; @@ -4471,7 +4485,14 @@ function PaymentRoute({ ? view.retry : undefined } - state={repurchaseError ? "error" : resultState} + state={ + repurchaseError + ? "error" + : returning + ? "waiting-for-payment" + : resultState + } + returning={returning} contractLoading={contract.loading} contractError={ contract.error diff --git a/packages/wallet-webui/src/routes/payment-actions.ts b/packages/wallet-webui/src/routes/payment-actions.ts @@ -71,7 +71,7 @@ export function usePaymentActions( contract: PaymentContractView, error: ErrorPresentation | undefined, setError: (error: ErrorPresentation | undefined) => void, - options: { automatic?: boolean } = {}, + options: { automatic?: boolean; sessionId?: string } = {}, ): PaymentActions { const { connection } = useServices(); const { language } = useLanguage(); @@ -182,7 +182,13 @@ export function usePaymentActions( if (!choice) return; const result = await callMutation( WalletApiOperation.ConfirmPay, - paymentConfirmationRequest(transactionId, index, choice, collect), + paymentConfirmationRequest( + transactionId, + index, + choice, + collect, + options.sessionId, + ), ["balances", "transactions"], ); if (!isActive(current)) return; diff --git a/packages/wallet-webui/src/routes/payment-fulfillment.ts b/packages/wallet-webui/src/routes/payment-fulfillment.ts @@ -14,8 +14,13 @@ with GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/>. */ +import { + Result, + TalerUriAction, + TalerUris, + type TalerPayUriResult, +} from "@gnu-taler/taler-util"; import { useCallback, useEffect, useState } from "preact/hooks"; -import { Result, TalerUriAction, TalerUris } from "@gnu-taler/taler-util"; import type { ActionEntry, ExternalNavigationTarget, @@ -24,37 +29,37 @@ import type { import { completeActionBestEffort } from "../platform/action-inbox.js"; import { safeWebUrl } from "./payment-model.js"; -function isBrowserCheckout(platform: PlatformAdapter, entry?: ActionEntry) { - if (platform.target === "pwa" || !entry) return false; - const parsed = TalerUris.parse(entry.uri); +function isBrowserCheckout(platform: PlatformAdapter, entry: ActionEntry) { + if (platform.target === "pwa") return false; return ( - Result.isOk(parsed) && - parsed.value.type === TalerUriAction.Pay && - (entry.source === "link" || - entry.source === "metadata" || - (entry.source === "protocol" && - entry.fulfillmentTarget === "current-tab")) + entry.source === "link" || + entry.source === "metadata" || + (entry.source === "protocol" && entry.fulfillmentTarget === "current-tab") ); } +interface PaymentFulfillmentContext { + id: string; + platform: PlatformAdapter; + target: ExternalNavigationTarget; + browserCheckout: boolean; + payUri?: TalerPayUriResult; + active: boolean; + completed: boolean; +} + /** Keep checkout context until payment succeeds, even when ConfirmPay is pending. */ export function usePaymentFulfillment( platform: PlatformAdapter, actionId: string, ) { - const [context, setContext] = useState<{ - id: string; - platform: PlatformAdapter; - target: ExternalNavigationTarget; - browserCheckout: boolean; - active: boolean; - completed: boolean; - }>(); + const [context, setContext] = useState<PaymentFulfillmentContext>(); + const [failedContext, setFailedContext] = useState<typeof context>(); useEffect(() => { - const current = { + const current: PaymentFulfillmentContext = { id: actionId, platform, - target: "new-tab" as ExternalNavigationTarget, + target: "new-tab", browserCheckout: false, active: true, completed: false, @@ -62,8 +67,14 @@ export function usePaymentFulfillment( void (async () => { try { const entry = await platform.actionInbox.get(actionId); + current.payUri = + entry && + Result.orUndefined( + TalerUris.parseRestricted(entry.uri, TalerUriAction.Pay), + ); current.target = entry?.fulfillmentTarget ?? "new-tab"; - current.browserCheckout = isBrowserCheckout(platform, entry); + current.browserCheckout = + !!current.payUri && !!entry && isBrowserCheckout(platform, entry); } catch { // Missing checkout context keeps completion manual. } @@ -85,15 +96,16 @@ export function usePaymentFulfillment( try { await platform.openExternal(url, context.target); } catch { - // The success screen retains its manual fulfillment button. Do not loop - // on transaction notifications or rerenders if navigation is unavailable. + if (context.active) setFailedContext(context); } }, [actionId, context, platform, ready], ); return { + payUri: ready ? context.payUri : undefined, fulfillmentTarget: ready ? context.target : undefined, browserCheckout: ready && context.browserCheckout, + navigationFailed: ready && failedContext === context, complete, }; } diff --git a/packages/wallet-webui/src/routes/payment-model.ts b/packages/wallet-webui/src/routes/payment-model.ts @@ -1,5 +1,10 @@ import { Amounts, + Result, + TalerUris, + TalerUriAction, + type TalerPayUriResult, + type TalerUriString, ChoiceSelectionDetailType, MerchantContractInputType, MerchantContractOutputType, @@ -42,9 +47,11 @@ export function paymentConfirmationRequest( choiceIndex: number, choice: PaymentChoiceView | undefined, collectDonationReceipt: boolean, + sessionId?: string, ): ConfirmPayRequest { return { noWait: true, + ...(sessionId === undefined ? {} : { sessionId }), transactionId, choiceIndex, ...(choice?.forceTokenSelection ? { forcedTokenSel: true } : {}), @@ -81,11 +88,39 @@ export function paymentRepurchaseTarget( return transaction.repurchaseTransactionId; } +/** Keep the released order's credentials and the session of the tab showing the QR. */ +export function checkoutHandoffUri( + publicUri: TalerUriString, + checkout?: TalerPayUriResult, +): TalerUriString { + if (!checkout) return publicUri; + const pay = Result.orUndefined( + TalerUris.parseRestricted(publicUri, TalerUriAction.Pay), + ); + if ( + !pay || + pay.orderId !== checkout.orderId || + pay.sessionId === checkout.sessionId + ) + return publicUri; + return TalerUris.stringify({ ...pay, sessionId: checkout.sessionId }); +} + /** Map a payment and its optional repurchase replay to the payment screen. */ export function paymentResultState( transaction: ObservedPaymentTransaction, replay: ObservedPaymentTransaction | undefined, -): "pending" | "paused" | "done" | "handed-off" | "error" { + sessionId?: string, +): + | "pending" + | "paused" + | "done" + | "paid-elsewhere" + | "waiting-for-payment" + | "handed-off" + | "error" { + if (sessionId && transaction.fulfilledSessions?.includes(sessionId)) + return "paid-elsewhere"; if (paymentRepurchaseTarget(transaction)) { if (!replay) return "pending"; if (replay.txState.major === TransactionMajorState.Done) return "done"; @@ -98,7 +133,16 @@ export function paymentResultState( if ( transaction.txState.minor === TransactionMinorState.ContinuedWithOtherWallet ) - return "handed-off"; + return transaction.txState.major === TransactionMajorState.Pending + ? "waiting-for-payment" + : "handed-off"; + if ( + transaction.txState.major === TransactionMajorState.Done && + transaction.txState.minor === TransactionMinorState.PaidByOther + ) + return transaction.fulfilledSessions + ? "waiting-for-payment" + : "paid-elsewhere"; if (transaction.txState.major === TransactionMajorState.Done) return "done"; if (transaction.txState.major === TransactionMajorState.Pending) return "pending"; diff --git a/packages/wallet-webui/src/routes/transaction-model.ts b/packages/wallet-webui/src/routes/transaction-model.ts @@ -267,7 +267,10 @@ export function transactionStateView(transaction: ObservedTransaction): { switch (transaction.txState.major) { case TransactionMajorState.Done: return { - label: i18n.str`Completed`, + label: + transaction.txState.minor === TransactionMinorState.PaidByOther + ? i18n.str`Paid with another wallet` + : i18n.str`Completed`, detail: i18n.str`This transaction completed successfully.`, tone: "success", }; diff --git a/packages/wallet-webui/src/screens/PaymentScreen.tsx b/packages/wallet-webui/src/screens/PaymentScreen.tsx @@ -157,6 +157,8 @@ export type PaymentScreenState = | "ready" | "paying" | "handoff" + | "waiting-for-payment" + | "paid-elsewhere" | "handed-off" | "pending" | "paused" @@ -464,6 +466,7 @@ export function PaymentLoading(props: { export function PaymentScreen(props: { state: PaymentScreenState; + returning?: boolean; merchantName?: string; merchantWebsite?: string; merchantAddress?: string; @@ -692,14 +695,19 @@ export function PaymentScreen(props: { </ErrorCard> )} - {props.state === "handed-off" && ( + {(props.state === "handed-off" || + props.state === "waiting-for-payment") && ( <Card class="border-primary bg-primaryContainer text-onPrimaryContainer"> <h2 class="text-xl font-semibold">{ /* Translators: The order was handed to another wallet; this does not mean that the other wallet has finished paying. */ i18n.str`Payment continued in another wallet` }</h2> - <p role="status" class="mt-2">{ - /* Translators: Claiming a merchant order assigns it to a wallet for payment; it does not mean that payment has completed. */ i18n.str`The other wallet claimed this payment. You can close this screen.` - }</p> + <p role="status" class="mt-2"> + {props.returning + ? i18n.str`Returning to merchant…` + : props.state === "waiting-for-payment" + ? i18n.str`Waiting for payment in the other wallet.` + : i18n.str`The other wallet claimed this payment. You can close this screen.`} + </p> <div class="mt-5"> <Button onClick={props.onBack}>{i18n.str`Back to wallet`}</Button> </div> @@ -763,10 +771,14 @@ export function PaymentScreen(props: { </ErrorCard> )} - {props.state === "done" && ( + {(props.state === "done" || props.state === "paid-elsewhere") && ( <> <Card class="border-success bg-successContainer text-onSuccessContainer"> - <h2 class="text-xl font-semibold">{i18n.str`Payment complete`}</h2> + <h2 class="text-xl font-semibold"> + {props.state === "paid-elsewhere" + ? i18n.str`Paid with another wallet` + : i18n.str`Payment complete`} + </h2> <p role="status" class="mt-2"> {props.fulfillmentMessage ?? i18n.str`The merchant accepted your payment.`} diff --git a/packages/wallet-webui/test/payment-model.test.ts b/packages/wallet-webui/test/payment-model.test.ts @@ -2,6 +2,9 @@ import assert from "node:assert/strict"; import test from "node:test"; import { ChoiceSelectionDetailType, + TalerUriAction, + TalerUris, + Result, MerchantContractInputType, MerchantContractVersion, MerchantContractOutputType, @@ -16,6 +19,7 @@ import { } from "@gnu-taler/taler-util"; import { activePaymentChoiceIndex, + checkoutHandoffUri, paymentConfirmationRequest, paymentRepurchaseTarget, paymentResultState, @@ -59,6 +63,26 @@ test("payment review keeps an unavailable choice visible", () => { ); }); +test("the QR keeps the released order's credentials and this tab's session", () => { + const parse = (uri: string) => + Result.unpack(TalerUris.parseRestricted(uri, TalerUriAction.Pay)); + const publicUri = TalerUris.stringify( + parse("taler://pay/merchant.example/order/original?c=PUBLIC"), + ); + const checkout = parse( + "taler://pay/merchant.example/order/second?c=OTHER&n=PRIVATE", + ); + const handoff = parse(checkoutHandoffUri(publicUri, checkout)); + assert.equal(handoff.sessionId, "second"); + assert.equal(handoff.claimToken, "PUBLIC"); + assert.equal(handoff.noncePriv, undefined); + assert.equal( + parse(checkoutHandoffUri(publicUri, { ...checkout, sessionId: undefined })) + .sessionId, + undefined, + ); +}); + test("payment confirmation always returns immediately", () => { assert.deepEqual( paymentConfirmationRequest( diff --git a/packages/wallet-webui/test/transaction-observation-routes.test.tsx b/packages/wallet-webui/test/transaction-observation-routes.test.tsx @@ -577,6 +577,90 @@ for (const url of ["https://merchant.example/fulfilled", undefined]) { }); } +test("checkout waits for external payment and navigates once", async () => { + const url = "https://merchant.example/fulfilled"; + const h = await harness("payment-review", url); + try { + const snapshot = h.readySnapshot; + assert.ok(snapshot.type === TransactionType.Payment); + const publish = ( + major: TransactionMajorState, + minor: TransactionMinorState, + ) => + h.act(async () => + h.publish({ + ...snapshot, + transaction: { ...snapshot.transaction, txState: { major, minor } }, + payment: null, + confirmation: { unavailableReasons: ["not-proposed"] }, + }), + ); + await h.waitFor(() => assert.equal(h.registrations.length, 1)); + await publish( + TransactionMajorState.Pending, + TransactionMinorState.ContinuedWithOtherWallet, + ); + await h.waitFor(() => + assert.ok(h.view.getByText("Waiting for payment in the other wallet.")), + ); + assert.deepEqual(h.navigations, []); + assert.deepEqual(h.completions, []); + await publish( + TransactionMajorState.Done, + TransactionMinorState.PaidByOther, + ); + await h.waitFor(() => + assert.ok(h.view.getByText("Returning to merchant…")), + ); + await publish( + TransactionMajorState.Done, + TransactionMinorState.PaidByOther, + ); + assert.deepEqual(h.completions, [h.entry.id]); + assert.deepEqual(h.navigations, [{ url, target: "current-tab" }]); + } finally { + await h.close(); + } +}); + +test("an equivalent payment in another session cannot redirect this checkout", async () => { + const url = "https://merchant.example/fulfilled"; + const h = await harness("payment-review", url); + try { + const initial = h.readySnapshot; + assert.ok(initial.type === TransactionType.Payment); + await h.act(async () => h.releaseDocument()); + const paid = { + ...initial.transaction, + txState: { + major: TransactionMajorState.Done, + minor: TransactionMinorState.PaidByOther, + }, + fulfilledSessions: ["other-session"], + }; + await h.act(async () => h.publish({ ...initial, transaction: paid })); + await h.waitFor(() => + assert.ok(h.view.getByText("Waiting for payment in the other wallet.")), + ); + assert.deepEqual(h.navigations, []); + assert.ok(await h.services.platform.actionInbox.get(h.entry.id)); + await h.act(async () => + h.publish({ + ...initial, + transaction: { + ...paid, + fulfilledSessions: ["other-session", "session"], + }, + }), + ); + await h.waitFor(() => + assert.deepEqual(h.navigations, [{ url, target: "current-tab" }]), + ); + } finally { + await h.close(); + } +}); + test("a failed claim observation shows retry despite retained claim progress", async () => { const h = await harness("payment-claim"); try { @@ -1065,6 +1149,7 @@ for (const route of ["payment-review", "payment-review-details"] as const) { const request = h.paymentRequests[0]; assert.equal(request.operation, WalletApiOperation.ConfirmPay); assert.deepEqual(request.args, { + ...(route === "payment-review" ? { sessionId: "session" } : {}), transactionId: h.transactionId, choiceIndex: 0, noWait: true,