From 1925a399f816b147c690dd5a494340d69af8bd4f Mon Sep 17 00:00:00 2001 From: Jakub Binczyk Date: Tue, 17 Nov 2026 22:27:58 +0100 Subject: [PATCH 1/5] feat(POINT-3697)(dc): poll the transaction after a lost opener When opener_loss_handling is on and DC decides the PSP tab lost its link to the checkout, DC now shows an awaiting-confirmation view with a Cancel button and polls GET invoices/{id}?expand=transaction: - right away, on focus / visibilitychange, then every 3 s while visible; - authorized / pending-capture / completed -> payment_success; - failed / voided / blocked -> payment_error; - after 15 min -> payment_pending {reason: opener_isolated, timeout: true}; - Cancel -> payment_cancelled {tab_closed: true}. No event is emitted while polling. A late postMessage token and the poller can't both report an outcome: the first one wins. --- src/dynamic-checkout/locales/ar.ts | 3 + src/dynamic-checkout/locales/bg.ts | 3 + src/dynamic-checkout/locales/bn.ts | 3 + src/dynamic-checkout/locales/cs.ts | 3 + src/dynamic-checkout/locales/da.ts | 3 + src/dynamic-checkout/locales/de.ts | 3 + src/dynamic-checkout/locales/el.ts | 3 + src/dynamic-checkout/locales/en.ts | 3 + src/dynamic-checkout/locales/es.ts | 3 + src/dynamic-checkout/locales/fi.ts | 3 + src/dynamic-checkout/locales/fr.ts | 3 + src/dynamic-checkout/locales/he.ts | 3 + src/dynamic-checkout/locales/hi.ts | 3 + src/dynamic-checkout/locales/id.ts | 3 + src/dynamic-checkout/locales/it.ts | 3 + src/dynamic-checkout/locales/ja.ts | 3 + src/dynamic-checkout/locales/kn.ts | 3 + src/dynamic-checkout/locales/ko.ts | 3 + src/dynamic-checkout/locales/nb.ts | 3 + src/dynamic-checkout/locales/nl.ts | 3 + src/dynamic-checkout/locales/pl.ts | 3 + src/dynamic-checkout/locales/pt.ts | 3 + src/dynamic-checkout/locales/ro.ts | 3 + src/dynamic-checkout/locales/ru.ts | 3 + src/dynamic-checkout/locales/sv.ts | 3 + src/dynamic-checkout/locales/ta.ts | 3 + src/dynamic-checkout/locales/te.ts | 3 + src/dynamic-checkout/locales/th.ts | 3 + src/dynamic-checkout/locales/tr.ts | 3 + src/dynamic-checkout/locales/uk.ts | 3 + src/dynamic-checkout/locales/vi.ts | 3 + src/dynamic-checkout/locales/zh-cn.ts | 2 + src/dynamic-checkout/locales/zh-tw.ts | 2 + src/dynamic-checkout/payment-methods/apm.ts | 36 ++- .../payment-methods/saved-apm.ts | 31 ++- src/dynamic-checkout/references.ts | 3 + src/dynamic-checkout/utils/events.ts | 2 + .../utils/opener-loss-flow.ts | 154 ++++++++++++ .../utils/transaction-poller.ts | 179 ++++++++++++++ .../views/payment-awaiting-confirmation.ts | 60 +++++ .../dynamic-checkout/opener-loss-flow.test.ts | 179 ++++++++++++++ .../transaction-poller.test.ts | 227 ++++++++++++++++++ test/support/loadNamespace.ts | 38 ++- 43 files changed, 999 insertions(+), 7 deletions(-) create mode 100644 src/dynamic-checkout/utils/opener-loss-flow.ts create mode 100644 src/dynamic-checkout/utils/transaction-poller.ts create mode 100644 src/dynamic-checkout/views/payment-awaiting-confirmation.ts create mode 100644 test/dynamic-checkout/opener-loss-flow.test.ts create mode 100644 test/dynamic-checkout/transaction-poller.test.ts diff --git a/src/dynamic-checkout/locales/ar.ts b/src/dynamic-checkout/locales/ar.ts index bd845d7d..a46f0e50 100644 --- a/src/dynamic-checkout/locales/ar.ts +++ b/src/dynamic-checkout/locales/ar.ts @@ -23,6 +23,9 @@ module ProcessOut { "payment-success-message": "اكتملت عملية الدفع هذه.", "payment-info-message": "نقوم بمعالجة عملية الدفع الخاصة بك. يمكنك الآن إغلاق هذه النافذة.", "payment-pending-message": "عملية الدفع الخاصة بك قيد الانتظار.", + "payment-awaiting-confirmation-message": + "أكمل الدفع في علامة التبويب الأخرى. سيتم تحديث هذه الصفحة تلقائيًا.", + "payment-awaiting-confirmation-cancel-button": "إلغاء", "payment-error-generic-message": "لم نتمكن من معالجة عملية الدفع الخاصة بك.", "verification-success-message": "اكتملت عملية التحقق هذه.", "verification-cancelled-message": "تم إلغاء عملية التحقق.", diff --git a/src/dynamic-checkout/locales/bg.ts b/src/dynamic-checkout/locales/bg.ts index 88360ba4..dd085c56 100644 --- a/src/dynamic-checkout/locales/bg.ts +++ b/src/dynamic-checkout/locales/bg.ts @@ -23,6 +23,9 @@ module ProcessOut { "payment-success-message": "Това плащане е завършено.", "payment-info-message": "Обработваме вашето плащане. Вече можете да затворите този прозорец.", "payment-pending-message": "Плащането ви е в изчакване.", + "payment-awaiting-confirmation-message": + "Завършете плащането в другия раздел. Тази страница ще се обнови автоматично.", + "payment-awaiting-confirmation-cancel-button": "Отказ", "payment-error-generic-message": "Не успяхме да обработим плащането ви.", "verification-success-message": "Тази проверка е завършена.", "verification-cancelled-message": "Проверката беше отменена.", diff --git a/src/dynamic-checkout/locales/bn.ts b/src/dynamic-checkout/locales/bn.ts index 2a64be16..6fc527a2 100644 --- a/src/dynamic-checkout/locales/bn.ts +++ b/src/dynamic-checkout/locales/bn.ts @@ -24,6 +24,9 @@ module ProcessOut { "payment-info-message": "আমরা আপনার পেমেন্ট প্রক্রিয়া করছি। আপনি এখন এই উইন্ডোটি বন্ধ করতে পারেন।", "payment-pending-message": "আপনার পেমেন্ট মুলতুবি রয়েছে।", + "payment-awaiting-confirmation-message": + "অন্য ট্যাবে পেমেন্টটি সম্পন্ন করুন। এই পৃষ্ঠাটি স্বয়ংক্রিয়ভাবে আপডেট হবে।", + "payment-awaiting-confirmation-cancel-button": "বাতিল করুন", "payment-error-generic-message": "আমরা আপনার পেমেন্ট প্রক্রিয়া করতে পারিনি।", "verification-success-message": "এই যাচাইকরণ সম্পন্ন হয়েছে।", "verification-cancelled-message": "যাচাইকরণ বাতিল করা হয়েছে।", diff --git a/src/dynamic-checkout/locales/cs.ts b/src/dynamic-checkout/locales/cs.ts index 91f83d63..e787b40b 100644 --- a/src/dynamic-checkout/locales/cs.ts +++ b/src/dynamic-checkout/locales/cs.ts @@ -23,6 +23,9 @@ module ProcessOut { "payment-success-message": "Tato platba byla dokončena.", "payment-info-message": "Vaši platbu zpracováváme. Toto okno můžete nyní zavřít.", "payment-pending-message": "Vaše platba čeká na zpracování.", + "payment-awaiting-confirmation-message": + "Dokončete platbu na druhé kartě. Tato stránka se automaticky aktualizuje.", + "payment-awaiting-confirmation-cancel-button": "Zrušit", "payment-error-generic-message": "Vaši platbu se nepodařilo zpracovat.", "verification-success-message": "Toto ověření bylo dokončeno.", "verification-cancelled-message": "Ověření bylo zrušeno.", diff --git a/src/dynamic-checkout/locales/da.ts b/src/dynamic-checkout/locales/da.ts index 314d37bd..7ce63c7f 100644 --- a/src/dynamic-checkout/locales/da.ts +++ b/src/dynamic-checkout/locales/da.ts @@ -23,6 +23,9 @@ module ProcessOut { "payment-success-message": "Denne betaling er gennemført.", "payment-info-message": "Vi behandler din betaling. Du kan nu lukke dette vindue.", "payment-pending-message": "Din betaling afventer.", + "payment-awaiting-confirmation-message": + "Gennemfør betalingen i den anden fane. Denne side opdateres automatisk.", + "payment-awaiting-confirmation-cancel-button": "Annuller", "payment-error-generic-message": "Vi kunne ikke behandle din betaling.", "verification-success-message": "Denne verificering er gennemført.", "verification-cancelled-message": "Verificeringen er blevet annulleret.", diff --git a/src/dynamic-checkout/locales/de.ts b/src/dynamic-checkout/locales/de.ts index af46c684..68dde6b7 100644 --- a/src/dynamic-checkout/locales/de.ts +++ b/src/dynamic-checkout/locales/de.ts @@ -24,6 +24,9 @@ module ProcessOut { "payment-info-message": "Wir verarbeiten Ihre Zahlung. Sie können dieses Fenster jetzt schließen.", "payment-pending-message": "Ihre Zahlung steht noch aus.", + "payment-awaiting-confirmation-message": + "Schließen Sie die Zahlung im anderen Tab ab. Diese Seite wird automatisch aktualisiert.", + "payment-awaiting-confirmation-cancel-button": "Abbrechen", "payment-error-generic-message": "Wir konnten Ihre Zahlung nicht verarbeiten.", "verification-success-message": "Diese Verifizierung wurde abgeschlossen.", "verification-cancelled-message": "Die Verifizierung wurde abgebrochen.", diff --git a/src/dynamic-checkout/locales/el.ts b/src/dynamic-checkout/locales/el.ts index cd6cd93f..94988549 100644 --- a/src/dynamic-checkout/locales/el.ts +++ b/src/dynamic-checkout/locales/el.ts @@ -24,6 +24,9 @@ module ProcessOut { "payment-info-message": "Επεξεργαζόμαστε την πληρωμή σας. Μπορείτε τώρα να κλείσετε αυτό το παράθυρο.", "payment-pending-message": "Η πληρωμή σας εκκρεμεί.", + "payment-awaiting-confirmation-message": + "Ολοκληρώστε την πληρωμή στην άλλη καρτέλα. Αυτή η σελίδα θα ενημερωθεί αυτόματα.", + "payment-awaiting-confirmation-cancel-button": "Ακύρωση", "payment-error-generic-message": "Δεν ήταν δυνατή η επεξεργασία της πληρωμής σας.", "verification-success-message": "Η επαλήθευση ολοκληρώθηκε.", "verification-cancelled-message": "Η επαλήθευση ακυρώθηκε.", diff --git a/src/dynamic-checkout/locales/en.ts b/src/dynamic-checkout/locales/en.ts index 7b5bcbcf..9d91f218 100644 --- a/src/dynamic-checkout/locales/en.ts +++ b/src/dynamic-checkout/locales/en.ts @@ -23,6 +23,9 @@ module ProcessOut { "payment-success-message": "This payment is completed.", "payment-info-message": "We are processing your payment. You can now close this window.", "payment-pending-message": "Your payment is pending.", + "payment-awaiting-confirmation-message": + "Complete the payment in the other tab. This page will update automatically.", + "payment-awaiting-confirmation-cancel-button": "Cancel", "payment-error-generic-message": "We were unable to process your payment.", "verification-success-message": "This verification is completed.", "verification-cancelled-message": "Verification has been cancelled.", diff --git a/src/dynamic-checkout/locales/es.ts b/src/dynamic-checkout/locales/es.ts index da269256..3ebc876b 100644 --- a/src/dynamic-checkout/locales/es.ts +++ b/src/dynamic-checkout/locales/es.ts @@ -23,6 +23,9 @@ module ProcessOut { "payment-success-message": "Este pago se ha completado.", "payment-info-message": "Estamos procesando su pago. Puede cerrar esta ventana.", "payment-pending-message": "Su pago está pendiente.", + "payment-awaiting-confirmation-message": + "Completa el pago en la otra pestaña. Esta página se actualizará automáticamente.", + "payment-awaiting-confirmation-cancel-button": "Cancelar", "payment-error-generic-message": "No pudimos procesar su pago.", "verification-success-message": "Esta verificación se ha completado.", "verification-cancelled-message": "La verificación ha sido cancelada.", diff --git a/src/dynamic-checkout/locales/fi.ts b/src/dynamic-checkout/locales/fi.ts index 31f41184..aa1f5b0f 100644 --- a/src/dynamic-checkout/locales/fi.ts +++ b/src/dynamic-checkout/locales/fi.ts @@ -23,6 +23,9 @@ module ProcessOut { "payment-success-message": "Tämä maksu on suoritettu.", "payment-info-message": "Käsittelemme maksuasi. Voit nyt sulkea tämän ikkunan.", "payment-pending-message": "Maksusi on käsittelyssä.", + "payment-awaiting-confirmation-message": + "Viimeistele maksu toisella välilehdellä. Tämä sivu päivittyy automaattisesti.", + "payment-awaiting-confirmation-cancel-button": "Peruuta", "payment-error-generic-message": "Maksuasi ei voitu käsitellä.", "verification-success-message": "Tämä vahvistus on suoritettu.", "verification-cancelled-message": "Vahvistus on peruutettu.", diff --git a/src/dynamic-checkout/locales/fr.ts b/src/dynamic-checkout/locales/fr.ts index e4752087..5680cba4 100644 --- a/src/dynamic-checkout/locales/fr.ts +++ b/src/dynamic-checkout/locales/fr.ts @@ -24,6 +24,9 @@ module ProcessOut { "payment-info-message": "Nous travaillons sur votre paiement. Vous pouvez maintenant fermer cette fenêtre.", "payment-pending-message": "Votre paiement est en attente.", + "payment-awaiting-confirmation-message": + "Finalisez le paiement dans l'autre onglet. Cette page se mettra à jour automatiquement.", + "payment-awaiting-confirmation-cancel-button": "Annuler", "payment-error-generic-message": "Nous n'avons pas pu traiter votre paiement.", "verification-success-message": "Cette vérification a été effectuée avec succès.", "verification-cancelled-message": "La vérification a été annulée.", diff --git a/src/dynamic-checkout/locales/he.ts b/src/dynamic-checkout/locales/he.ts index 5be9aed3..9c14cf75 100644 --- a/src/dynamic-checkout/locales/he.ts +++ b/src/dynamic-checkout/locales/he.ts @@ -23,6 +23,9 @@ module ProcessOut { "payment-success-message": "התשלום הושלם.", "payment-info-message": "התשלום שלכם בטיפול. כעת ניתן לסגור חלון זה.", "payment-pending-message": "התשלום שלכם ממתין לאישור.", + "payment-awaiting-confirmation-message": + "השלימו את התשלום בכרטיסייה האחרת. דף זה יתעדכן אוטומטית.", + "payment-awaiting-confirmation-cancel-button": "ביטול", "payment-error-generic-message": "לא הצלחנו לעבד את התשלום שלכם.", "verification-success-message": "האימות הושלם.", "verification-cancelled-message": "האימות בוטל.", diff --git a/src/dynamic-checkout/locales/hi.ts b/src/dynamic-checkout/locales/hi.ts index f29ef770..5751ea16 100644 --- a/src/dynamic-checkout/locales/hi.ts +++ b/src/dynamic-checkout/locales/hi.ts @@ -23,6 +23,9 @@ module ProcessOut { "payment-success-message": "यह भुगतान पूरा हो गया है।", "payment-info-message": "हम आपके भुगतान को संसाधित कर रहे हैं। अब आप यह विंडो बंद कर सकते हैं।", "payment-pending-message": "आपका भुगतान लंबित है।", + "payment-awaiting-confirmation-message": + "दूसरे टैब में भुगतान पूरा करें। यह पेज अपने आप अपडेट हो जाएगा।", + "payment-awaiting-confirmation-cancel-button": "रद्द करें", "payment-error-generic-message": "हम आपका भुगतान संसाधित नहीं कर सके।", "verification-success-message": "यह सत्यापन पूरा हो गया है।", "verification-cancelled-message": "सत्यापन रद्द कर दिया गया है।", diff --git a/src/dynamic-checkout/locales/id.ts b/src/dynamic-checkout/locales/id.ts index e318a258..c25706de 100644 --- a/src/dynamic-checkout/locales/id.ts +++ b/src/dynamic-checkout/locales/id.ts @@ -24,6 +24,9 @@ module ProcessOut { "payment-info-message": "Kami sedang memproses pembayaran Anda. Anda dapat menutup jendela ini sekarang.", "payment-pending-message": "Pembayaran Anda sedang menunggu.", + "payment-awaiting-confirmation-message": + "Selesaikan pembayaran di tab lain. Halaman ini akan diperbarui secara otomatis.", + "payment-awaiting-confirmation-cancel-button": "Batal", "payment-error-generic-message": "Kami tidak dapat memproses pembayaran Anda.", "verification-success-message": "Verifikasi ini telah selesai.", "verification-cancelled-message": "Verifikasi telah dibatalkan.", diff --git a/src/dynamic-checkout/locales/it.ts b/src/dynamic-checkout/locales/it.ts index 58922c7f..ed9cfd9b 100644 --- a/src/dynamic-checkout/locales/it.ts +++ b/src/dynamic-checkout/locales/it.ts @@ -24,6 +24,9 @@ module ProcessOut { "payment-info-message": "Stiamo elaborando il tuo pagamento. Ora puoi chiudere questa finestra.", "payment-pending-message": "Il tuo pagamento è in sospeso.", + "payment-awaiting-confirmation-message": + "Completa il pagamento nell'altra scheda. Questa pagina si aggiornerà automaticamente.", + "payment-awaiting-confirmation-cancel-button": "Annulla", "payment-error-generic-message": "Non è stato possibile elaborare il pagamento.", "verification-success-message": "La verifica è stata completata.", "verification-cancelled-message": "La verifica è stata annullata.", diff --git a/src/dynamic-checkout/locales/ja.ts b/src/dynamic-checkout/locales/ja.ts index 09bb5cc0..67e3791f 100644 --- a/src/dynamic-checkout/locales/ja.ts +++ b/src/dynamic-checkout/locales/ja.ts @@ -24,6 +24,9 @@ module ProcessOut { "payment-info-message": "お支払いを処理しています。このウィンドウを閉じていただいて構いません。", "payment-pending-message": "お支払いは保留中です。", + "payment-awaiting-confirmation-message": + "もう一方のタブでお支払いを完了してください。このページは自動的に更新されます。", + "payment-awaiting-confirmation-cancel-button": "キャンセル", "payment-error-generic-message": "お支払いを処理できませんでした。", "verification-success-message": "確認が完了しました。", "verification-cancelled-message": "確認がキャンセルされました。", diff --git a/src/dynamic-checkout/locales/kn.ts b/src/dynamic-checkout/locales/kn.ts index 80ad137a..7318b83c 100644 --- a/src/dynamic-checkout/locales/kn.ts +++ b/src/dynamic-checkout/locales/kn.ts @@ -24,6 +24,9 @@ module ProcessOut { "payment-info-message": "ನಿಮ್ಮ ಪಾವತಿಯನ್ನು ನಾವು ಪ್ರಕ್ರಿಯೆಗೊಳಿಸುತ್ತಿದ್ದೇವೆ. ಈಗ ನೀವು ಈ ವಿಂಡೋವನ್ನು ಮುಚ್ಚಬಹುದು.", "payment-pending-message": "ನಿಮ್ಮ ಪಾವತಿ ಬಾಕಿ ಇದೆ.", + "payment-awaiting-confirmation-message": + "ಇನ್ನೊಂದು ಟ್ಯಾಬ್‌ನಲ್ಲಿ ಪಾವತಿಯನ್ನು ಪೂರ್ಣಗೊಳಿಸಿ. ಈ ಪುಟವು ಸ್ವಯಂಚಾಲಿತವಾಗಿ ನವೀಕರಿಸಲ್ಪಡುತ್ತದೆ.", + "payment-awaiting-confirmation-cancel-button": "ರದ್ದುಮಾಡಿ", "payment-error-generic-message": "ನಿಮ್ಮ ಪಾವತಿಯನ್ನು ಪ್ರಕ್ರಿಯೆಗೊಳಿಸಲು ನಮಗೆ ಸಾಧ್ಯವಾಗಲಿಲ್ಲ.", "verification-success-message": "ಈ ಪರಿಶೀಲನೆ ಪೂರ್ಣಗೊಂಡಿದೆ.", "verification-cancelled-message": "ಪರಿಶೀಲನೆಯನ್ನು ರದ್ದುಗೊಳಿಸಲಾಗಿದೆ.", diff --git a/src/dynamic-checkout/locales/ko.ts b/src/dynamic-checkout/locales/ko.ts index e819d52e..a03fe870 100644 --- a/src/dynamic-checkout/locales/ko.ts +++ b/src/dynamic-checkout/locales/ko.ts @@ -23,6 +23,9 @@ module ProcessOut { "payment-success-message": "결제가 완료되었습니다.", "payment-info-message": "결제를 처리하고 있습니다. 이 창을 닫으셔도 됩니다.", "payment-pending-message": "결제가 대기 중입니다.", + "payment-awaiting-confirmation-message": + "다른 탭에서 결제를 완료하세요. 이 페이지는 자동으로 업데이트됩니다.", + "payment-awaiting-confirmation-cancel-button": "취소", "payment-error-generic-message": "결제를 처리할 수 없습니다.", "verification-success-message": "인증이 완료되었습니다.", "verification-cancelled-message": "인증이 취소되었습니다.", diff --git a/src/dynamic-checkout/locales/nb.ts b/src/dynamic-checkout/locales/nb.ts index b0b2af3f..ce4dea79 100644 --- a/src/dynamic-checkout/locales/nb.ts +++ b/src/dynamic-checkout/locales/nb.ts @@ -23,6 +23,9 @@ module ProcessOut { "payment-success-message": "Denne betalingen er fullført.", "payment-info-message": "Vi behandler betalingen din. Du kan nå lukke dette vinduet.", "payment-pending-message": "Betalingen din er under behandling.", + "payment-awaiting-confirmation-message": + "Fullfør betalingen i den andre fanen. Denne siden oppdateres automatisk.", + "payment-awaiting-confirmation-cancel-button": "Avbryt", "payment-error-generic-message": "Vi kunne ikke behandle betalingen din.", "verification-success-message": "Denne verifiseringen er fullført.", "verification-cancelled-message": "Verifiseringen er kansellert.", diff --git a/src/dynamic-checkout/locales/nl.ts b/src/dynamic-checkout/locales/nl.ts index a663e08a..0004de6e 100644 --- a/src/dynamic-checkout/locales/nl.ts +++ b/src/dynamic-checkout/locales/nl.ts @@ -23,6 +23,9 @@ module ProcessOut { "payment-success-message": "Deze betaling is voltooid.", "payment-info-message": "We verwerken uw betaling. U kunt dit venster nu sluiten.", "payment-pending-message": "Uw betaling is in behandeling.", + "payment-awaiting-confirmation-message": + "Rond de betaling af in het andere tabblad. Deze pagina wordt automatisch bijgewerkt.", + "payment-awaiting-confirmation-cancel-button": "Annuleren", "payment-error-generic-message": "We konden uw betaling niet verwerken.", "verification-success-message": "Deze verificatie is voltooid.", "verification-cancelled-message": "De verificatie is geannuleerd.", diff --git a/src/dynamic-checkout/locales/pl.ts b/src/dynamic-checkout/locales/pl.ts index b25bcc73..af4972c5 100644 --- a/src/dynamic-checkout/locales/pl.ts +++ b/src/dynamic-checkout/locales/pl.ts @@ -23,6 +23,9 @@ module ProcessOut { "payment-success-message": "Płatność została zakończona pomyślnie.", "payment-info-message": "Przetwarzamy Twoją płatność. Możesz teraz zamknąć tę okno.", "payment-pending-message": "Twoja płatność oczekuje na realizację.", + "payment-awaiting-confirmation-message": + "Dokończ płatność w drugiej karcie. Ta strona zaktualizuje się automatycznie.", + "payment-awaiting-confirmation-cancel-button": "Anuluj", "payment-error-generic-message": "Nie udało nam się przetworzyć Twojej płatności.", "verification-success-message": "Weryfikacja została zakończona pomyślnie.", "verification-cancelled-message": "Weryfikacja została anulowana.", diff --git a/src/dynamic-checkout/locales/pt.ts b/src/dynamic-checkout/locales/pt.ts index 6d33cfe2..fd2b949e 100644 --- a/src/dynamic-checkout/locales/pt.ts +++ b/src/dynamic-checkout/locales/pt.ts @@ -23,6 +23,9 @@ module ProcessOut { "payment-success-message": "Este pagamento foi concluído.", "payment-info-message": "Estamos a processar o seu pagamento. Pode agora fechar esta janela.", "payment-pending-message": "O seu pagamento está pendente.", + "payment-awaiting-confirmation-message": + "Conclua o pagamento na outra aba. Esta página será atualizada automaticamente.", + "payment-awaiting-confirmation-cancel-button": "Cancelar", "payment-error-generic-message": "Não foi possível processar o seu pagamento.", "verification-success-message": "Esta verificação foi concluída.", "verification-cancelled-message": "A verificação foi cancelada.", diff --git a/src/dynamic-checkout/locales/ro.ts b/src/dynamic-checkout/locales/ro.ts index 1fed728b..18fed697 100644 --- a/src/dynamic-checkout/locales/ro.ts +++ b/src/dynamic-checkout/locales/ro.ts @@ -24,6 +24,9 @@ module ProcessOut { "payment-info-message": "Plata dumneavoastră este în curs de procesare. Puteți închide această fereastră.", "payment-pending-message": "Plata dumneavoastră este în așteptare.", + "payment-awaiting-confirmation-message": + "Finalizați plata în cealaltă filă. Această pagină se va actualiza automat.", + "payment-awaiting-confirmation-cancel-button": "Anulează", "payment-error-generic-message": "Nu am putut procesa plata dumneavoastră.", "verification-success-message": "Verificarea a fost finalizată.", "verification-cancelled-message": "Verificarea a fost anulată.", diff --git a/src/dynamic-checkout/locales/ru.ts b/src/dynamic-checkout/locales/ru.ts index 910fdd3e..cf9a3d96 100644 --- a/src/dynamic-checkout/locales/ru.ts +++ b/src/dynamic-checkout/locales/ru.ts @@ -23,6 +23,9 @@ module ProcessOut { "payment-success-message": "Платёж завершён.", "payment-info-message": "Мы обрабатываем ваш платёж. Вы можете закрыть это окно.", "payment-pending-message": "Ваш платёж ожидает подтверждения.", + "payment-awaiting-confirmation-message": + "Завершите оплату в другой вкладке. Эта страница обновится автоматически.", + "payment-awaiting-confirmation-cancel-button": "Отмена", "payment-error-generic-message": "Нам не удалось обработать ваш платёж.", "verification-success-message": "Проверка завершена.", "verification-cancelled-message": "Проверка отменена.", diff --git a/src/dynamic-checkout/locales/sv.ts b/src/dynamic-checkout/locales/sv.ts index 95dbe351..06f6e45f 100644 --- a/src/dynamic-checkout/locales/sv.ts +++ b/src/dynamic-checkout/locales/sv.ts @@ -23,6 +23,9 @@ module ProcessOut { "payment-success-message": "Betalningen är slutförd.", "payment-info-message": "Vi behandlar din betalning. Du kan nu stänga det här fönstret.", "payment-pending-message": "Din betalning väntar på behandling.", + "payment-awaiting-confirmation-message": + "Slutför betalningen i den andra fliken. Den här sidan uppdateras automatiskt.", + "payment-awaiting-confirmation-cancel-button": "Avbryt", "payment-error-generic-message": "Vi kunde inte behandla din betalning.", "verification-success-message": "Verifieringen är slutförd.", "verification-cancelled-message": "Verifieringen har avbrutits.", diff --git a/src/dynamic-checkout/locales/ta.ts b/src/dynamic-checkout/locales/ta.ts index cfe8e935..cc6b5ff7 100644 --- a/src/dynamic-checkout/locales/ta.ts +++ b/src/dynamic-checkout/locales/ta.ts @@ -23,6 +23,9 @@ module ProcessOut { "payment-success-message": "இந்தக் கட்டணம் முடிந்தது.", "payment-info-message": "உங்கள் கட்டணத்தைச் செயலாக்குகிறோம். இப்போது இந்தச் சாளரத்தை மூடலாம்.", "payment-pending-message": "உங்கள் கட்டணம் நிலுவையில் உள்ளது.", + "payment-awaiting-confirmation-message": + "மற்ற தாவலில் கட்டணத்தை முடிக்கவும். இந்தப் பக்கம் தானாகவே புதுப்பிக்கப்படும்.", + "payment-awaiting-confirmation-cancel-button": "ரத்துசெய்", "payment-error-generic-message": "உங்கள் கட்டணத்தைச் செயலாக்க முடியவில்லை.", "verification-success-message": "இந்தச் சரிபார்ப்பு முடிந்தது.", "verification-cancelled-message": "சரிபார்ப்பு ரத்து செய்யப்பட்டது.", diff --git a/src/dynamic-checkout/locales/te.ts b/src/dynamic-checkout/locales/te.ts index 31977313..eec150a5 100644 --- a/src/dynamic-checkout/locales/te.ts +++ b/src/dynamic-checkout/locales/te.ts @@ -24,6 +24,9 @@ module ProcessOut { "payment-info-message": "మేము మీ చెల్లింపును ప్రాసెస్ చేస్తున్నాము. మీరు ఇప్పుడు ఈ విండోను మూసివేయవచ్చు.", "payment-pending-message": "మీ చెల్లింపు పెండింగ్‌లో ఉంది.", + "payment-awaiting-confirmation-message": + "మరో ట్యాబ్‌లో చెల్లింపును పూర్తి చేయండి. ఈ పేజీ స్వయంచాలకంగా అప్‌డేట్ అవుతుంది.", + "payment-awaiting-confirmation-cancel-button": "రద్దు చేయి", "payment-error-generic-message": "మేము మీ చెల్లింపును ప్రాసెస్ చేయలేకపోయాము.", "verification-success-message": "ఈ ధృవీకరణ పూర్తయింది.", "verification-cancelled-message": "ధృవీకరణ రద్దు చేయబడింది.", diff --git a/src/dynamic-checkout/locales/th.ts b/src/dynamic-checkout/locales/th.ts index eb313208..6b892d6b 100644 --- a/src/dynamic-checkout/locales/th.ts +++ b/src/dynamic-checkout/locales/th.ts @@ -23,6 +23,9 @@ module ProcessOut { "payment-success-message": "การชำระเงินเสร็จสมบูรณ์แล้ว", "payment-info-message": "เรากำลังดำเนินการชำระเงินของคุณ คุณสามารถปิดหน้าต่างนี้ได้", "payment-pending-message": "การชำระเงินของคุณอยู่ระหว่างรอดำเนินการ", + "payment-awaiting-confirmation-message": + "ชำระเงินให้เสร็จสิ้นในแท็บอื่น หน้านี้จะอัปเดตโดยอัตโนมัติ", + "payment-awaiting-confirmation-cancel-button": "ยกเลิก", "payment-error-generic-message": "เราไม่สามารถดำเนินการชำระเงินของคุณได้", "verification-success-message": "การยืนยันเสร็จสมบูรณ์แล้ว", "verification-cancelled-message": "การยืนยันถูกยกเลิกแล้ว", diff --git a/src/dynamic-checkout/locales/tr.ts b/src/dynamic-checkout/locales/tr.ts index b5c9c52b..44e35502 100644 --- a/src/dynamic-checkout/locales/tr.ts +++ b/src/dynamic-checkout/locales/tr.ts @@ -23,6 +23,9 @@ module ProcessOut { "payment-success-message": "Bu ödeme tamamlandı.", "payment-info-message": "Ödemeniz işleniyor. Bu pencereyi şimdi kapatabilirsiniz.", "payment-pending-message": "Ödemeniz beklemede.", + "payment-awaiting-confirmation-message": + "Ödemeyi diğer sekmede tamamlayın. Bu sayfa otomatik olarak güncellenecektir.", + "payment-awaiting-confirmation-cancel-button": "İptal", "payment-error-generic-message": "Ödemenizi işleyemedik.", "verification-success-message": "Bu doğrulama tamamlandı.", "verification-cancelled-message": "Doğrulama iptal edildi.", diff --git a/src/dynamic-checkout/locales/uk.ts b/src/dynamic-checkout/locales/uk.ts index 7f08d0d9..8bba851d 100644 --- a/src/dynamic-checkout/locales/uk.ts +++ b/src/dynamic-checkout/locales/uk.ts @@ -23,6 +23,9 @@ module ProcessOut { "payment-success-message": "Платіж завершено.", "payment-info-message": "Ми обробляємо ваш платіж. Ви можете закрити це вікно.", "payment-pending-message": "Ваш платіж очікує на обробку.", + "payment-awaiting-confirmation-message": + "Завершіть оплату в іншій вкладці. Ця сторінка оновиться автоматично.", + "payment-awaiting-confirmation-cancel-button": "Скасувати", "payment-error-generic-message": "Не вдалося обробити ваш платіж.", "verification-success-message": "Перевірку завершено.", "verification-cancelled-message": "Перевірку скасовано.", diff --git a/src/dynamic-checkout/locales/vi.ts b/src/dynamic-checkout/locales/vi.ts index 992f11d4..07d40a8c 100644 --- a/src/dynamic-checkout/locales/vi.ts +++ b/src/dynamic-checkout/locales/vi.ts @@ -24,6 +24,9 @@ module ProcessOut { "payment-info-message": "Chúng tôi đang xử lý thanh toán của bạn. Bạn có thể đóng cửa sổ này ngay bây giờ.", "payment-pending-message": "Thanh toán của bạn đang chờ xử lý.", + "payment-awaiting-confirmation-message": + "Hoàn tất thanh toán ở tab còn lại. Trang này sẽ tự động cập nhật.", + "payment-awaiting-confirmation-cancel-button": "Hủy", "payment-error-generic-message": "Chúng tôi không thể xử lý thanh toán của bạn.", "verification-success-message": "Xác minh này đã hoàn tất.", "verification-cancelled-message": "Xác minh đã bị hủy.", diff --git a/src/dynamic-checkout/locales/zh-cn.ts b/src/dynamic-checkout/locales/zh-cn.ts index 5af5fa7f..8fa74a70 100644 --- a/src/dynamic-checkout/locales/zh-cn.ts +++ b/src/dynamic-checkout/locales/zh-cn.ts @@ -23,6 +23,8 @@ module ProcessOut { "payment-success-message": "付款已完成。", "payment-info-message": "我们正在处理您的付款。您现在可以关闭此窗口。", "payment-pending-message": "您的付款正在等待处理。", + "payment-awaiting-confirmation-message": "请在另一个标签页中完成付款。此页面将自动更新。", + "payment-awaiting-confirmation-cancel-button": "取消", "payment-error-generic-message": "我们无法处理您的付款。", "verification-success-message": "验证已完成。", "verification-cancelled-message": "验证已取消。", diff --git a/src/dynamic-checkout/locales/zh-tw.ts b/src/dynamic-checkout/locales/zh-tw.ts index 9076eda6..c4d2e263 100644 --- a/src/dynamic-checkout/locales/zh-tw.ts +++ b/src/dynamic-checkout/locales/zh-tw.ts @@ -23,6 +23,8 @@ module ProcessOut { "payment-success-message": "付款已完成。", "payment-info-message": "我們正在處理您的付款,您現在可以關閉此視窗。", "payment-pending-message": "您的付款處理中。", + "payment-awaiting-confirmation-message": "請在另一個分頁中完成付款。此頁面將自動更新。", + "payment-awaiting-confirmation-cancel-button": "取消", "payment-error-generic-message": "我們無法處理您的付款。", "verification-success-message": "驗證已完成。", "verification-cancelled-message": "驗證已取消。", diff --git a/src/dynamic-checkout/payment-methods/apm.ts b/src/dynamic-checkout/payment-methods/apm.ts index aeca34b0..ecda63d6 100644 --- a/src/dynamic-checkout/payment-methods/apm.ts +++ b/src/dynamic-checkout/payment-methods/apm.ts @@ -20,6 +20,7 @@ module ProcessOut { private displayOverride: DynamicCheckoutPaymentMethodOverride private theme: DynamicCheckoutThemeType private resetContainerHtml: () => HTMLElement + private openerLossFlow: DynamicCheckoutOpenerLossFlow | null = null constructor( processOutInstance: ProcessOut, @@ -114,10 +115,16 @@ module ProcessOut { return_url: this.paymentConfig.invoiceDetails.return_url || null, }) + this.resetOpenerLossFlow() + const actionStartedAt = Date.now() this.processOutInstance.handleAction( redirectUrl, paymentToken => { + if (this.isOpenerLossResolved()) { + return + } + this.resetContainerHtml().appendChild( new DynamicCheckoutInvoiceLoadingView(this.paymentConfig.locale).element, ) @@ -285,10 +292,16 @@ module ProcessOut { return } + this.resetOpenerLossFlow() + const actionStartedAt = Date.now() this.processOutInstance.handleAction( data.customer_action.value, paymentToken => { + if (this.isOpenerLossResolved()) { + return + } + this.resetContainerHtml().appendChild( new DynamicCheckoutInvoiceLoadingView(this.paymentConfig.locale).element, ) @@ -478,12 +491,29 @@ module ProcessOut { return false } - this.resetContainerHtml().appendChild( - new DynamicCheckoutPaymentPendingView(this.processOutInstance, this.paymentConfig).element, - ) + this.openerLossFlow = new DynamicCheckoutOpenerLossFlow({ + processOutInstance: this.processOutInstance, + paymentConfig: this.paymentConfig, + resetContainerHtml: this.resetContainerHtml, + gatewayName: apm.gateway_name, + paymentMethodDisplayName: this.paymentMethodDisplayName, + }) + this.openerLossFlow.start() return true } + private resetOpenerLossFlow() { + if (this.openerLossFlow) { + this.openerLossFlow.takeOver() + this.openerLossFlow = null + } + } + + // A late postMessage token after a lost opener: the first outcome wins. + private isOpenerLossResolved(): boolean { + return !!this.openerLossFlow && this.openerLossFlow.takeOver() + } + private getChildrenElement() { const saveForFutureAttributes: Record = { type: "checkbox", diff --git a/src/dynamic-checkout/payment-methods/saved-apm.ts b/src/dynamic-checkout/payment-methods/saved-apm.ts index 526881b2..26881ca8 100644 --- a/src/dynamic-checkout/payment-methods/saved-apm.ts +++ b/src/dynamic-checkout/payment-methods/saved-apm.ts @@ -8,6 +8,7 @@ module ProcessOut { private paymentMethodDisplayName: string private displayOverride: DynamicCheckoutPaymentMethodOverride private resetContainerHtml: () => HTMLElement + private openerLossFlow: DynamicCheckoutOpenerLossFlow | null = null constructor( processOutInstance: ProcessOut, @@ -87,10 +88,16 @@ module ProcessOut { customer_token_id: apm_customer_token.customer_token_id, }) + this.resetOpenerLossFlow() + const actionStartedAt = Date.now() return this.processOutInstance.handleAction( redirectUrl, paymentToken => { + if (this.isOpenerLossResolved()) { + return + } + this.processOutInstance.makeCardPayment( invoiceId, paymentToken, @@ -251,12 +258,30 @@ module ProcessOut { return false } - this.resetContainerHtml().appendChild( - new DynamicCheckoutPaymentPendingView(this.processOutInstance, this.paymentConfig).element, - ) + this.openerLossFlow = new DynamicCheckoutOpenerLossFlow({ + processOutInstance: this.processOutInstance, + paymentConfig: this.paymentConfig, + resetContainerHtml: this.resetContainerHtml, + gatewayName: apm_customer_token.gateway_name, + paymentMethodDisplayName: this.paymentMethodDisplayName, + customerTokenId: apm_customer_token.customer_token_id, + }) + this.openerLossFlow.start() return true } + private resetOpenerLossFlow() { + if (this.openerLossFlow) { + this.openerLossFlow.takeOver() + this.openerLossFlow = null + } + } + + // A late postMessage token after a lost opener: the first outcome wins. + private isOpenerLossResolved(): boolean { + return !!this.openerLossFlow && this.openerLossFlow.takeOver() + } + private handlePaymentSuccess(invoiceId: string, data) { this.resetContainerHtml().appendChild( new DynamicCheckoutPaymentSuccessView(this.processOutInstance, this.paymentConfig).element, diff --git a/src/dynamic-checkout/references.ts b/src/dynamic-checkout/references.ts index 72faca29..3c53f537 100644 --- a/src/dynamic-checkout/references.ts +++ b/src/dynamic-checkout/references.ts @@ -7,6 +7,7 @@ /// /// /// +/// /// /// /// @@ -61,6 +62,8 @@ /// /// /// +/// +/// /// /// /// diff --git a/src/dynamic-checkout/utils/events.ts b/src/dynamic-checkout/utils/events.ts index 3ba83d1c..4c5906ee 100644 --- a/src/dynamic-checkout/utils/events.ts +++ b/src/dynamic-checkout/utils/events.ts @@ -329,6 +329,8 @@ module ProcessOut { customer_token_id?: string authorized?: boolean captured?: boolean + reason?: string + timeout?: boolean }, isCardVerification?: boolean, ) { diff --git a/src/dynamic-checkout/utils/opener-loss-flow.ts b/src/dynamic-checkout/utils/opener-loss-flow.ts new file mode 100644 index 00000000..a7fb314b --- /dev/null +++ b/src/dynamic-checkout/utils/opener-loss-flow.ts @@ -0,0 +1,154 @@ +module ProcessOut { + export const OPENER_LOSS_PENDING_REASON = "opener_isolated" + + export type DynamicCheckoutOpenerLossFlowOptions = { + processOutInstance: ProcessOut + paymentConfig: DynamicCheckoutPaymentConfig + resetContainerHtml: () => HTMLElement + gatewayName: string + paymentMethodDisplayName: string + customerTokenId?: string + } + + /** + * Waits for the outcome of a payment whose PSP tab lost its link to the checkout. DC shows the + * awaiting-confirmation view and polls the transaction; it emits no event until the outcome is known, + * because the HPP (and likely merchants) treat payment_pending as final. + */ + export class DynamicCheckoutOpenerLossFlow { + private options: DynamicCheckoutOpenerLossFlowOptions + private poller: DynamicCheckoutTransactionPoller | null = null + private view: Element | null = null + + constructor(options: DynamicCheckoutOpenerLossFlowOptions) { + this.options = options + } + + public start() { + const { processOutInstance, paymentConfig } = this.options + + this.view = new DynamicCheckoutPaymentAwaitingConfirmationView( + processOutInstance, + paymentConfig, + () => this.cancel(), + ).element + this.options.resetContainerHtml().appendChild(this.view) + + this.poller = new DynamicCheckoutTransactionPoller({ + processOutInstance, + invoiceId: paymentConfig.invoiceId, + clientSecret: paymentConfig.clientSecret, + onSuccess: transaction => this.showSuccess(transaction), + onFailure: transaction => this.showFailure(transaction), + onTimeout: () => this.showTimeout(), + isMounted: () => !!this.view && document.body.contains(this.view), + }) + this.poller.start() + } + + /** + * Called when the normal flow returns a result after all (e.g. a postMessage that got through). + * Returns true when this flow already reported an outcome, so the caller must ignore its result. + */ + public takeOver(): boolean { + if (!this.poller) { + return false + } + const alreadyResolved = this.poller.isFinished() + this.poller.stop() + return alreadyResolved + } + + private cancel() { + this.poller.stop() + this.options + .resetContainerHtml() + .appendChild( + new DynamicCheckoutPaymentCancelledView( + this.options.processOutInstance, + this.options.paymentConfig, + ).element, + ) + + DynamicCheckoutEventsUtils.dispatchPaymentCancelledEvent({ + ...this.getEventBase(), + tab_closed: true, + }) + } + + private showSuccess(transaction: PolledTransaction) { + const { processOutInstance, paymentConfig } = this.options + + if (paymentConfig.showStatusMessage) { + this.options + .resetContainerHtml() + .appendChild( + new DynamicCheckoutPaymentSuccessView(processOutInstance, paymentConfig).element, + ) + } else if (!paymentConfig.invoiceDetails.return_url) { + this.options + .resetContainerHtml() + .appendChild( + new DynamicCheckoutPaymentInfoView(processOutInstance, paymentConfig).element, + ) + } + + DynamicCheckoutEventsUtils.dispatchPaymentSuccessEvent({ + ...this.getEventBase(), + customer_token_id: this.options.customerTokenId, + ...DynamicCheckoutEventsUtils.getPaymentStatusEventDetail(transaction), + }) + } + + private showFailure(transaction: PolledTransaction) { + const { processOutInstance, paymentConfig } = this.options + + this.options + .resetContainerHtml() + .appendChild(new DynamicCheckoutPaymentErrorView(processOutInstance, paymentConfig).element) + + DynamicCheckoutEventsUtils.dispatchPaymentErrorEvent( + paymentConfig.invoiceId, + { + code: "gateway.declined", + message: "The payment was not completed.", + transaction_status: transaction.status, + }, + this.options.gatewayName, + undefined, + paymentConfig.invoiceDetails.return_url || null, + this.options.customerTokenId, + this.options.paymentMethodDisplayName, + ) + } + + private showTimeout() { + this.options + .resetContainerHtml() + .appendChild( + new DynamicCheckoutPaymentPendingView( + this.options.processOutInstance, + this.options.paymentConfig, + ).element, + ) + + DynamicCheckoutEventsUtils.dispatchPaymentPendingEvent({ + ...this.getEventBase(), + customer_token_id: this.options.customerTokenId, + reason: OPENER_LOSS_PENDING_REASON, + timeout: true, + }) + } + + private getEventBase() { + const { paymentConfig } = this.options + + return { + payment_method_name: this.options.gatewayName, + payment_method_display_name: this.options.paymentMethodDisplayName, + invoice_id: paymentConfig.invoiceId, + return_url: paymentConfig.invoiceDetails.return_url || null, + } + } + } +} diff --git a/src/dynamic-checkout/utils/transaction-poller.ts b/src/dynamic-checkout/utils/transaction-poller.ts new file mode 100644 index 00000000..bff59996 --- /dev/null +++ b/src/dynamic-checkout/utils/transaction-poller.ts @@ -0,0 +1,179 @@ +module ProcessOut { + // Transaction statuses after which the payment can't change any more from the shopper's point of view. + const SUCCESSFUL_TRANSACTION_STATUSES = ["authorized", "pending-capture", "completed"] + const FAILED_TRANSACTION_STATUSES = ["failed", "voided", "blocked"] + + export const TRANSACTION_POLLING_INTERVAL_MS = 3000 + // Same as the APM v2 default timeout. + export const TRANSACTION_POLLING_TIMEOUT_MS = 15 * 60 * 1000 + + export type PolledTransaction = { + status: string + authorized?: boolean + captured?: boolean + } + + export type DynamicCheckoutTransactionPollerOptions = { + processOutInstance: ProcessOut + invoiceId: string + clientSecret?: string + onSuccess: (transaction: PolledTransaction) => void + onFailure: (transaction: PolledTransaction) => void + onTimeout: () => void + // Polling stops silently once this returns false, e.g. when the merchant removes the widget. + isMounted: () => boolean + intervalMs?: number + timeoutMs?: number + now?: () => number + win?: Window + doc?: Document + } + + /** + * Polls our invoice API until the transaction reaches a final status or the timeout. + * It never calls the PSP: the backend keeps the transaction in sync (webhook, token apply, reconcile). + */ + export class DynamicCheckoutTransactionPoller { + private options: DynamicCheckoutTransactionPollerOptions + private startedAt = 0 + private timer: number | null = null + private requestInFlight = false + private finished = false + + constructor(options: DynamicCheckoutTransactionPollerOptions) { + this.options = options + this.onPageActive = this.onPageActive.bind(this) + } + + public start() { + this.startedAt = this.now() + this.getWindow().addEventListener("focus", this.onPageActive) + this.getDocument().addEventListener("visibilitychange", this.onPageActive) + this.check() + } + + // Stops without calling any callback, e.g. when another result (postMessage, Cancel) won. + public stop() { + this.finished = true + this.clearTimer() + this.getWindow().removeEventListener("focus", this.onPageActive) + this.getDocument().removeEventListener("visibilitychange", this.onPageActive) + } + + public isFinished() { + return this.finished + } + + static isSuccessfulStatus(status: string) { + return SUCCESSFUL_TRANSACTION_STATUSES.indexOf(status) !== -1 + } + + static isFailedStatus(status: string) { + return FAILED_TRANSACTION_STATUSES.indexOf(status) !== -1 + } + + private onPageActive() { + if (this.isPageVisible()) { + this.check() + } + } + + private check() { + if (this.finished || this.requestInFlight) { + return + } + if (!this.options.isMounted()) { + this.stop() + return + } + if (this.now() - this.startedAt >= this.getTimeoutMs()) { + this.stop() + this.options.onTimeout() + return + } + if (!this.isPageVisible()) { + this.scheduleNext() + return + } + + this.clearTimer() + this.requestInFlight = true + this.options.processOutInstance.apiRequest( + "GET", + `invoices/${this.options.invoiceId}?expand=transaction`, + {}, + data => { + this.requestInFlight = false + this.handleTransaction(data && data.invoice ? data.invoice.transaction : null) + }, + () => { + this.requestInFlight = false + this.scheduleNext() + }, + 0, + { + isLegacy: false, + clientSecret: this.options.clientSecret, + }, + ) + } + + private handleTransaction(transaction: PolledTransaction | null) { + if (this.finished) { + return + } + + const status = transaction ? transaction.status : "" + if (DynamicCheckoutTransactionPoller.isSuccessfulStatus(status)) { + this.stop() + this.options.onSuccess(transaction) + return + } + if (DynamicCheckoutTransactionPoller.isFailedStatus(status)) { + this.stop() + this.options.onFailure(transaction) + return + } + + this.scheduleNext() + } + + private scheduleNext() { + if (this.finished) { + return + } + this.clearTimer() + this.timer = this.getWindow().setTimeout(() => { + this.timer = null + this.check() + }, this.options.intervalMs || TRANSACTION_POLLING_INTERVAL_MS) + } + + private clearTimer() { + if (this.timer !== null) { + this.getWindow().clearTimeout(this.timer) + this.timer = null + } + } + + private isPageVisible() { + return this.getDocument().visibilityState === "visible" + } + + private getTimeoutMs() { + return this.options.timeoutMs || TRANSACTION_POLLING_TIMEOUT_MS + } + + private now() { + return this.options.now ? this.options.now() : Date.now() + } + + private getWindow(): Window { + return this.options.win || window + } + + private getDocument(): Document { + return this.options.doc || document + } + } +} diff --git a/src/dynamic-checkout/views/payment-awaiting-confirmation.ts b/src/dynamic-checkout/views/payment-awaiting-confirmation.ts new file mode 100644 index 00000000..c45abd87 --- /dev/null +++ b/src/dynamic-checkout/views/payment-awaiting-confirmation.ts @@ -0,0 +1,60 @@ +/// + +module ProcessOut { + /** + * Shown while DC waits for a payment whose PSP tab lost its link to the checkout (e.g. after a COOP page). + * The shopper finishes the payment in the other tab; Cancel gives up waiting. + */ + export class DynamicCheckoutPaymentAwaitingConfirmationView { + public element: Element + + constructor( + processOutInstance: ProcessOut, + paymentConfig: DynamicCheckoutPaymentConfig, + onCancel: () => void, + ) { + const [element, image, message, cancelButton] = HTMLElements.createMultipleElements([ + { + tagName: "div", + classNames: ["dco-card-payment-success"], + attributes: { + role: "status", + }, + }, + { + tagName: "img", + classNames: ["dco-card-payment-success-image"], + attributes: { + src: processOutInstance.endpoint("js", PAYMENT_PENDING_IMAGE_ASSET), + alt: "", + }, + }, + { + tagName: "p", + classNames: ["dco-card-payment-success-text"], + textContent: Translations.getText( + "payment-awaiting-confirmation-message", + paymentConfig.locale, + ), + }, + { + tagName: "button", + classNames: ["dco-payment-method-button-pay-button"], + attributes: { + type: "button", + }, + textContent: Translations.getText( + "payment-awaiting-confirmation-cancel-button", + paymentConfig.locale, + ), + }, + ]) + + cancelButton.addEventListener("click", onCancel) + + HTMLElements.appendChildren(element, [image, message, cancelButton]) + + this.element = element + } + } +} diff --git a/test/dynamic-checkout/opener-loss-flow.test.ts b/test/dynamic-checkout/opener-loss-flow.test.ts new file mode 100644 index 00000000..a1273884 --- /dev/null +++ b/test/dynamic-checkout/opener-loss-flow.test.ts @@ -0,0 +1,179 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" +import { CapturedEvent, loadOpenerLossFlow } from "../support/loadNamespace" + +const INTERVAL_MS = 3000 +const TIMEOUT_MS = 15 * 60 * 1000 +const PAYMENT_SUCCESS = "processout_dynamic_checkout_payment_success" +const PAYMENT_ERROR = "processout_dynamic_checkout_payment_error" +const PAYMENT_PENDING = "processout_dynamic_checkout_payment_pending" +const PAYMENT_CANCELLED = "processout_dynamic_checkout_payment_cancelled" + +let ProcessOut: Record +let dispatchedEvents: CapturedEvent[] + +beforeEach(() => { + vi.useFakeTimers() + vi.stubGlobal("document", { + visibilityState: "visible", + addEventListener: () => {}, + removeEventListener: () => {}, + body: { contains: () => true }, + }) + const loaded = loadOpenerLossFlow() + ProcessOut = loaded.namespace + dispatchedEvents = loaded.dispatchedEvents +}) + +afterEach(() => { + vi.useRealTimers() + vi.unstubAllGlobals() +}) + +function createFlow(statuses: string[], options: { showStatusMessage?: boolean } = {}) { + const shownViews: any[] = [] + const container = { appendChild: (element: any) => shownViews.push(element) } + let call = 0 + const apiRequest = vi.fn((_method, _path, _data, success) => { + const status = statuses[Math.min(call, statuses.length - 1)] + call++ + success({ invoice: { transaction: { status, authorized: true, captured: true } } }) + }) + const paymentConfig = { + invoiceId: "iv_test", + clientSecret: "secret", + showStatusMessage: options.showStatusMessage ?? true, + invoiceDetails: { return_url: "https://merchant.test/return" }, + } + const flow = new ProcessOut.DynamicCheckoutOpenerLossFlow({ + processOutInstance: { apiRequest }, + paymentConfig, + resetContainerHtml: () => container, + gatewayName: "mercadopagomxcashinaccount", + paymentMethodDisplayName: "Mercado Pago", + }) + + return { flow, apiRequest, shownViews: () => shownViews.map(element => element.view) } +} + +const eventBase = { + payment_method_name: "mercadopagomxcashinaccount", + payment_method_display_name: "Mercado Pago", + invoice_id: "iv_test", + return_url: "https://merchant.test/return", +} + +describe("DynamicCheckoutOpenerLossFlow", () => { + it("shows the awaiting view and emits no event while the transaction is waiting", () => { + const { flow, shownViews } = createFlow(["waiting"]) + + flow.start() + vi.advanceTimersByTime(INTERVAL_MS * 10) + + expect(shownViews()).toEqual(["DynamicCheckoutPaymentAwaitingConfirmationView"]) + expect(dispatchedEvents).toEqual([]) + }) + + it("emits payment_success with the transaction status once the payment completes", () => { + const { flow, shownViews } = createFlow(["waiting", "completed"]) + + flow.start() + vi.advanceTimersByTime(INTERVAL_MS) + + expect(shownViews()).toEqual([ + "DynamicCheckoutPaymentAwaitingConfirmationView", + "DynamicCheckoutPaymentSuccessView", + ]) + expect(dispatchedEvents).toEqual([ + { type: PAYMENT_SUCCESS, detail: { ...eventBase, authorized: true, captured: true } }, + ]) + }) + + it("leaves the view to the merchant redirect when status messages are off", () => { + const { flow, shownViews } = createFlow(["completed"], { showStatusMessage: false }) + + flow.start() + + expect(shownViews()).toEqual(["DynamicCheckoutPaymentAwaitingConfirmationView"]) + expect(dispatchedEvents.map(event => event.type)).toEqual([PAYMENT_SUCCESS]) + }) + + it("emits payment_error for a failed transaction", () => { + const { flow, shownViews } = createFlow(["failed"]) + + flow.start() + + expect(shownViews()).toEqual([ + "DynamicCheckoutPaymentAwaitingConfirmationView", + "DynamicCheckoutPaymentErrorView", + ]) + expect(dispatchedEvents).toEqual([ + { + type: PAYMENT_ERROR, + detail: { + ...eventBase, + error_type: "gateway.declined", + error_message: "The payment was not completed.", + transaction_status: "failed", + }, + }, + ]) + }) + + it("emits payment_pending with reason and timeout only after 15 min", () => { + const { flow, shownViews } = createFlow(["waiting"]) + + flow.start() + vi.advanceTimersByTime(TIMEOUT_MS - INTERVAL_MS) + expect(dispatchedEvents).toEqual([]) + + vi.advanceTimersByTime(INTERVAL_MS * 2) + + expect(shownViews()).toEqual([ + "DynamicCheckoutPaymentAwaitingConfirmationView", + "DynamicCheckoutPaymentPendingView", + ]) + expect(dispatchedEvents).toEqual([ + { + type: PAYMENT_PENDING, + detail: { ...eventBase, reason: "opener_isolated", timeout: true }, + }, + ]) + }) + + it("Cancel stops polling and emits payment_cancelled with tab_closed", () => { + const { flow, apiRequest, shownViews } = createFlow(["waiting"]) + + flow.start() + const awaitingView = flow["view"] + const onCancel = awaitingView.args[2] + onCancel() + vi.advanceTimersByTime(INTERVAL_MS * 5) + + expect(apiRequest).toHaveBeenCalledOnce() + expect(shownViews()).toEqual([ + "DynamicCheckoutPaymentAwaitingConfirmationView", + "DynamicCheckoutPaymentCancelledView", + ]) + expect(dispatchedEvents).toEqual([ + { type: PAYMENT_CANCELLED, detail: { ...eventBase, tab_closed: true } }, + ]) + }) + + it("takeOver() stops polling and tells whether an outcome was already reported", () => { + const pending = createFlow(["waiting"]) + pending.flow.start() + expect(pending.flow.takeOver()).toBe(false) + vi.advanceTimersByTime(INTERVAL_MS * 5) + expect(pending.apiRequest).toHaveBeenCalledOnce() + + const resolved = createFlow(["completed"]) + resolved.flow.start() + expect(resolved.flow.takeOver()).toBe(true) + }) + + it("takeOver() before start() reports nothing to ignore", () => { + const { flow } = createFlow(["waiting"]) + + expect(flow.takeOver()).toBe(false) + }) +}) diff --git a/test/dynamic-checkout/transaction-poller.test.ts b/test/dynamic-checkout/transaction-poller.test.ts new file mode 100644 index 00000000..6aa8f1e8 --- /dev/null +++ b/test/dynamic-checkout/transaction-poller.test.ts @@ -0,0 +1,227 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" +import { LOCALES, loadDynamicCheckout, loadTransactionPoller } from "../support/loadNamespace" + +const INTERVAL_MS = 3000 +const TIMEOUT_MS = 15 * 60 * 1000 + +let Poller: any + +beforeEach(() => { + vi.useFakeTimers() + Poller = loadTransactionPoller().DynamicCheckoutTransactionPoller +}) + +afterEach(() => { + vi.useRealTimers() +}) + +type FakeResponse = { status?: string; error?: boolean } + +function createHarness(responses: FakeResponse[], visibilityState = "visible") { + const listeners: Record void>> = {} + const addListener = (type: string, listener: () => void) => { + listeners[type] = [...(listeners[type] || []), listener] + } + const removeListener = (type: string, listener: () => void) => { + listeners[type] = (listeners[type] || []).filter(l => l !== listener) + } + const doc = { + visibilityState, + addEventListener: vi.fn(addListener), + removeEventListener: vi.fn(removeListener), + } + const win = { + addEventListener: vi.fn(addListener), + removeEventListener: vi.fn(removeListener), + setTimeout: (fn: () => void, ms: number) => setTimeout(fn, ms), + clearTimeout: (id: any) => clearTimeout(id), + } + let call = 0 + const apiRequest = vi.fn((_method, _path, _data, success, error) => { + const response = responses[Math.min(call, responses.length - 1)] + call++ + if (response.error) { + error() + } else { + success({ invoice: { transaction: { status: response.status, captured: true } } }) + } + }) + const callbacks = { onSuccess: vi.fn(), onFailure: vi.fn(), onTimeout: vi.fn() } + let mounted = true + const startedAt = Date.now() + + const poller = new Poller({ + processOutInstance: { apiRequest }, + invoiceId: "iv_test", + clientSecret: "secret", + ...callbacks, + isMounted: () => mounted, + now: () => Date.now(), + win, + doc, + }) + + return { + poller, + apiRequest, + callbacks, + doc, + fire: (type: string) => (listeners[type] || []).forEach(listener => listener()), + listenerCount: () => Object.values(listeners).reduce((n, l) => n + l.length, 0), + unmount: () => { + mounted = false + }, + startedAt, + } +} + +describe("DynamicCheckoutTransactionPoller", () => { + it("checks right away with the client secret", () => { + const h = createHarness([{ status: "waiting" }]) + + h.poller.start() + + expect(h.apiRequest).toHaveBeenCalledOnce() + expect(h.apiRequest.mock.calls[0][0]).toBe("GET") + expect(h.apiRequest.mock.calls[0][1]).toBe("invoices/iv_test?expand=transaction") + expect(h.apiRequest.mock.calls[0][6]).toEqual({ isLegacy: false, clientSecret: "secret" }) + }) + + it("polls every 3 s until a successful status, then reports it once and stops", () => { + const h = createHarness([{ status: "waiting" }, { status: "pending" }, { status: "completed" }]) + + h.poller.start() + vi.advanceTimersByTime(INTERVAL_MS * 5) + + expect(h.apiRequest).toHaveBeenCalledTimes(3) + expect(h.callbacks.onSuccess).toHaveBeenCalledExactlyOnceWith({ + status: "completed", + captured: true, + }) + expect(h.callbacks.onFailure).not.toHaveBeenCalled() + expect(h.poller.isFinished()).toBe(true) + expect(h.listenerCount()).toBe(0) + }) + + it.each(["authorized", "pending-capture", "completed"])("treats %s as success", status => { + const h = createHarness([{ status }]) + + h.poller.start() + + expect(h.callbacks.onSuccess).toHaveBeenCalledOnce() + }) + + it.each(["failed", "voided", "blocked"])("treats %s as failure", status => { + const h = createHarness([{ status }]) + + h.poller.start() + + expect(h.callbacks.onFailure).toHaveBeenCalledOnce() + expect(h.callbacks.onSuccess).not.toHaveBeenCalled() + }) + + it("keeps polling after a request error", () => { + const h = createHarness([{ error: true }, { status: "completed" }]) + + h.poller.start() + vi.advanceTimersByTime(INTERVAL_MS) + + expect(h.apiRequest).toHaveBeenCalledTimes(2) + expect(h.callbacks.onSuccess).toHaveBeenCalledOnce() + }) + + it("doesn't request while the page is hidden, and checks right away when it becomes visible", () => { + const h = createHarness([{ status: "waiting" }], "hidden") + + h.poller.start() + vi.advanceTimersByTime(INTERVAL_MS * 3) + expect(h.apiRequest).not.toHaveBeenCalled() + + h.doc.visibilityState = "visible" + h.fire("visibilitychange") + + expect(h.apiRequest).toHaveBeenCalledOnce() + }) + + it("checks on focus without waiting for the next tick", () => { + const h = createHarness([{ status: "waiting" }]) + + h.poller.start() + h.fire("focus") + + expect(h.apiRequest).toHaveBeenCalledTimes(2) + }) + + it("times out after 15 min with a single timeout callback", () => { + const h = createHarness([{ status: "waiting" }]) + + h.poller.start() + vi.advanceTimersByTime(TIMEOUT_MS + INTERVAL_MS) + + expect(h.callbacks.onTimeout).toHaveBeenCalledOnce() + expect(h.callbacks.onSuccess).not.toHaveBeenCalled() + expect(h.apiRequest).toHaveBeenCalledTimes(TIMEOUT_MS / INTERVAL_MS) + expect(h.listenerCount()).toBe(0) + }) + + it("times out even while the page stays hidden", () => { + const h = createHarness([{ status: "waiting" }], "hidden") + + h.poller.start() + vi.advanceTimersByTime(TIMEOUT_MS + INTERVAL_MS) + + expect(h.callbacks.onTimeout).toHaveBeenCalledOnce() + expect(h.apiRequest).not.toHaveBeenCalled() + }) + + it("stops silently when the widget is unmounted", () => { + const h = createHarness([{ status: "waiting" }]) + + h.poller.start() + h.unmount() + vi.advanceTimersByTime(INTERVAL_MS * 3) + + expect(h.apiRequest).toHaveBeenCalledOnce() + expect(h.poller.isFinished()).toBe(true) + expect(h.callbacks.onTimeout).not.toHaveBeenCalled() + expect(h.listenerCount()).toBe(0) + }) + + it("stop() ends polling without any callback", () => { + const h = createHarness([{ status: "waiting" }]) + + h.poller.start() + h.poller.stop() + vi.advanceTimersByTime(INTERVAL_MS * 3) + h.fire("focus") + + expect(h.apiRequest).toHaveBeenCalledOnce() + expect(h.callbacks.onSuccess).not.toHaveBeenCalled() + expect(h.callbacks.onFailure).not.toHaveBeenCalled() + expect(h.callbacks.onTimeout).not.toHaveBeenCalled() + }) + + it("ignores a response that arrives after stop()", () => { + let pendingSuccess: ((data: any) => void) | null = null + const h = createHarness([{ status: "waiting" }]) + h.apiRequest.mockImplementationOnce((_m, _p, _d, success) => { + pendingSuccess = success + }) + + h.poller.start() + h.poller.stop() + pendingSuccess!({ invoice: { transaction: { status: "completed" } } }) + + expect(h.callbacks.onSuccess).not.toHaveBeenCalled() + }) +}) + +describe("payment-awaiting-confirmation translations", () => { + it.each(LOCALES.map(locale => locale.file))("%s has both keys", file => { + const { namespace } = loadDynamicCheckout() + const translations = namespace[LOCALES.find(locale => locale.file === file)!.name] + + expect(translations["payment-awaiting-confirmation-message"]).toBeTruthy() + expect(translations["payment-awaiting-confirmation-cancel-button"]).toBeTruthy() + }) +}) diff --git a/test/support/loadNamespace.ts b/test/support/loadNamespace.ts index f209a459..c81238ad 100644 --- a/test/support/loadNamespace.ts +++ b/test/support/loadNamespace.ts @@ -112,7 +112,7 @@ export interface DynamicCheckoutNamespace { * the namespace members under those names, in the same order the real * `tsc --outFile` bundle concatenates them. */ -export function loadDynamicCheckout(): DynamicCheckoutNamespace { +export function loadDynamicCheckout(extraChunks: string[] = []): DynamicCheckoutNamespace { const chunks = [ ...LOCALES.map(locale => compile(`src/dynamic-checkout/locales/${locale.file}.ts`)), `const { ${LOCALES.map(locale => locale.name).join(", ")} } = ProcessOut;`, @@ -127,6 +127,7 @@ export function loadDynamicCheckout(): DynamicCheckoutNamespace { `function PaymentToken(type, token) { this.type = type; this.token = token; }`, compile("src/dynamic-checkout/clients/google-pay.ts"), compile("src/dynamic-checkout/clients/apple-pay.ts"), + ...extraChunks, ] const dispatchedEvents: CapturedEvent[] = [] @@ -142,6 +143,10 @@ export function loadDynamicCheckout(): DynamicCheckoutNamespace { dispatchedEvents.push(event) return true }, + addEventListener: () => {}, + removeEventListener: () => {}, + setTimeout: (fn: () => void, ms: number) => setTimeout(fn, ms), + clearTimeout: (id: ReturnType) => clearTimeout(id), } const moduleShim = { exports: {} as Record } @@ -291,3 +296,34 @@ export function loadOpenerLoss( run(moduleShim, moduleShim.exports, windowShim, navigatorShim, undefined) return moduleShim.exports } + +/** + * Load `src/dynamic-checkout/utils/transaction-poller.ts` and return its `ProcessOut` namespace. + */ +export function loadTransactionPoller(): Record { + const js = compile("src/dynamic-checkout/utils/transaction-poller.ts") + const moduleShim = { exports: {} as Record } + const run = new Function("module", "exports", `${js}\nmodule.exports = ProcessOut;`) + run(moduleShim, moduleShim.exports) + return moduleShim.exports +} + +/** + * Load the opener-loss flow on top of the Dynamic Checkout events. Views are stubbed with classes + * that record their name, so tests can assert which view is shown without a DOM. + */ +export function loadOpenerLossFlow(): DynamicCheckoutNamespace { + const viewStub = (name: string) => + `var ${name} = function () { this.element = { view: "${name}", args: Array.prototype.slice.call(arguments) } };` + return loadDynamicCheckout([ + viewStub("DynamicCheckoutPaymentAwaitingConfirmationView"), + viewStub("DynamicCheckoutPaymentCancelledView"), + viewStub("DynamicCheckoutPaymentSuccessView"), + viewStub("DynamicCheckoutPaymentInfoView"), + viewStub("DynamicCheckoutPaymentErrorView"), + viewStub("DynamicCheckoutPaymentPendingView"), + compile("src/dynamic-checkout/utils/transaction-poller.ts"), + `const { DynamicCheckoutTransactionPoller } = ProcessOut;`, + compile("src/dynamic-checkout/utils/opener-loss-flow.ts"), + ]) +} From ba148772c646b3cf2bdf24ba8f968fb838b54a47 Mon Sep 17 00:00:00 2001 From: Jakub Binczyk Date: Thu, 19 Nov 2026 11:29:48 +0100 Subject: [PATCH 2/5] chore: bump version to 1.9.23 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 5b4c0e15..29e9f374 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "processout.js", - "version": "1.9.22", + "version": "1.9.23", "description": "ProcessOut.js is a JavaScript library for ProcessOut's payment processing API.", "scripts": { "build:processout": "tsc -p src/processout && uglifyjs --compress --keep-fnames --ie8 dist/processout.js -o dist/processout.js", From 92838dea9d9a0f6b353a89dd444e1daec8ed7ecb Mon Sep 17 00:00:00 2001 From: Jakub Binczyk Date: Tue, 24 Nov 2026 10:16:16 +0100 Subject: [PATCH 3/5] feat(POINT-3697)(dc): check the transaction before showing cancelled after a real tab close In on mode, a real close (DC page focused) now checks the transaction once. A shopper whose PSP tab lost only its own opener sees the close-this-tab landing, closes it, and DC used to show payment cancelled although the payment was captured. Success shows the success view and event; any other status or a request error keeps payment cancelled. off and shadow are unchanged. --- src/dynamic-checkout/payment-methods/apm.ts | 13 ++- .../payment-methods/saved-apm.ts | 13 ++- .../utils/opener-loss-flow.ts | 54 ++++++++- src/dynamic-checkout/utils/opener-loss.ts | 38 +++++- .../dynamic-checkout/opener-loss-flow.test.ts | 108 +++++++++++++++++- test/dynamic-checkout/opener-loss.test.ts | 34 ++++++ test/support/loadNamespace.ts | 1 + 7 files changed, 245 insertions(+), 16 deletions(-) diff --git a/src/dynamic-checkout/payment-methods/apm.ts b/src/dynamic-checkout/payment-methods/apm.ts index 81e7e347..7d6cb78c 100644 --- a/src/dynamic-checkout/payment-methods/apm.ts +++ b/src/dynamic-checkout/payment-methods/apm.ts @@ -474,11 +474,12 @@ module ProcessOut { /** * Must run first in the handleAction error callback: PO.js refocuses the window right after it. - * Returns true when the tab_closed was a lost opener and DC shows pending instead of cancelled. + * Returns true when the opener-loss flow took over: pending for a lost opener, or a status check before + * "payment cancelled" for a real close (`on` mode only). */ private handleOpenerLoss(error: Exception, actionStartedAt: number): boolean { const { apm } = this.paymentMethod - const isOpenerLoss = DynamicCheckoutOpenerLossUtils.isOpenerLoss( + const handling = DynamicCheckoutOpenerLossUtils.getTabClosedHandling( this.processOutInstance, error, { @@ -488,7 +489,7 @@ module ProcessOut { actionStartedAt, }, ) - if (!isOpenerLoss) { + if (handling === "cancel") { return false } @@ -499,7 +500,11 @@ module ProcessOut { gatewayName: apm.gateway_name, paymentMethodDisplayName: this.paymentMethodDisplayName, }) - this.openerLossFlow.start() + if (handling === "opener_loss") { + this.openerLossFlow.start() + } else { + this.openerLossFlow.confirmClose() + } return true } diff --git a/src/dynamic-checkout/payment-methods/saved-apm.ts b/src/dynamic-checkout/payment-methods/saved-apm.ts index 9b1eb131..fbbe62ca 100644 --- a/src/dynamic-checkout/payment-methods/saved-apm.ts +++ b/src/dynamic-checkout/payment-methods/saved-apm.ts @@ -242,11 +242,12 @@ module ProcessOut { /** * Must run first in the handleAction error callback: PO.js refocuses the window right after it. - * Returns true when the tab_closed was a lost opener and DC shows pending instead of cancelled. + * Returns true when the opener-loss flow took over: pending for a lost opener, or a status check before + * "payment cancelled" for a real close (`on` mode only). */ private handleOpenerLoss(error: Exception, actionStartedAt: number): boolean { const { apm_customer_token } = this.paymentMethod - const isOpenerLoss = DynamicCheckoutOpenerLossUtils.isOpenerLoss( + const handling = DynamicCheckoutOpenerLossUtils.getTabClosedHandling( this.processOutInstance, error, { @@ -256,7 +257,7 @@ module ProcessOut { actionStartedAt, }, ) - if (!isOpenerLoss) { + if (handling === "cancel") { return false } @@ -268,7 +269,11 @@ module ProcessOut { paymentMethodDisplayName: this.paymentMethodDisplayName, customerTokenId: apm_customer_token.customer_token_id, }) - this.openerLossFlow.start() + if (handling === "opener_loss") { + this.openerLossFlow.start() + } else { + this.openerLossFlow.confirmClose() + } return true } diff --git a/src/dynamic-checkout/utils/opener-loss-flow.ts b/src/dynamic-checkout/utils/opener-loss-flow.ts index a7fb314b..3b906e02 100644 --- a/src/dynamic-checkout/utils/opener-loss-flow.ts +++ b/src/dynamic-checkout/utils/opener-loss-flow.ts @@ -19,6 +19,8 @@ module ProcessOut { private options: DynamicCheckoutOpenerLossFlowOptions private poller: DynamicCheckoutTransactionPoller | null = null private view: Element | null = null + private closeCheckPending = false + private closeCheckReported = false constructor(options: DynamicCheckoutOpenerLossFlowOptions) { this.options = options @@ -46,21 +48,71 @@ module ProcessOut { this.poller.start() } + /** + * After a real tab close: checks the transaction once instead of reporting "payment cancelled" right away. + * Success → the same views and event as polling; anything else, or a request error → "payment cancelled". + */ + public confirmClose() { + const { processOutInstance, paymentConfig } = this.options + + this.view = new DynamicCheckoutInvoiceLoadingView(paymentConfig.locale).element + this.options.resetContainerHtml().appendChild(this.view) + this.closeCheckPending = true + + processOutInstance.apiRequest( + "GET", + `invoices/${paymentConfig.invoiceId}?expand=transaction`, + {}, + data => this.finishCloseCheck(data && data.invoice ? data.invoice.transaction : null), + () => this.finishCloseCheck(null), + 0, + { + isLegacy: false, + clientSecret: paymentConfig.clientSecret, + }, + ) + } + /** * Called when the normal flow returns a result after all (e.g. a postMessage that got through). * Returns true when this flow already reported an outcome, so the caller must ignore its result. */ public takeOver(): boolean { - if (!this.poller) { + if (this.closeCheckPending) { + this.closeCheckPending = false return false } + if (!this.poller) { + return this.closeCheckReported + } const alreadyResolved = this.poller.isFinished() this.poller.stop() return alreadyResolved } + private finishCloseCheck(transaction: PolledTransaction | null) { + if (!this.closeCheckPending) { + return + } + this.closeCheckPending = false + if (!this.view || !document.body.contains(this.view)) { + return + } + + this.closeCheckReported = true + if (transaction && DynamicCheckoutTransactionPoller.isSuccessfulStatus(transaction.status)) { + this.showSuccess(transaction) + } else { + this.showCancelled() + } + } + private cancel() { this.poller.stop() + this.showCancelled() + } + + private showCancelled() { this.options .resetContainerHtml() .appendChild( diff --git a/src/dynamic-checkout/utils/opener-loss.ts b/src/dynamic-checkout/utils/opener-loss.ts index 53f816a5..9ee24834 100644 --- a/src/dynamic-checkout/utils/opener-loss.ts +++ b/src/dynamic-checkout/utils/opener-loss.ts @@ -7,6 +7,14 @@ module ProcessOut { export type OpenerLossVerdict = "real_close" | "severed_link" + /** + * What DC does after a `tab_closed`: + * - `cancel`: today's "payment cancelled". + * - `opener_loss`: wait for the outcome (awaiting view and polling). + * - `confirm_close`: check the transaction once, then show success or "payment cancelled". + */ + export type TabClosedHandling = "cancel" | "opener_loss" | "confirm_close" + export type OpenerLossPageState = { hasFocus: boolean visibilityState: string @@ -65,17 +73,38 @@ module ProcessOut { context: OpenerLossContext, doc: Document = document, ): boolean { + return ( + DynamicCheckoutOpenerLossUtils.getTabClosedHandling( + processOutInstance, + error, + context, + doc, + ) === "opener_loss" + ) + } + + /** + * Same check as `isOpenerLoss`, with the outcome for a real close in `on` mode: `confirm_close`. + * A shopper whose PSP tab lost only its own opener sees the "you can close this tab" landing, closes it, + * and DC sees a real close although the payment may be done; one status check avoids a false "cancelled". + */ + static getTabClosedHandling( + processOutInstance: ProcessOut, + error: Exception, + context: OpenerLossContext, + doc: Document = document, + ): TabClosedHandling { if ( error.code !== "customer.canceled" || !error.metadata || error.metadata.reason !== "tab_closed" ) { - return false + return "cancel" } const mode = DynamicCheckoutOpenerLossUtils.getMode(context.mode) if (mode === "off") { - return false + return "cancel" } const state = DynamicCheckoutOpenerLossUtils.readPageState(doc) @@ -83,7 +112,10 @@ module ProcessOut { DynamicCheckoutOpenerLossUtils.report(processOutInstance, context, mode, verdict, state) - return mode === "on" && verdict === "severed_link" + if (mode !== "on") { + return "cancel" + } + return verdict === "severed_link" ? "opener_loss" : "confirm_close" } private static report( diff --git a/test/dynamic-checkout/opener-loss-flow.test.ts b/test/dynamic-checkout/opener-loss-flow.test.ts index a1273884..ab766ad3 100644 --- a/test/dynamic-checkout/opener-loss-flow.test.ts +++ b/test/dynamic-checkout/opener-loss-flow.test.ts @@ -29,14 +29,26 @@ afterEach(() => { vi.unstubAllGlobals() }) -function createFlow(statuses: string[], options: { showStatusMessage?: boolean } = {}) { +function createFlow( + statuses: string[], + options: { showStatusMessage?: boolean; respond?: boolean; requestFails?: boolean } = {}, +) { const shownViews: any[] = [] const container = { appendChild: (element: any) => shownViews.push(element) } let call = 0 - const apiRequest = vi.fn((_method, _path, _data, success) => { + const pendingResponses: Array<() => void> = [] + const apiRequest = vi.fn((_method, _path, _data, success, failure) => { const status = statuses[Math.min(call, statuses.length - 1)] call++ - success({ invoice: { transaction: { status, authorized: true, captured: true } } }) + const respond = () => + options.requestFails + ? failure() + : success({ invoice: { transaction: { status, authorized: true, captured: true } } }) + if (options.respond === false) { + pendingResponses.push(respond) + } else { + respond() + } }) const paymentConfig = { invoiceId: "iv_test", @@ -52,7 +64,12 @@ function createFlow(statuses: string[], options: { showStatusMessage?: boolean } paymentMethodDisplayName: "Mercado Pago", }) - return { flow, apiRequest, shownViews: () => shownViews.map(element => element.view) } + return { + flow, + apiRequest, + shownViews: () => shownViews.map(element => element.view), + respondNow: () => pendingResponses.splice(0).forEach(respond => respond()), + } } const eventBase = { @@ -171,6 +188,89 @@ describe("DynamicCheckoutOpenerLossFlow", () => { expect(resolved.flow.takeOver()).toBe(true) }) + describe("confirmClose()", () => { + it("checks the transaction once and emits payment_success when the payment went through", () => { + const { flow, apiRequest, shownViews } = createFlow(["completed"]) + + flow.confirmClose() + vi.advanceTimersByTime(INTERVAL_MS * 5) + + expect(apiRequest).toHaveBeenCalledOnce() + expect(apiRequest.mock.calls[0][1]).toBe("invoices/iv_test?expand=transaction") + expect(shownViews()).toEqual([ + "DynamicCheckoutInvoiceLoadingView", + "DynamicCheckoutPaymentSuccessView", + ]) + expect(dispatchedEvents).toEqual([ + { type: PAYMENT_SUCCESS, detail: { ...eventBase, authorized: true, captured: true } }, + ]) + }) + + it.each([["waiting"], ["failed"]])( + "emits payment_cancelled with tab_closed when the transaction is %s", + status => { + const { flow, apiRequest, shownViews } = createFlow([status]) + + flow.confirmClose() + vi.advanceTimersByTime(INTERVAL_MS * 5) + + expect(apiRequest).toHaveBeenCalledOnce() + expect(shownViews()).toEqual([ + "DynamicCheckoutInvoiceLoadingView", + "DynamicCheckoutPaymentCancelledView", + ]) + expect(dispatchedEvents).toEqual([ + { type: PAYMENT_CANCELLED, detail: { ...eventBase, tab_closed: true } }, + ]) + }, + ) + + it("emits payment_cancelled when the status request fails", () => { + const { flow, shownViews } = createFlow(["completed"], { requestFails: true }) + + flow.confirmClose() + + expect(shownViews()).toEqual([ + "DynamicCheckoutInvoiceLoadingView", + "DynamicCheckoutPaymentCancelledView", + ]) + expect(dispatchedEvents.map(event => event.type)).toEqual([PAYMENT_CANCELLED]) + }) + + it("emits nothing when a new attempt takes over before the response", () => { + const { flow, shownViews, respondNow } = createFlow(["completed"], { respond: false }) + + flow.confirmClose() + expect(flow.takeOver()).toBe(false) + respondNow() + + expect(shownViews()).toEqual(["DynamicCheckoutInvoiceLoadingView"]) + expect(dispatchedEvents).toEqual([]) + }) + + it("emits nothing when the widget was removed before the response", () => { + vi.stubGlobal("document", { + visibilityState: "visible", + addEventListener: () => {}, + removeEventListener: () => {}, + body: { contains: () => false }, + }) + const { flow } = createFlow(["completed"]) + + flow.confirmClose() + + expect(dispatchedEvents).toEqual([]) + }) + + it("takeOver() after the check tells that an outcome was reported", () => { + const { flow } = createFlow(["completed"]) + + flow.confirmClose() + + expect(flow.takeOver()).toBe(true) + }) + }) + it("takeOver() before start() reports nothing to ignore", () => { const { flow } = createFlow(["waiting"]) diff --git a/test/dynamic-checkout/opener-loss.test.ts b/test/dynamic-checkout/opener-loss.test.ts index 82d094e1..0482b77e 100644 --- a/test/dynamic-checkout/opener-loss.test.ts +++ b/test/dynamic-checkout/opener-loss.test.ts @@ -138,6 +138,40 @@ describe("DynamicCheckoutOpenerLossUtils.isOpenerLoss", () => { }) }) +describe("DynamicCheckoutOpenerLossUtils.getTabClosedHandling", () => { + const context = { gatewayName: "mercadopagomxcashinaccount", invoiceId: "iv_test" } + + it.each([ + // mode, hasFocus, visibility, expected handling + ["off", true, "visible", "cancel"], + ["off", false, "hidden", "cancel"], + ["shadow", true, "visible", "cancel"], + ["shadow", false, "hidden", "cancel"], + ["on", false, "hidden", "opener_loss"], + ["on", true, "visible", "confirm_close"], + ])("mode=%s hasFocus=%s visibility=%s -> %s", (mode, hasFocus, visibilityState, expected) => { + const handling = OpenerLoss.getTabClosedHandling( + fakeProcessOut(), + tabClosed, + { ...context, mode }, + fakeDocument(hasFocus, visibilityState), + ) + + expect(handling).toBe(expected) + }) + + it("cancels a cancel that isn't a closed tab, even in on mode", () => { + const handling = OpenerLoss.getTabClosedHandling( + fakeProcessOut(), + overlayCancel, + { ...context, mode: "on" }, + fakeDocument(true, "visible"), + ) + + expect(handling).toBe("cancel") + }) +}) + describe("DynamicCheckoutOpenerLossUtils.markRedirectUrl", () => { it.each([ [ diff --git a/test/support/loadNamespace.ts b/test/support/loadNamespace.ts index c81238ad..ec855e04 100644 --- a/test/support/loadNamespace.ts +++ b/test/support/loadNamespace.ts @@ -322,6 +322,7 @@ export function loadOpenerLossFlow(): DynamicCheckoutNamespace { viewStub("DynamicCheckoutPaymentInfoView"), viewStub("DynamicCheckoutPaymentErrorView"), viewStub("DynamicCheckoutPaymentPendingView"), + viewStub("DynamicCheckoutInvoiceLoadingView"), compile("src/dynamic-checkout/utils/transaction-poller.ts"), `const { DynamicCheckoutTransactionPoller } = ProcessOut;`, compile("src/dynamic-checkout/utils/opener-loss-flow.ts"), From b2b22cb7e4856ee42b05382ec3e16fec2bb77b9b Mon Sep 17 00:00:00 2001 From: Jakub Binczyk Date: Wed, 25 Nov 2026 15:54:09 +0100 Subject: [PATCH 4/5] feat(POINT-3697)(dc): back off the transaction polling interval from 3 s to 30 s The interval grows by 1.5x after each check, up to 30 s, so a shopper who keeps the DC tab open makes about 35 requests in 15 minutes instead of about 300. Coming back to the tab still checks at once and starts again at 3 s, and the last wait never runs past the timeout. --- .../utils/transaction-poller.ts | 35 ++++++++-- .../transaction-poller.test.ts | 64 ++++++++++++++++++- 2 files changed, 92 insertions(+), 7 deletions(-) diff --git a/src/dynamic-checkout/utils/transaction-poller.ts b/src/dynamic-checkout/utils/transaction-poller.ts index bff59996..5bb107ac 100644 --- a/src/dynamic-checkout/utils/transaction-poller.ts +++ b/src/dynamic-checkout/utils/transaction-poller.ts @@ -3,7 +3,11 @@ module ProcessOut { const SUCCESSFUL_TRANSACTION_STATUSES = ["authorized", "pending-capture", "completed"] const FAILED_TRANSACTION_STATUSES = ["failed", "voided", "blocked"] + // The interval starts at 3 s and grows by 1.5x after each check, up to 30 s, so a shopper who keeps the + // DC tab open doesn't poll every 3 s for 15 minutes. Coming back to the tab checks at once and starts again at 3 s. export const TRANSACTION_POLLING_INTERVAL_MS = 3000 + export const TRANSACTION_POLLING_MAX_INTERVAL_MS = 30 * 1000 + export const TRANSACTION_POLLING_BACKOFF_FACTOR = 1.5 // Same as the APM v2 default timeout. export const TRANSACTION_POLLING_TIMEOUT_MS = 15 * 60 * 1000 @@ -22,7 +26,9 @@ module ProcessOut { onTimeout: () => void // Polling stops silently once this returns false, e.g. when the merchant removes the widget. isMounted: () => boolean + // First interval; it grows by TRANSACTION_POLLING_BACKOFF_FACTOR up to maxIntervalMs. intervalMs?: number + maxIntervalMs?: number timeoutMs?: number now?: () => number win?: Window @@ -38,6 +44,7 @@ module ProcessOut { private startedAt = 0 private timer: number | null = null private requestInFlight = false + private delayMs = 0 private finished = false constructor(options: DynamicCheckoutTransactionPollerOptions) { @@ -47,6 +54,7 @@ module ProcessOut { public start() { this.startedAt = this.now() + this.delayMs = this.getInitialIntervalMs() this.getWindow().addEventListener("focus", this.onPageActive) this.getDocument().addEventListener("visibilitychange", this.onPageActive) this.check() @@ -74,6 +82,7 @@ module ProcessOut { private onPageActive() { if (this.isPageVisible()) { + this.delayMs = this.getInitialIntervalMs() this.check() } } @@ -109,6 +118,7 @@ module ProcessOut { () => { this.requestInFlight = false this.scheduleNext() + this.growDelay() }, 0, { @@ -136,17 +146,34 @@ module ProcessOut { } this.scheduleNext() + this.growDelay() } + // Never waits past the timeout, so onTimeout fires on time even with a long interval. private scheduleNext() { if (this.finished) { return } this.clearTimer() - this.timer = this.getWindow().setTimeout(() => { - this.timer = null - this.check() - }, this.options.intervalMs || TRANSACTION_POLLING_INTERVAL_MS) + const remainingMs = this.getTimeoutMs() - (this.now() - this.startedAt) + this.timer = this.getWindow().setTimeout( + () => { + this.timer = null + this.check() + }, + Math.max(0, Math.min(this.delayMs, remainingMs)), + ) + } + + private growDelay() { + this.delayMs = Math.min( + this.delayMs * TRANSACTION_POLLING_BACKOFF_FACTOR, + this.options.maxIntervalMs || TRANSACTION_POLLING_MAX_INTERVAL_MS, + ) + } + + private getInitialIntervalMs() { + return this.options.intervalMs || TRANSACTION_POLLING_INTERVAL_MS } private clearTimer() { diff --git a/test/dynamic-checkout/transaction-poller.test.ts b/test/dynamic-checkout/transaction-poller.test.ts index 6aa8f1e8..7f39c0dd 100644 --- a/test/dynamic-checkout/transaction-poller.test.ts +++ b/test/dynamic-checkout/transaction-poller.test.ts @@ -2,8 +2,23 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" import { LOCALES, loadDynamicCheckout, loadTransactionPoller } from "../support/loadNamespace" const INTERVAL_MS = 3000 +const MAX_INTERVAL_MS = 30 * 1000 +const BACKOFF_FACTOR = 1.5 const TIMEOUT_MS = 15 * 60 * 1000 +// Start times of the checks while the page stays visible: 0, 3 s, 7.5 s, … with the interval capped at 30 s. +function checkTimesUntil(endMs: number): number[] { + const times: number[] = [] + let at = 0 + let delay = INTERVAL_MS + while (at < endMs) { + times.push(at) + at += Math.min(delay, endMs - at) + delay = Math.min(delay * BACKOFF_FACTOR, MAX_INTERVAL_MS) + } + return times +} + let Poller: any beforeEach(() => { @@ -17,7 +32,11 @@ afterEach(() => { type FakeResponse = { status?: string; error?: boolean } -function createHarness(responses: FakeResponse[], visibilityState = "visible") { +function createHarness( + responses: FakeResponse[], + visibilityState = "visible", + options: { timeoutMs?: number } = {}, +) { const listeners: Record void>> = {} const addListener = (type: string, listener: () => void) => { listeners[type] = [...(listeners[type] || []), listener] @@ -59,6 +78,7 @@ function createHarness(responses: FakeResponse[], visibilityState = "visible") { now: () => Date.now(), win, doc, + ...options, }) return { @@ -87,7 +107,7 @@ describe("DynamicCheckoutTransactionPoller", () => { expect(h.apiRequest.mock.calls[0][6]).toEqual({ isLegacy: false, clientSecret: "secret" }) }) - it("polls every 3 s until a successful status, then reports it once and stops", () => { + it("polls until a successful status, then reports it once and stops", () => { const h = createHarness([{ status: "waiting" }, { status: "pending" }, { status: "completed" }]) h.poller.start() @@ -152,6 +172,32 @@ describe("DynamicCheckoutTransactionPoller", () => { expect(h.apiRequest).toHaveBeenCalledTimes(2) }) + it("starts at 3 s and grows the interval by 1.5x up to 30 s", () => { + const h = createHarness([{ status: "waiting" }]) + const expectedDelays = [3000, 4500, 6750, 10125, 15187.5, 22781.25, 30000, 30000] + + h.poller.start() + for (const [index, delay] of expectedDelays.entries()) { + vi.advanceTimersByTime(delay - 1) + expect(h.apiRequest).toHaveBeenCalledTimes(index + 1) + vi.advanceTimersByTime(1) + expect(h.apiRequest).toHaveBeenCalledTimes(index + 2) + } + }) + + it("starts again at 3 s when the shopper comes back to the page", () => { + const h = createHarness([{ status: "waiting" }]) + + h.poller.start() + vi.advanceTimersByTime(3000 + 4500 + 6750) + expect(h.apiRequest).toHaveBeenCalledTimes(4) + + h.fire("focus") + expect(h.apiRequest).toHaveBeenCalledTimes(5) + vi.advanceTimersByTime(INTERVAL_MS) + expect(h.apiRequest).toHaveBeenCalledTimes(6) + }) + it("times out after 15 min with a single timeout callback", () => { const h = createHarness([{ status: "waiting" }]) @@ -160,10 +206,22 @@ describe("DynamicCheckoutTransactionPoller", () => { expect(h.callbacks.onTimeout).toHaveBeenCalledOnce() expect(h.callbacks.onSuccess).not.toHaveBeenCalled() - expect(h.apiRequest).toHaveBeenCalledTimes(TIMEOUT_MS / INTERVAL_MS) + expect(h.apiRequest).toHaveBeenCalledTimes(checkTimesUntil(TIMEOUT_MS).length) expect(h.listenerCount()).toBe(0) }) + it("doesn't wait past the timeout when the interval is longer than the time left", () => { + const h = createHarness([{ status: "waiting" }], "visible", { timeoutMs: 10000 }) + + h.poller.start() + vi.advanceTimersByTime(9999) + expect(h.callbacks.onTimeout).not.toHaveBeenCalled() + + vi.advanceTimersByTime(1) + expect(h.callbacks.onTimeout).toHaveBeenCalledOnce() + expect(h.apiRequest).toHaveBeenCalledTimes(3) + }) + it("times out even while the page stays hidden", () => { const h = createHarness([{ status: "waiting" }], "hidden") From a29cf943c5fd9530c438ffab295fc670ed54c3a5 Mon Sep 17 00:00:00 2001 From: Jakub Binczyk Date: Fri, 27 Nov 2026 16:13:59 +0100 Subject: [PATCH 5/5] fix(POINT-3697)(dc): settle the opener loss flow once, and bound its requests - A late postMessage error after a lost opener goes through the same first-outcome-wins check as a late token, so it can't report a second outcome or leave polling running. - The save-for-future path passes the new customer_token_id to the opener loss flow. - Cancel on the awaiting view does nothing once polling has reported an outcome (the view stays mounted for the merchant redirect when status messages are off). - apiRequest has no XHR timeout: a polling request counts as an error after 30 s, so the 15 min timeout still fires, and the real-close check falls back to payment cancelled after 10 s. - A final status that arrives after the widget was removed is ignored. --- src/dynamic-checkout/payment-methods/apm.ts | 16 +++-- .../payment-methods/saved-apm.ts | 4 +- .../utils/opener-loss-flow.ts | 20 +++++++ .../utils/transaction-poller.ts | 60 ++++++++++++++++--- .../dynamic-checkout/opener-loss-flow.test.ts | 39 ++++++++++++ .../transaction-poller.test.ts | 49 +++++++++++++++ 6 files changed, 173 insertions(+), 15 deletions(-) diff --git a/src/dynamic-checkout/payment-methods/apm.ts b/src/dynamic-checkout/payment-methods/apm.ts index 7d6cb78c..fa6af205 100644 --- a/src/dynamic-checkout/payment-methods/apm.ts +++ b/src/dynamic-checkout/payment-methods/apm.ts @@ -192,7 +192,7 @@ module ProcessOut { ) }, error => { - if (this.handleOpenerLoss(error, actionStartedAt)) { + if (this.isOpenerLossResolved() || this.handleOpenerLoss(error, actionStartedAt)) { return } @@ -391,7 +391,10 @@ module ProcessOut { ) }, error => { - if (this.handleOpenerLoss(error, actionStartedAt)) { + if ( + this.isOpenerLossResolved() || + this.handleOpenerLoss(error, actionStartedAt, data.customer_token_id) + ) { return } @@ -477,7 +480,11 @@ module ProcessOut { * Returns true when the opener-loss flow took over: pending for a lost opener, or a status check before * "payment cancelled" for a real close (`on` mode only). */ - private handleOpenerLoss(error: Exception, actionStartedAt: number): boolean { + private handleOpenerLoss( + error: Exception, + actionStartedAt: number, + customerTokenId?: string, + ): boolean { const { apm } = this.paymentMethod const handling = DynamicCheckoutOpenerLossUtils.getTabClosedHandling( this.processOutInstance, @@ -499,6 +506,7 @@ module ProcessOut { resetContainerHtml: this.resetContainerHtml, gatewayName: apm.gateway_name, paymentMethodDisplayName: this.paymentMethodDisplayName, + customerTokenId, }) if (handling === "opener_loss") { this.openerLossFlow.start() @@ -515,7 +523,7 @@ module ProcessOut { } } - // A late postMessage token after a lost opener: the first outcome wins. + // A late postMessage result (token or error) after a lost opener: the first outcome wins. private isOpenerLossResolved(): boolean { return !!this.openerLossFlow && this.openerLossFlow.takeOver() } diff --git a/src/dynamic-checkout/payment-methods/saved-apm.ts b/src/dynamic-checkout/payment-methods/saved-apm.ts index fbbe62ca..b4e5c7dd 100644 --- a/src/dynamic-checkout/payment-methods/saved-apm.ts +++ b/src/dynamic-checkout/payment-methods/saved-apm.ts @@ -178,7 +178,7 @@ module ProcessOut { ) }, error => { - if (this.handleOpenerLoss(error, actionStartedAt)) { + if (this.isOpenerLossResolved() || this.handleOpenerLoss(error, actionStartedAt)) { return } @@ -284,7 +284,7 @@ module ProcessOut { } } - // A late postMessage token after a lost opener: the first outcome wins. + // A late postMessage result (token or error) after a lost opener: the first outcome wins. private isOpenerLossResolved(): boolean { return !!this.openerLossFlow && this.openerLossFlow.takeOver() } diff --git a/src/dynamic-checkout/utils/opener-loss-flow.ts b/src/dynamic-checkout/utils/opener-loss-flow.ts index 3b906e02..a37bb2ea 100644 --- a/src/dynamic-checkout/utils/opener-loss-flow.ts +++ b/src/dynamic-checkout/utils/opener-loss-flow.ts @@ -1,5 +1,7 @@ module ProcessOut { export const OPENER_LOSS_PENDING_REASON = "opener_isolated" + // apiRequest has no XHR timeout: without an answer by then, the close check falls back to "payment cancelled". + export const OPENER_LOSS_CLOSE_CHECK_TIMEOUT_MS = 10 * 1000 export type DynamicCheckoutOpenerLossFlowOptions = { processOutInstance: ProcessOut @@ -20,6 +22,7 @@ module ProcessOut { private poller: DynamicCheckoutTransactionPoller | null = null private view: Element | null = null private closeCheckPending = false + private closeCheckTimer: number | null = null private closeCheckReported = false constructor(options: DynamicCheckoutOpenerLossFlowOptions) { @@ -58,6 +61,10 @@ module ProcessOut { this.view = new DynamicCheckoutInvoiceLoadingView(paymentConfig.locale).element this.options.resetContainerHtml().appendChild(this.view) this.closeCheckPending = true + this.closeCheckTimer = window.setTimeout( + () => this.finishCloseCheck(null), + OPENER_LOSS_CLOSE_CHECK_TIMEOUT_MS, + ) processOutInstance.apiRequest( "GET", @@ -80,6 +87,7 @@ module ProcessOut { public takeOver(): boolean { if (this.closeCheckPending) { this.closeCheckPending = false + this.clearCloseCheckTimer() return false } if (!this.poller) { @@ -95,6 +103,7 @@ module ProcessOut { return } this.closeCheckPending = false + this.clearCloseCheckTimer() if (!this.view || !document.body.contains(this.view)) { return } @@ -107,11 +116,22 @@ module ProcessOut { } } + // The awaiting view stays mounted after success when the merchant redirects, so Cancel must not report a second outcome. private cancel() { + if (this.poller.isFinished()) { + return + } this.poller.stop() this.showCancelled() } + private clearCloseCheckTimer() { + if (this.closeCheckTimer !== null) { + window.clearTimeout(this.closeCheckTimer) + this.closeCheckTimer = null + } + } + private showCancelled() { this.options .resetContainerHtml() diff --git a/src/dynamic-checkout/utils/transaction-poller.ts b/src/dynamic-checkout/utils/transaction-poller.ts index 5bb107ac..72b73932 100644 --- a/src/dynamic-checkout/utils/transaction-poller.ts +++ b/src/dynamic-checkout/utils/transaction-poller.ts @@ -10,6 +10,8 @@ module ProcessOut { export const TRANSACTION_POLLING_BACKOFF_FACTOR = 1.5 // Same as the APM v2 default timeout. export const TRANSACTION_POLLING_TIMEOUT_MS = 15 * 60 * 1000 + // apiRequest has no XHR timeout: a request that never answers counts as an error after this, so polling goes on. + export const TRANSACTION_POLLING_REQUEST_TIMEOUT_MS = 30 * 1000 export type PolledTransaction = { status: string @@ -30,6 +32,7 @@ module ProcessOut { intervalMs?: number maxIntervalMs?: number timeoutMs?: number + requestTimeoutMs?: number now?: () => number win?: Window doc?: Document @@ -43,7 +46,9 @@ module ProcessOut { private options: DynamicCheckoutTransactionPollerOptions private startedAt = 0 private timer: number | null = null + private requestTimer: number | null = null private requestInFlight = false + private requestCount = 0 private delayMs = 0 private finished = false @@ -64,6 +69,7 @@ module ProcessOut { public stop() { this.finished = true this.clearTimer() + this.clearRequestTimer() this.getWindow().removeEventListener("focus", this.onPageActive) this.getDocument().removeEventListener("visibilitychange", this.onPageActive) } @@ -107,19 +113,21 @@ module ProcessOut { this.clearTimer() this.requestInFlight = true + const request = ++this.requestCount + const remainingMs = this.getTimeoutMs() - (this.now() - this.startedAt) + this.requestTimer = this.getWindow().setTimeout( + () => this.finishRequest(request, null), + Math.min(this.getRequestTimeoutMs(), remainingMs), + ) this.options.processOutInstance.apiRequest( "GET", `invoices/${this.options.invoiceId}?expand=transaction`, {}, - data => { - this.requestInFlight = false - this.handleTransaction(data && data.invoice ? data.invoice.transaction : null) - }, - () => { - this.requestInFlight = false - this.scheduleNext() - this.growDelay() - }, + data => + this.finishRequest(request, { + transaction: data && data.invoice ? data.invoice.transaction : null, + }), + () => this.finishRequest(request, null), 0, { isLegacy: false, @@ -128,10 +136,33 @@ module ProcessOut { ) } + // response is null for a request error or timeout. A response after the request timed out is ignored. + private finishRequest( + request: number, + response: { transaction: PolledTransaction | null } | null, + ) { + if (request !== this.requestCount || !this.requestInFlight) { + return + } + this.requestInFlight = false + this.clearRequestTimer() + + if (response) { + this.handleTransaction(response.transaction) + return + } + this.scheduleNext() + this.growDelay() + } + private handleTransaction(transaction: PolledTransaction | null) { if (this.finished) { return } + if (!this.options.isMounted()) { + this.stop() + return + } const status = transaction ? transaction.status : "" if (DynamicCheckoutTransactionPoller.isSuccessfulStatus(status)) { @@ -183,6 +214,13 @@ module ProcessOut { } } + private clearRequestTimer() { + if (this.requestTimer !== null) { + this.getWindow().clearTimeout(this.requestTimer) + this.requestTimer = null + } + } + private isPageVisible() { return this.getDocument().visibilityState === "visible" } @@ -191,6 +229,10 @@ module ProcessOut { return this.options.timeoutMs || TRANSACTION_POLLING_TIMEOUT_MS } + private getRequestTimeoutMs() { + return this.options.requestTimeoutMs || TRANSACTION_POLLING_REQUEST_TIMEOUT_MS + } + private now() { return this.options.now ? this.options.now() : Date.now() } diff --git a/test/dynamic-checkout/opener-loss-flow.test.ts b/test/dynamic-checkout/opener-loss-flow.test.ts index ab766ad3..82f4b233 100644 --- a/test/dynamic-checkout/opener-loss-flow.test.ts +++ b/test/dynamic-checkout/opener-loss-flow.test.ts @@ -3,6 +3,7 @@ import { CapturedEvent, loadOpenerLossFlow } from "../support/loadNamespace" const INTERVAL_MS = 3000 const TIMEOUT_MS = 15 * 60 * 1000 +const CLOSE_CHECK_TIMEOUT_MS = 10 * 1000 const PAYMENT_SUCCESS = "processout_dynamic_checkout_payment_success" const PAYMENT_ERROR = "processout_dynamic_checkout_payment_error" const PAYMENT_PENDING = "processout_dynamic_checkout_payment_pending" @@ -176,6 +177,17 @@ describe("DynamicCheckoutOpenerLossFlow", () => { ]) }) + it("ignores Cancel on the awaiting view left for the merchant redirect after success", () => { + const { flow, shownViews } = createFlow(["completed"], { showStatusMessage: false }) + + flow.start() + const onCancel = flow["view"].args[2] + onCancel() + + expect(shownViews()).toEqual(["DynamicCheckoutPaymentAwaitingConfirmationView"]) + expect(dispatchedEvents.map(event => event.type)).toEqual([PAYMENT_SUCCESS]) + }) + it("takeOver() stops polling and tells whether an outcome was already reported", () => { const pending = createFlow(["waiting"]) pending.flow.start() @@ -262,6 +274,33 @@ describe("DynamicCheckoutOpenerLossFlow", () => { expect(dispatchedEvents).toEqual([]) }) + it("emits payment_cancelled when the status request doesn't answer within 10 s, and ignores a late answer", () => { + const { flow, shownViews, respondNow } = createFlow(["completed"], { respond: false }) + + flow.confirmClose() + vi.advanceTimersByTime(CLOSE_CHECK_TIMEOUT_MS - 1) + expect(dispatchedEvents).toEqual([]) + + vi.advanceTimersByTime(1) + respondNow() + + expect(shownViews()).toEqual([ + "DynamicCheckoutInvoiceLoadingView", + "DynamicCheckoutPaymentCancelledView", + ]) + expect(dispatchedEvents.map(event => event.type)).toEqual([PAYMENT_CANCELLED]) + }) + + it("emits nothing at the 10 s deadline when a new attempt took over", () => { + const { flow } = createFlow(["completed"], { respond: false }) + + flow.confirmClose() + flow.takeOver() + vi.advanceTimersByTime(CLOSE_CHECK_TIMEOUT_MS) + + expect(dispatchedEvents).toEqual([]) + }) + it("takeOver() after the check tells that an outcome was reported", () => { const { flow } = createFlow(["completed"]) diff --git a/test/dynamic-checkout/transaction-poller.test.ts b/test/dynamic-checkout/transaction-poller.test.ts index 7f39c0dd..bca5fec2 100644 --- a/test/dynamic-checkout/transaction-poller.test.ts +++ b/test/dynamic-checkout/transaction-poller.test.ts @@ -5,6 +5,7 @@ const INTERVAL_MS = 3000 const MAX_INTERVAL_MS = 30 * 1000 const BACKOFF_FACTOR = 1.5 const TIMEOUT_MS = 15 * 60 * 1000 +const REQUEST_TIMEOUT_MS = 30 * 1000 // Start times of the checks while the page stays visible: 0, 3 s, 7.5 s, … with the interval capped at 30 s. function checkTimesUntil(endMs: number): number[] { @@ -272,6 +273,54 @@ describe("DynamicCheckoutTransactionPoller", () => { expect(h.callbacks.onSuccess).not.toHaveBeenCalled() }) + + it("counts a request that never answers as an error after 30 s and polls again", () => { + let lateSuccess: ((data: any) => void) | null = null + const h = createHarness([{ status: "completed" }]) + h.apiRequest.mockImplementationOnce((_m, _p, _d, success) => { + lateSuccess = success + }) + + h.poller.start() + h.fire("focus") + vi.advanceTimersByTime(REQUEST_TIMEOUT_MS - 1) + expect(h.apiRequest).toHaveBeenCalledOnce() + + vi.advanceTimersByTime(1 + INTERVAL_MS) + expect(h.apiRequest).toHaveBeenCalledTimes(2) + expect(h.callbacks.onSuccess).toHaveBeenCalledOnce() + + lateSuccess!({ invoice: { transaction: { status: "failed" } } }) + expect(h.callbacks.onFailure).not.toHaveBeenCalled() + }) + + it("times out after 15 min even when requests never answer", () => { + const h = createHarness([{ status: "waiting" }]) + h.apiRequest.mockImplementation(() => {}) + + h.poller.start() + vi.advanceTimersByTime(TIMEOUT_MS - 1) + expect(h.callbacks.onTimeout).not.toHaveBeenCalled() + + vi.advanceTimersByTime(1) + expect(h.callbacks.onTimeout).toHaveBeenCalledOnce() + }) + + it("ignores a final status that arrives after the widget was removed", () => { + let pendingSuccess: ((data: any) => void) | null = null + const h = createHarness([{ status: "waiting" }]) + h.apiRequest.mockImplementationOnce((_m, _p, _d, success) => { + pendingSuccess = success + }) + + h.poller.start() + h.unmount() + pendingSuccess!({ invoice: { transaction: { status: "completed" } } }) + + expect(h.callbacks.onSuccess).not.toHaveBeenCalled() + expect(h.poller.isFinished()).toBe(true) + expect(h.listenerCount()).toBe(0) + }) }) describe("payment-awaiting-confirmation translations", () => {