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", 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 bf936d4b..fa6af205 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, @@ -115,10 +116,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, ) @@ -185,7 +192,7 @@ module ProcessOut { ) }, error => { - if (this.handleOpenerLoss(error, actionStartedAt)) { + if (this.isOpenerLossResolved() || this.handleOpenerLoss(error, actionStartedAt)) { return } @@ -286,10 +293,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, ) @@ -378,7 +391,10 @@ module ProcessOut { ) }, error => { - if (this.handleOpenerLoss(error, actionStartedAt)) { + if ( + this.isOpenerLossResolved() || + this.handleOpenerLoss(error, actionStartedAt, data.customer_token_id) + ) { return } @@ -461,11 +477,16 @@ 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 { + private handleOpenerLoss( + error: Exception, + actionStartedAt: number, + customerTokenId?: string, + ): boolean { const { apm } = this.paymentMethod - const isOpenerLoss = DynamicCheckoutOpenerLossUtils.isOpenerLoss( + const handling = DynamicCheckoutOpenerLossUtils.getTabClosedHandling( this.processOutInstance, error, { @@ -475,16 +496,38 @@ module ProcessOut { actionStartedAt, }, ) - if (!isOpenerLoss) { + if (handling === "cancel") { 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, + customerTokenId, + }) + if (handling === "opener_loss") { + this.openerLossFlow.start() + } else { + this.openerLossFlow.confirmClose() + } return true } + private resetOpenerLossFlow() { + if (this.openerLossFlow) { + this.openerLossFlow.takeOver() + this.openerLossFlow = null + } + } + + // A late postMessage result (token or error) 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 140fdd5d..b4e5c7dd 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, @@ -89,10 +90,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, @@ -171,7 +178,7 @@ module ProcessOut { ) }, error => { - if (this.handleOpenerLoss(error, actionStartedAt)) { + if (this.isOpenerLossResolved() || this.handleOpenerLoss(error, actionStartedAt)) { return } @@ -235,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, { @@ -249,16 +257,38 @@ module ProcessOut { actionStartedAt, }, ) - if (!isOpenerLoss) { + if (handling === "cancel") { 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, + }) + if (handling === "opener_loss") { + this.openerLossFlow.start() + } else { + this.openerLossFlow.confirmClose() + } return true } + private resetOpenerLossFlow() { + if (this.openerLossFlow) { + this.openerLossFlow.takeOver() + this.openerLossFlow = null + } + } + + // A late postMessage result (token or error) 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..a37bb2ea --- /dev/null +++ b/src/dynamic-checkout/utils/opener-loss-flow.ts @@ -0,0 +1,226 @@ +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 + 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 + private closeCheckPending = false + private closeCheckTimer: number | null = null + private closeCheckReported = false + + 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() + } + + /** + * 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 + this.closeCheckTimer = window.setTimeout( + () => this.finishCloseCheck(null), + OPENER_LOSS_CLOSE_CHECK_TIMEOUT_MS, + ) + + 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.closeCheckPending) { + this.closeCheckPending = false + this.clearCloseCheckTimer() + 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 + this.clearCloseCheckTimer() + if (!this.view || !document.body.contains(this.view)) { + return + } + + this.closeCheckReported = true + if (transaction && DynamicCheckoutTransactionPoller.isSuccessfulStatus(transaction.status)) { + this.showSuccess(transaction) + } else { + this.showCancelled() + } + } + + // 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() + .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/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/src/dynamic-checkout/utils/transaction-poller.ts b/src/dynamic-checkout/utils/transaction-poller.ts new file mode 100644 index 00000000..72b73932 --- /dev/null +++ b/src/dynamic-checkout/utils/transaction-poller.ts @@ -0,0 +1,248 @@ +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"] + + // 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 + // 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 + 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 + // First interval; it grows by TRANSACTION_POLLING_BACKOFF_FACTOR up to maxIntervalMs. + intervalMs?: number + maxIntervalMs?: number + timeoutMs?: number + requestTimeoutMs?: 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 requestTimer: number | null = null + private requestInFlight = false + private requestCount = 0 + private delayMs = 0 + private finished = false + + constructor(options: DynamicCheckoutTransactionPollerOptions) { + this.options = options + this.onPageActive = this.onPageActive.bind(this) + } + + public start() { + this.startedAt = this.now() + this.delayMs = this.getInitialIntervalMs() + 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.clearRequestTimer() + 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.delayMs = this.getInitialIntervalMs() + 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 + 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.finishRequest(request, { + transaction: data && data.invoice ? data.invoice.transaction : null, + }), + () => this.finishRequest(request, null), + 0, + { + isLegacy: false, + clientSecret: this.options.clientSecret, + }, + ) + } + + // 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)) { + this.stop() + this.options.onSuccess(transaction) + return + } + if (DynamicCheckoutTransactionPoller.isFailedStatus(status)) { + this.stop() + this.options.onFailure(transaction) + return + } + + 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() + 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() { + if (this.timer !== null) { + this.getWindow().clearTimeout(this.timer) + this.timer = null + } + } + + private clearRequestTimer() { + if (this.requestTimer !== null) { + this.getWindow().clearTimeout(this.requestTimer) + this.requestTimer = null + } + } + + private isPageVisible() { + return this.getDocument().visibilityState === "visible" + } + + private getTimeoutMs() { + 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() + } + + 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..82f4b233 --- /dev/null +++ b/test/dynamic-checkout/opener-loss-flow.test.ts @@ -0,0 +1,318 @@ +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 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" +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; respond?: boolean; requestFails?: boolean } = {}, +) { + const shownViews: any[] = [] + const container = { appendChild: (element: any) => shownViews.push(element) } + let call = 0 + const pendingResponses: Array<() => void> = [] + const apiRequest = vi.fn((_method, _path, _data, success, failure) => { + const status = statuses[Math.min(call, statuses.length - 1)] + call++ + 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", + 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), + respondNow: () => pendingResponses.splice(0).forEach(respond => respond()), + } +} + +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("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() + 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) + }) + + 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("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"]) + + flow.confirmClose() + + expect(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/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/dynamic-checkout/transaction-poller.test.ts b/test/dynamic-checkout/transaction-poller.test.ts new file mode 100644 index 00000000..bca5fec2 --- /dev/null +++ b/test/dynamic-checkout/transaction-poller.test.ts @@ -0,0 +1,334 @@ +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 +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[] { + 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(() => { + vi.useFakeTimers() + Poller = loadTransactionPoller().DynamicCheckoutTransactionPoller +}) + +afterEach(() => { + vi.useRealTimers() +}) + +type FakeResponse = { status?: string; error?: boolean } + +function createHarness( + responses: FakeResponse[], + visibilityState = "visible", + options: { timeoutMs?: number } = {}, +) { + 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, + ...options, + }) + + 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 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("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" }]) + + h.poller.start() + vi.advanceTimersByTime(TIMEOUT_MS + INTERVAL_MS) + + expect(h.callbacks.onTimeout).toHaveBeenCalledOnce() + expect(h.callbacks.onSuccess).not.toHaveBeenCalled() + 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") + + 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() + }) + + 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", () => { + 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..ec855e04 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,35 @@ 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"), + viewStub("DynamicCheckoutInvoiceLoadingView"), + compile("src/dynamic-checkout/utils/transaction-poller.ts"), + `const { DynamicCheckoutTransactionPoller } = ProcessOut;`, + compile("src/dynamic-checkout/utils/opener-loss-flow.ts"), + ]) +}