commit 4ea226543158ece0318ae70024b668fdb27c3afd
parent cb305704b09979b23b0054d7bf5436d58000048c
Author: Florian Dold <dold@taler.net>
Date: Thu, 26 Nov 2026 00:18:16 +0100
wallet-core: track payment after another wallet claims an order
A claim tells the first wallet who holds the order. Keep watching the
merchant until payment is confirmed, and record which checkout sessions
the merchant has fulfilled.
Issue: https://bugs.taler.net/n/10644
Diffstat:
6 files changed, 499 insertions(+), 206 deletions(-)
diff --git a/packages/taler-harness/src/integrationtests/test-payment-unclaim.ts b/packages/taler-harness/src/integrationtests/test-payment-unclaim.ts
@@ -160,7 +160,7 @@ export async function runPaymentUnclaimTest(t: GlobalTestState) {
await firstWallet.call(WalletApiOperation.TestingWaitTransactionState, {
transactionId: firstPrepared.transactionId,
txState: {
- major: TransactionMajorState.Aborted,
+ major: TransactionMajorState.Pending,
minor: TransactionMinorState.ContinuedWithOtherWallet,
},
});
@@ -170,4 +170,11 @@ export async function runPaymentUnclaimTest(t: GlobalTestState) {
choiceIndex: 0,
});
t.assertTrue(paid.type === ConfirmPayResultType.Done);
+ await firstWallet.call(WalletApiOperation.TestingWaitTransactionState, {
+ transactionId: firstPrepared.transactionId,
+ txState: {
+ major: TransactionMajorState.Done,
+ minor: TransactionMinorState.PaidByOther,
+ },
+ });
}
diff --git a/packages/taler-util/src/types-taler-wallet-observations.ts b/packages/taler-util/src/types-taler-wallet-observations.ts
@@ -180,6 +180,7 @@ export interface ObservedPaymentTransaction extends ObservedTransactionCommon {
type: TransactionType.Payment;
merchantBaseUrl: string;
unclaimedPayUri?: TalerUriString;
+ fulfilledSessions?: string[];
info: OrderShortInfo | undefined;
totalRefundRaw: AmountString;
totalRefundEffective: AmountString;
@@ -453,6 +454,7 @@ export function observedTransaction(
type: transaction.type,
merchantBaseUrl: transaction.merchantBaseUrl,
unclaimedPayUri: transaction.unclaimedPayUri,
+ fulfilledSessions: transaction.fulfilledSessions,
info: transaction.info,
totalRefundRaw: transaction.totalRefundRaw,
totalRefundEffective: transaction.totalRefundEffective,
diff --git a/packages/taler-util/src/types-taler-wallet-transactions.ts b/packages/taler-util/src/types-taler-wallet-transactions.ts
@@ -783,6 +783,9 @@ export interface TransactionPayment extends TransactionCommon {
*/
unclaimedPayUri?: TalerUriString;
+ /** Merchant sessions fulfilled by an equivalent order paid in another wallet. */
+ fulfilledSessions?: string[];
+
/**
* Additional information about the payment.
*
diff --git a/packages/taler-wallet-core/src/db/records.ts b/packages/taler-wallet-core/src/db/records.ts
@@ -913,6 +913,8 @@ export interface WalletDonationPlanchet {
* "purchases" object stores.
*/
export interface WalletProposalDownloadInfo {
+ /** HTTP 200 confirms this order. HTTP 402 can fulfill an individual session. */
+ externalPayment?: "order-paid" | WalletExternalPaymentSessions;
/** Refunds for older paid purchases that have no payInfo. */
accountedRefunds?: AccountedCoinRefunds;
contractTermsHash: string;
@@ -921,6 +923,15 @@ export interface WalletProposalDownloadInfo {
contractTermsMerchantSig: string;
}
+export interface WalletExternalPaymentSessions {
+ observing:
+ | PurchaseStatus.DialogShared
+ | PurchaseStatus.DialogUnclaimed
+ | PurchaseStatus.PendingClaimedByOther;
+ pending: (string | null)[];
+ fulfilled: string[];
+}
+
export interface WalletTokenSelection {
tokenPubs: string[];
}
@@ -2196,6 +2207,12 @@ export enum PurchaseStatus {
*/
DialogUnclaimed = 0x0101_0002,
+ /** Another wallet claimed the released order. Keep watching for payment. */
+ PendingClaimedByOther = 0x0100_0006,
+
+ /** Merchant confirmed fulfillment without a local spend. */
+ DonePaidByOther = 0x0500_0002,
+
/**
* Generic failure, check error code.
*/
diff --git a/packages/taler-wallet-core/src/pay-merchant.test.ts b/packages/taler-wallet-core/src/pay-merchant.test.ts
@@ -682,6 +682,262 @@ test("unclaimed payments wait for and finish neutrally in another wallet", () =>
);
});
+const externalCheckoutCases: {
+ name: string;
+ initial: PurchaseStatus;
+ response: 200 | 202 | 402 | 404;
+ overdue?: boolean;
+ alreadyPaidOrder?: string;
+ expected: PurchaseStatus;
+}[] = [
+ {
+ name: "fast payment before claim notification",
+ initial: PurchaseStatus.DialogUnclaimed,
+ response: 200,
+ expected: PurchaseStatus.DonePaidByOther,
+ },
+ {
+ name: "shared order paid without a local spend",
+ initial: PurchaseStatus.DialogShared,
+ response: 200,
+ expected: PurchaseStatus.DonePaidByOther,
+ },
+ {
+ name: "reorder URL for a claimed order",
+ initial: PurchaseStatus.PendingClaimedByOther,
+ response: 202,
+ expected: PurchaseStatus.PendingClaimedByOther,
+ },
+ {
+ name: "the merchant recognizes a paid order for this session",
+ initial: PurchaseStatus.DialogUnclaimed,
+ response: 402,
+ alreadyPaidOrder: "previous-order",
+ expected: PurchaseStatus.DonePaidByOther,
+ },
+ {
+ name: "the merchant deleted the order after handoff",
+ initial: PurchaseStatus.PendingClaimedByOther,
+ response: 404,
+ expected: PurchaseStatus.AbortedOrderDeleted,
+ },
+ {
+ name: "payment completed while offline past expiry",
+ initial: PurchaseStatus.PendingClaimedByOther,
+ overdue: true,
+ response: 200,
+ expected: PurchaseStatus.DonePaidByOther,
+ },
+ {
+ name: "expired handoff still unpaid",
+ initial: PurchaseStatus.DialogUnclaimed,
+ overdue: true,
+ response: 402,
+ expected: PurchaseStatus.Expired,
+ },
+];
+
+for (const scenario of externalCheckoutCases) {
+ test(`external checkout: ${scenario.name}`, async (t) => {
+ const runner = await makeIdbRunner();
+ try {
+ // The test contract's pay deadline is 300 seconds since the epoch.
+ t.mock.timers.enable({
+ apis: ["Date"],
+ now: scenario.overdue ? 400_000 : 200_000,
+ });
+ const purchase = makeDownloadedPurchase(
+ "external-payment",
+ scenario.initial,
+ );
+ purchase.payInfo = undefined;
+ purchase.shared = scenario.initial === PurchaseStatus.DialogShared;
+ await runner.runReadWriteTx(async (tx) => {
+ await upsertTestContractTerms(tx, purchase);
+ await tx.upsertPurchase(purchase);
+ });
+ const urls: URL[] = [];
+ const wex = {
+ runWalletDbTx: runner.runReadWriteTx.bind(runner),
+ ws: { networkAvailable: true, longpollQueue: new LongpollQueue() },
+ http: {
+ fetch: async (url: string) => {
+ urls.push(new URL(url));
+ const headers = new HeadersImpl();
+ headers.set("content-type", "application/json");
+ return {
+ status: scenario.response,
+ requestUrl: url,
+ requestMethod: "GET",
+ headers,
+ json: async () =>
+ ({
+ 200: {
+ refunded: false,
+ refund_pending: false,
+ refund_amount: "TESTKUDOS:0",
+ refund_taken: "TESTKUDOS:0",
+ },
+ 202: { public_reorder_url: "https://merchant.example/new" },
+ 402: {
+ taler_pay_uri: purchase.talerUri,
+ already_paid_order_id: scenario.alreadyPaidOrder,
+ },
+ 404: { code: TalerErrorCode.MERCHANT_GENERIC_ORDER_UNKNOWN },
+ })[scenario.response],
+ };
+ },
+ },
+ } as unknown as WalletExecutionContext;
+ await processPurchase(wex, purchase.proposalId);
+ assert.equal(urls.length, 1);
+ const params = urls[0].searchParams;
+ assert.equal(params.get("session_id"), purchase.downloadSessionId);
+ assert.equal(params.has("timeout_ms"), !scenario.overdue);
+ assert.equal(params.has("h_contract"), purchase.shared);
+ assert.equal(params.has("token"), !purchase.shared);
+ const stored = await runner.runReadWriteTx((tx) =>
+ tx.getPurchase(purchase.proposalId),
+ );
+ assert.equal(stored?.purchaseStatus, scenario.expected);
+ assert.equal(stored?.timestampFirstSuccessfulPay, undefined);
+ assert.equal(stored?.payInfo, undefined);
+ if (scenario.response === 404) {
+ assert.equal(
+ stored?.abortReason?.code,
+ TalerErrorCode.MERCHANT_GENERIC_ORDER_UNKNOWN,
+ );
+ }
+ } finally {
+ await runner.close();
+ }
+ });
+}
+
+for (const makeRunner of runnerFactories) {
+ test(`${makeRunner.name}: a paid sibling order fulfills only the requested checkout session`, async (t) => {
+ t.mock.timers.enable({ apis: ["Date"], now: 200_000 });
+ const runner = await makeRunner();
+ try {
+ const purchase = makeDownloadedPurchase(
+ "external-session",
+ PurchaseStatus.DialogShared,
+ );
+ purchase.shared = true;
+ purchase.payInfo = undefined;
+ await runner.runReadWriteTx(async (tx) => {
+ await upsertTestContractTerms(tx, purchase);
+ await tx.upsertPurchase(purchase);
+ });
+ let start!: () => void, release!: () => void;
+ const started = new Promise<void>((resolve) => {
+ start = resolve;
+ });
+ const held = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ let paid = false;
+ const sessions: (string | null)[] = [];
+ const wex = {
+ runWalletDbTx: runner.runReadWriteTx.bind(runner),
+ ws: { networkAvailable: true, longpollQueue: new LongpollQueue() },
+ taskScheduler: { resetTask: async () => {} },
+ http: {
+ fetch: async (url: string) => {
+ const params = new URL(url).searchParams;
+ assert.ok(params.has("h_contract"));
+ const session = params.get("session_id");
+ sessions.push(session);
+ if (session === "session") {
+ start();
+ await held;
+ }
+ const headers = new HeadersImpl();
+ headers.set("content-type", "application/json");
+ return {
+ status: paid ? 200 : 402,
+ requestUrl: url,
+ requestMethod: "GET",
+ headers,
+ json: async () =>
+ paid
+ ? {
+ refunded: false,
+ refund_pending: false,
+ refund_amount: "TESTKUDOS:0",
+ refund_taken: "TESTKUDOS:0",
+ }
+ : {
+ taler_pay_uri: purchase.talerUri,
+ already_paid_order_id: session ? "sibling" : undefined,
+ },
+ };
+ },
+ },
+ } as unknown as WalletExecutionContext;
+ const prepare = (session: string) =>
+ preparePayForUriV2(
+ wex,
+ `taler://pay/merchant.example/order/${session}`,
+ );
+ const read = () =>
+ runner.runReadWriteTx((tx) => tx.getPurchase(purchase.proposalId));
+ const notifications: WalletNotification[] = [];
+ runner.setNotificationSink((n) => notifications.push(n));
+ const first = processPurchase(wex, purchase.proposalId);
+ await started;
+ await prepare("second");
+ notifications.length = 0;
+ release();
+ await first;
+ assert.ok(
+ notifications.some(
+ (n) => n.type === NotificationType.TransactionStateTransition,
+ ),
+ );
+ let record = await read();
+ assert.equal(record?.purchaseStatus, PurchaseStatus.DialogShared);
+ assert.deepEqual(record?.download?.externalPayment, {
+ observing: PurchaseStatus.DialogShared,
+ pending: ["second"],
+ fulfilled: ["session"],
+ });
+
+ await processPurchase(wex, purchase.proposalId);
+ assert.equal(
+ (await read())?.purchaseStatus,
+ PurchaseStatus.DonePaidByOther,
+ );
+ await prepare("session");
+ assert.equal(
+ (await read())?.purchaseStatus,
+ PurchaseStatus.DonePaidByOther,
+ );
+ await prepare("");
+ assert.equal((await read())?.purchaseStatus, PurchaseStatus.DialogShared);
+ await processPurchase(wex, purchase.proposalId);
+ record = await read();
+ assert.equal(record?.purchaseStatus, PurchaseStatus.DialogShared);
+ assert.deepEqual(record?.download?.externalPayment, {
+ observing: PurchaseStatus.DialogShared,
+ pending: [null],
+ fulfilled: ["session", "second"],
+ });
+ paid = true;
+ await processPurchase(wex, purchase.proposalId);
+ await prepare("third");
+ assert.equal((await read())?.download?.externalPayment, "order-paid");
+ assert.equal(
+ (await read())?.purchaseStatus,
+ PurchaseStatus.DonePaidByOther,
+ );
+ assert.deepEqual(sessions, ["session", "second", null, null]);
+ } finally {
+ await runner.close();
+ }
+ });
+}
+
test("deleting a proposed payment only uses local state", async () => {
const runner = await makeIdbRunner();
const proposalId = "delete-proposed-payment";
diff --git a/packages/taler-wallet-core/src/pay-merchant.ts b/packages/taler-wallet-core/src/pay-merchant.ts
@@ -159,6 +159,7 @@ import {
WalletDonationPlanchet,
WalletPurchase,
WalletPurchasePayInfo,
+ WalletExternalPaymentSessions,
WalletRefundGroup,
WalletRefundItem,
WalletRefreshGroup,
@@ -389,6 +390,9 @@ export class PayMerchantTransactionContext implements TransactionContext {
return undefined;
}
+ const externalPayment =
+ purchaseRec.download?.externalPayment ??
+ externalPaymentState(purchaseRec);
const txState = computePayMerchantTransactionState(purchaseRec);
const unclaimedPayUri =
purchaseRec.purchaseStatus === PurchaseStatus.DialogUnclaimed
@@ -500,6 +504,12 @@ export class PayMerchantTransactionContext implements TransactionContext {
merchantBaseUrl: purchaseRec.merchantBaseUrl,
txState,
unclaimedPayUri,
+ fulfilledSessions:
+ externalPayment &&
+ externalPayment !== "order-paid" &&
+ externalPayment.fulfilled.length
+ ? externalPayment.fulfilled
+ : undefined,
stId: purchaseRec.purchaseStatus,
scopes,
txActions: computePayMerchantTransactionActions(purchaseRec),
@@ -2137,7 +2147,10 @@ export async function createOrReusePurchase(
}
}
}
- if (isSharedPurchase(oldProposal)) {
+ const external =
+ externalPaymentState(oldProposal) &&
+ (await registerExternalSession(wex, oldCtx, sessionId));
+ if (external || isSharedPurchase(oldProposal)) {
// Preparing a payment is deliberately local-only. Wake the transaction
// task so that it can check the merchant asynchronously.
await wex.taskScheduler.resetTask(oldCtx.taskId);
@@ -3671,12 +3684,7 @@ export async function confirmPay(
}
}
- let sessionId: string | undefined;
- if (sessionIdOverride !== undefined) {
- sessionId = sessionIdOverride;
- } else {
- sessionId = proposal.downloadSessionId;
- }
+ const sessionId = sessionIdOverride ?? proposedPaymentSession(proposal);
logger.trace(
`recording payment on ${proposal.orderId} with session ID ${sessionId}`,
@@ -3933,9 +3941,9 @@ export async function processPurchase(
case PurchaseStatus.PendingAcceptRefund:
return processPurchaseAcceptRefund(wex, purchase);
case PurchaseStatus.DialogShared:
- return processPurchaseDialogShared(wex, purchase);
case PurchaseStatus.DialogUnclaimed:
- return processPurchaseDialogUnclaimed(wex, purchase);
+ case PurchaseStatus.PendingClaimedByOther:
+ return observeExternalPayment(wex, purchase);
case PurchaseStatus.DialogProposed:
return processPurchaseDialogProposed(wex, purchase);
case PurchaseStatus.FailedClaim:
@@ -3943,6 +3951,7 @@ export async function processPurchase(
case PurchaseStatus.DoneRepurchaseDetected:
case PurchaseStatus.AbortedProposalRefused:
case PurchaseStatus.AbortedIncompletePayment:
+ case PurchaseStatus.DonePaidByOther:
case PurchaseStatus.AbortedClaimedByOther:
case PurchaseStatus.AbortedOrderDeleted:
case PurchaseStatus.AbortedRefunded:
@@ -4874,6 +4883,16 @@ export function computePayMerchantTransactionState(
major: TransactionMajorState.Dialog,
minor: TransactionMinorState.Proposed,
};
+ case PurchaseStatus.PendingClaimedByOther:
+ return {
+ major: TransactionMajorState.Pending,
+ minor: TransactionMinorState.ContinuedWithOtherWallet,
+ };
+ case PurchaseStatus.DonePaidByOther:
+ return {
+ major: TransactionMajorState.Done,
+ minor: TransactionMinorState.PaidByOther,
+ };
case PurchaseStatus.DialogUnclaimed:
return {
major: TransactionMajorState.Dialog,
@@ -5027,6 +5046,8 @@ export function computePayMerchantTransactionActions(
case PurchaseStatus.DialogShared:
return [TransactionAction.Retry, TransactionAction.Delete];
case PurchaseStatus.DialogUnclaimed:
+ case PurchaseStatus.PendingClaimedByOther:
+ case PurchaseStatus.DonePaidByOther:
return [TransactionAction.Delete];
// Final States
case PurchaseStatus.AbortedProposalRefused:
@@ -5063,12 +5084,22 @@ export function computePayMerchantTransactionActions(
}
}
+function proposedPaymentSession(purchase: WalletPurchase): string | undefined {
+ const external = purchase.download?.externalPayment;
+ if (external && external !== "order-paid" && external.pending.length) {
+ // A checkout with a named session supplies it explicitly on confirmation.
+ if (external.pending.includes(null)) return undefined;
+ return external.pending[0] ?? undefined;
+ }
+ return purchase.downloadSessionId;
+}
+
function makePublicPayUri(purchase: WalletPurchase) {
return TalerUris.stringify({
type: TalerUriAction.Pay,
merchantBaseUrl: purchase.merchantBaseUrl as HostPortPath,
orderId: purchase.orderId,
- sessionId: purchase.lastSessionId ?? purchase.downloadSessionId,
+ sessionId: purchase.lastSessionId ?? proposedPaymentSession(purchase),
claimToken: purchase.claimToken,
});
}
@@ -5176,6 +5207,7 @@ export async function reclaimPayment(
switch (purchase.purchaseStatus) {
case PurchaseStatus.DialogProposed:
case PurchaseStatus.DialogUnclaimed:
+ purchase.downloadSessionId = proposedPaymentSession(purchase);
purchase.purchaseStatus = PurchaseStatus.PendingDownloadingProposal;
purchase.failReason = undefined;
await handle.update(purchase, "reclaim", BalanceEffect.None);
@@ -5298,219 +5330,195 @@ async function processPurchaseDialogProposed(
return TaskRunResult.runAgainAt(expiry);
}
-/**
- * While the transaction is in the dialog(shared) state,
- * we long-poll the merchant. We do this to find out if
- * another wallet paid for the order.
- */
-async function processPurchaseDialogShared(
- wex: WalletExecutionContext,
- purchase: WalletPurchase,
-): Promise<TaskRunResult> {
- const proposalId = purchase.proposalId;
- logger.trace(`processing dialog-shared for proposal ${proposalId}`);
- const ctx = new PayMerchantTransactionContext(wex, proposalId);
- const txRes = await wex.runWalletDbTx(async (tx) => {
- const rec = await tx.getPurchase(proposalId);
- if (!rec) {
- return undefined;
- }
- const download = await expectProposalDownloadByIdInTx(wex, tx, proposalId);
- return { download, rec };
- });
- if (!txRes) {
- // Transaction longer exists.
- return TaskRunResult.finished();
- }
- const { download, rec } = txRes;
- if (purchase.purchaseStatus !== PurchaseStatus.DialogShared) {
- return TaskRunResult.finished();
- }
-
- const contractTerms = download.contractTerms;
-
- let paidByOther = false;
-
- const merchantClient = walletMerchantClient(
- contractTerms.merchant_base_url,
- wex,
- );
- const resp = await suspendForLongpoll(wex, () =>
- merchantClient.getPaymentStatus(contractTerms.order_id, {
- contractTermHash: download.contractTermsHash,
- sessionId: rec.lastSessionId ?? undefined,
- timeout: MERCHANT_ORDER_STATUS_LONGPOLL_MS,
- }),
- );
-
- if (isOrderUnknown(resp)) {
- // The merchant deleted the order, so no other wallet can pay it anymore
- // and there is nothing left to watch for.
- await wex.runWalletDbTx(async (tx) => {
- const [p, h] = await ctx.getRecordHandle(tx);
- if (p?.purchaseStatus !== PurchaseStatus.DialogShared) {
- return;
- }
- p.purchaseStatus = PurchaseStatus.AbortedOrderDeleted;
- p.abortReason =
- resp.case === HttpStatusCode.NotFound ? resp.detail : undefined;
- await h.update(p, "shared-order-gone");
- });
- return TaskRunResult.progress();
- }
-
- switch (resp.case) {
- case "ok": // 200 paid
- case HttpStatusCode.Accepted: // 202 goto
- paidByOther = true;
- break;
- case HttpStatusCode.PaymentRequired: // 402 unpaid
- if (resp.body.already_paid_order_id != null) {
- paidByOther = true;
- }
- break;
- }
-
- if (!paidByOther) {
- return TaskRunResult.backoff();
+function externalPaymentState(
+ p: WalletPurchase,
+): WalletExternalPaymentSessions | undefined {
+ const status = p.purchaseStatus;
+ if (
+ status !== PurchaseStatus.DialogShared &&
+ status !== PurchaseStatus.DialogUnclaimed &&
+ status !== PurchaseStatus.PendingClaimedByOther &&
+ status !== PurchaseStatus.DonePaidByOther
+ )
+ return;
+ if (!p.download || p.download.externalPayment === "order-paid") return;
+ if (p.download.externalPayment) return p.download.externalPayment;
+ const session = p.lastSessionId ?? p.downloadSessionId ?? null;
+ // A terminal record from an older wallet does not distinguish HTTP 200
+ // from a session-specific HTTP 402. Recheck it when the session changes.
+ if (status === PurchaseStatus.DonePaidByOther) {
+ if (session === null) return;
+ return {
+ observing: isSharedPurchase(p)
+ ? PurchaseStatus.DialogShared
+ : PurchaseStatus.DialogUnclaimed,
+ pending: [],
+ fulfilled: [session],
+ };
}
+ return { observing: status, pending: [session], fulfilled: [] };
+}
- await wex.runWalletDbTx(async (tx) => {
+async function registerExternalSession(
+ wex: WalletExecutionContext,
+ ctx: PayMerchantTransactionContext,
+ sessionId: string | undefined,
+): Promise<boolean> {
+ return wex.runWalletDbTx(async (tx) => {
const [p, h] = await ctx.getRecordHandle(tx);
- switch (p?.purchaseStatus) {
- case PurchaseStatus.DialogShared:
- p.purchaseStatus = PurchaseStatus.FailedPaidByOther;
- p.failReason = makeErrorDetail(
- TalerErrorCode.WALLET_TRANSACTION_COMPLETED_BY_OTHER_WALLET,
- {},
- "order paid by another wallet",
- );
- break;
- default:
- return;
- }
- await h.update(p, "shared-paid-by-other");
+ if (!p?.download) return false;
+ const state = externalPaymentState(p);
+ if (
+ !state ||
+ state.pending.includes(sessionId ?? null) ||
+ (sessionId && state.fulfilled.includes(sessionId))
+ )
+ return false;
+ state.pending.push(sessionId ?? null);
+ p.download.externalPayment = state;
+ p.purchaseStatus = state.observing;
+ await h.update(p, "observe-external-session", BalanceEffect.None);
+ return true;
});
- return TaskRunResult.progress();
}
-async function processPurchaseDialogUnclaimed(
+/** Observe payment without committing coins from this wallet. */
+async function observeExternalPayment(
wex: WalletExecutionContext,
purchase: WalletPurchase,
): Promise<TaskRunResult> {
- const proposalId = purchase.proposalId;
- const ctx = new PayMerchantTransactionContext(wex, proposalId);
- const txRes = await wex.runWalletDbTx(async (tx) => {
- const rec = await tx.getPurchase(proposalId);
- if (!rec) {
- return undefined;
- }
- const download = await expectProposalDownloadByIdInTx(wex, tx, proposalId);
- return { download, rec };
- });
- if (!txRes || txRes.rec.purchaseStatus !== PurchaseStatus.DialogUnclaimed) {
- return TaskRunResult.finished();
- }
-
- const expiry = AbsoluteTime.addDuration(
- AbsoluteTime.fromProtocolTimestamp(
- txRes.download.contractTerms.pay_deadline,
- ),
- Duration.fromSpec({ seconds: 10 }),
- );
- if (AbsoluteTime.isExpired(expiry)) {
- await wex.runWalletDbTx(async (tx) => {
- const [rec, handle] = await ctx.getRecordHandle(tx);
- if (rec?.purchaseStatus !== PurchaseStatus.DialogUnclaimed) {
- return;
- }
- rec.timestampExpired = timestampPreciseToDb(TalerPreciseTimestamp.now());
- rec.purchaseStatus = PurchaseStatus.Expired;
- await handle.update(rec, "unclaimed-order-expired");
- });
- return TaskRunResult.progress();
- }
-
- const merchantClient = walletMerchantClient(
- txRes.download.contractTerms.merchant_base_url,
- wex,
- );
- let response = await suspendForLongpoll(wex, () =>
- merchantClient.getPaymentStatus(txRes.download.contractTerms.order_id, {
- claimToken: txRes.rec.claimToken,
- sessionId: txRes.rec.lastSessionId ?? undefined,
- timeout: MERCHANT_ORDER_STATUS_LONGPOLL_MS,
- }),
+ const state = externalPaymentState(purchase)!;
+ const status = state.observing;
+ const ctx = new PayMerchantTransactionContext(wex, purchase.proposalId);
+ const download = await expectProposalDownload(wex, purchase);
+ const merchant = walletMerchantClient(purchase.merchantBaseUrl, wex);
+ const expired = AbsoluteTime.isExpired(
+ getProposalExpiry(download.contractTerms),
);
-
- // The claim token keeps the long-poll authorized while the order is
- // unclaimed. A 402 response alone does not reveal whether another wallet
- // has claimed it, because the token remains valid for the newly generated
- // contract. Probe once with the old contract hash after the long-poll
- // returns: the merchant distinguishes the unclaimed order from a new claim
- // with its error code.
- if (
- response.case === HttpStatusCode.PaymentRequired &&
- response.body.already_paid_order_id == null
- ) {
- response = await merchantClient.getPaymentStatus(
- txRes.download.contractTerms.order_id,
- {
- contractTermHash: txRes.download.contractTermsHash,
- sessionId: txRes.rec.lastSessionId ?? undefined,
- },
- );
- }
-
- if (isOrderUnknown(response)) {
- await wex.runWalletDbTx(async (tx) => {
- const [rec, handle] = await ctx.getRecordHandle(tx);
- if (rec?.purchaseStatus !== PurchaseStatus.DialogUnclaimed) {
- return;
- }
- rec.purchaseStatus = PurchaseStatus.AbortedOrderDeleted;
- rec.abortReason =
- response.case === HttpStatusCode.NotFound ? response.detail : undefined;
- await handle.update(rec, "unclaimed-order-gone");
+ const longpoll = !expired && state.pending.length === 1;
+ const check = async (sessionId: string | undefined) => {
+ let response = await merchant.getPaymentStatus(purchase.orderId, {
+ ...(status === PurchaseStatus.DialogShared
+ ? { contractTermHash: download.contractTermsHash }
+ : { claimToken: purchase.claimToken }),
+ sessionId,
+ timeout: longpoll ? MERCHANT_ORDER_STATUS_LONGPOLL_MS : undefined,
});
- return TaskRunResult.progress();
- }
- if (
- response.case === HttpStatusCode.Forbidden &&
- response.detail?.code ===
- TalerErrorCode.MERCHANT_GET_ORDERS_ID_INVALID_CONTRACT_HASH
- ) {
- return TaskRunResult.longpollReturnedPending();
- }
+ // The token authorizes both the released and newly claimed order. Only
+ // probe the previous hash until the other wallet's claim is established.
+ if (
+ status === PurchaseStatus.DialogUnclaimed &&
+ !expired &&
+ response.case === HttpStatusCode.PaymentRequired &&
+ !response.body.already_paid_order_id
+ ) {
+ response = await merchant.getPaymentStatus(purchase.orderId, {
+ contractTermHash: download.contractTermsHash,
+ sessionId,
+ });
+ }
- const claimed =
- response.case === "ok" ||
- response.case === HttpStatusCode.Accepted ||
- response.case === HttpStatusCode.PaymentRequired ||
- (response.case === HttpStatusCode.Forbidden &&
- response.detail?.code ===
- TalerErrorCode.MERCHANT_GENERIC_CONTRACT_HASH_DOES_NOT_MATCH_ORDER);
- if (!claimed) {
- throw TalerError.fromDetail(
- TalerErrorCode.WALLET_UNEXPECTED_REQUEST_ERROR,
- getHttpResponseErrorDetails(response.response),
- "checking whether the released order was claimed failed",
- );
+ if (response.case === HttpStatusCode.NotFound && isOrderUnknown(response))
+ return { kind: "deleted", reason: response.detail } as const;
+ if (response.case === "ok") return { kind: "paid" } as const;
+ if (
+ sessionId &&
+ response.case === HttpStatusCode.PaymentRequired &&
+ response.body.already_paid_order_id
+ )
+ return { kind: "fulfilled", sessionId } as const;
+ if (
+ expired &&
+ (response.case === HttpStatusCode.PaymentRequired ||
+ response.case === HttpStatusCode.Accepted)
+ ) {
+ return { kind: "expired" } as const;
+ } else if (
+ status === PurchaseStatus.DialogUnclaimed &&
+ (response.case === HttpStatusCode.Accepted ||
+ response.case === HttpStatusCode.PaymentRequired ||
+ (response.case === HttpStatusCode.Forbidden &&
+ response.detail?.code ===
+ TalerErrorCode.MERCHANT_GENERIC_CONTRACT_HASH_DOES_NOT_MATCH_ORDER))
+ ) {
+ return { kind: "claimed" } as const;
+ } else if (
+ response.case === HttpStatusCode.PaymentRequired ||
+ (status === PurchaseStatus.DialogUnclaimed &&
+ response.case === HttpStatusCode.Forbidden &&
+ response.detail?.code ===
+ TalerErrorCode.MERCHANT_GET_ORDERS_ID_INVALID_CONTRACT_HASH)
+ ) {
+ return { kind: "pending" } as const;
+ } else if (response.case === HttpStatusCode.Accepted) {
+ // A reorder URL is not a payment confirmation.
+ return { kind: "reorder" } as const;
+ } else {
+ throw TalerError.fromDetail(
+ TalerErrorCode.WALLET_UNEXPECTED_REQUEST_ERROR,
+ getHttpResponseErrorDetails(response.response),
+ "checking external payment status failed",
+ );
+ }
+ };
+ const results = await suspendForLongpoll(wex, () =>
+ Promise.all(state.pending.map((session) => check(session ?? undefined))),
+ );
+ if (results.every((r) => r.kind === "pending" || r.kind === "reorder")) {
+ if (state.pending.length > 1)
+ return TaskRunResult.runAgainAfter({ seconds: 1 });
+ return results[0]?.kind === "reorder"
+ ? TaskRunResult.backoff()
+ : TaskRunResult.longpollReturnedPending();
}
-
await wex.runWalletDbTx(async (tx) => {
const [rec, handle] = await ctx.getRecordHandle(tx);
- if (rec?.purchaseStatus !== PurchaseStatus.DialogUnclaimed) {
+ if (
+ rec?.purchaseStatus !== status ||
+ !rec.download ||
+ rec.download.contractTermsHash !== purchase.download?.contractTermsHash
+ )
return;
+ const current = externalPaymentState(rec)!;
+ const deleted = results.find((r) => r.kind === "deleted");
+ if (results.some((r) => r.kind === "paid")) {
+ rec.purchaseStatus = PurchaseStatus.DonePaidByOther;
+ rec.download.externalPayment = "order-paid";
+ } else if (deleted) {
+ rec.purchaseStatus = PurchaseStatus.AbortedOrderDeleted;
+ rec.abortReason = deleted.reason;
+ } else {
+ for (const result of results) {
+ if (
+ result.kind === "fulfilled" &&
+ !current.fulfilled.includes(result.sessionId)
+ ) {
+ current.fulfilled.push(result.sessionId);
+ current.pending = current.pending.filter(
+ (id) => id !== result.sessionId,
+ );
+ }
+ }
+ if (results.some((r) => r.kind === "claimed"))
+ current.observing = PurchaseStatus.PendingClaimedByOther;
+ rec.download.externalPayment = current;
+ rec.purchaseStatus = current.pending.length
+ ? current.observing
+ : PurchaseStatus.DonePaidByOther;
+ if (
+ results.some((r) => r.kind === "expired") &&
+ current.pending.every((id) => state.pending.includes(id))
+ ) {
+ rec.purchaseStatus = PurchaseStatus.Expired;
+ rec.timestampExpired = timestampPreciseToDb(
+ TalerPreciseTimestamp.now(),
+ );
+ }
}
- rec.purchaseStatus = PurchaseStatus.AbortedClaimedByOther;
- rec.abortReason = makeErrorDetail(
- TalerErrorCode.WALLET_TRANSACTION_COMPLETED_BY_OTHER_WALLET,
- {},
- "order claimed by another wallet",
- );
- await handle.update(rec, "unclaimed-order-claimed-by-other");
+ await handle.update(rec, "external-payment-status", BalanceEffect.None, {
+ detailsChanged: results.some((r) => r.kind === "fulfilled"),
+ });
});
return TaskRunResult.progress();
}