@swichpay/react-native 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (277) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/LICENSE +21 -0
  3. package/README.md +82 -2
  4. package/docs/checkouts.md +98 -0
  5. package/docs/getting-started.md +140 -0
  6. package/docs/going-live.md +45 -0
  7. package/docs/own-screen.md +81 -0
  8. package/docs/results-and-errors.md +75 -0
  9. package/docs/server.md +163 -0
  10. package/docs/troubleshooting.md +57 -0
  11. package/lib/commonjs/HostedCheckout.js +115 -0
  12. package/lib/commonjs/checkout-webview.js +85 -0
  13. package/lib/commonjs/checkouts/PaymentSheet.js +1317 -0
  14. package/lib/commonjs/checkouts/direct.js +671 -0
  15. package/lib/commonjs/context.js +64 -0
  16. package/lib/commonjs/core/api/direct-payment-api.js +425 -0
  17. package/lib/commonjs/core/api/discount-api.js +19 -0
  18. package/lib/commonjs/core/api/gateway-api.js +366 -0
  19. package/lib/commonjs/core/api/payments-api.js +79 -0
  20. package/lib/commonjs/core/api/repositories.js +5 -0
  21. package/lib/commonjs/core/assets/images.js +12 -0
  22. package/lib/commonjs/core/assets/method-logos.js +19 -0
  23. package/lib/commonjs/core/assets/pwa-images.js +13 -0
  24. package/lib/commonjs/core/browser/clipboard.js +30 -0
  25. package/lib/commonjs/core/browser/dom.js +71 -0
  26. package/lib/commonjs/core/browser/hosted-checkout.js +107 -0
  27. package/lib/commonjs/core/browser/index.js +119 -0
  28. package/lib/commonjs/core/browser/qr.js +109 -0
  29. package/lib/commonjs/core/browser/three-ds.js +151 -0
  30. package/lib/commonjs/core/client.js +344 -0
  31. package/lib/commonjs/core/config.js +132 -0
  32. package/lib/commonjs/core/environment.js +34 -0
  33. package/lib/commonjs/core/errors.js +138 -0
  34. package/lib/commonjs/core/events.js +57 -0
  35. package/lib/commonjs/core/flows/controller.js +106 -0
  36. package/lib/commonjs/core/flows/countdown.js +41 -0
  37. package/lib/commonjs/core/flows/direct-bank-transfer.js +236 -0
  38. package/lib/commonjs/core/flows/direct-card.js +354 -0
  39. package/lib/commonjs/core/flows/direct-ewallet.js +124 -0
  40. package/lib/commonjs/core/flows/direct-one-bill.js +172 -0
  41. package/lib/commonjs/core/flows/direct-qr.js +109 -0
  42. package/lib/commonjs/core/flows/direct-rtp.js +302 -0
  43. package/lib/commonjs/core/flows/discount-lookup.js +80 -0
  44. package/lib/commonjs/core/flows/headless.js +94 -0
  45. package/lib/commonjs/core/flows/payment-sheet.js +1321 -0
  46. package/lib/commonjs/core/flows/services.js +31 -0
  47. package/lib/commonjs/core/flows/shared.js +90 -0
  48. package/lib/commonjs/core/http/api-client.js +208 -0
  49. package/lib/commonjs/core/http/endpoints.js +61 -0
  50. package/lib/commonjs/core/http/token-manager.js +46 -0
  51. package/lib/commonjs/core/http/transport.js +134 -0
  52. package/lib/commonjs/core/index.js +688 -0
  53. package/lib/commonjs/core/models/category.js +113 -0
  54. package/lib/commonjs/core/models/discount.js +51 -0
  55. package/lib/commonjs/core/models/payment.js +95 -0
  56. package/lib/commonjs/core/models/session.js +131 -0
  57. package/lib/commonjs/core/server/index.js +64 -0
  58. package/lib/commonjs/core/server/node.js +60 -0
  59. package/lib/commonjs/core/server/proxy.js +194 -0
  60. package/lib/commonjs/core/server/verify.js +122 -0
  61. package/lib/commonjs/core/swichpay.js +72 -0
  62. package/lib/commonjs/core/utils/crypto.js +78 -0
  63. package/lib/commonjs/core/utils/formatters.js +68 -0
  64. package/lib/commonjs/core/utils/json.js +110 -0
  65. package/lib/commonjs/core/utils/log.js +75 -0
  66. package/lib/commonjs/core/utils/runtime.js +34 -0
  67. package/lib/commonjs/core/utils/validators.js +59 -0
  68. package/lib/commonjs/hooks.js +77 -0
  69. package/lib/commonjs/index.js +203 -0
  70. package/lib/commonjs/package.json +1 -0
  71. package/lib/commonjs/polyfills.js +3 -0
  72. package/lib/commonjs/presenter.js +61 -0
  73. package/lib/commonjs/provider.js +192 -0
  74. package/lib/commonjs/swichpay.js +192 -0
  75. package/lib/commonjs/theme.js +54 -0
  76. package/lib/commonjs/ui.js +1142 -0
  77. package/lib/commonjs/webviews.js +279 -0
  78. package/lib/module/HostedCheckout.js +111 -0
  79. package/lib/module/checkout-webview.js +83 -0
  80. package/lib/module/checkouts/PaymentSheet.js +1313 -0
  81. package/lib/module/checkouts/direct.js +661 -0
  82. package/lib/module/context.js +58 -0
  83. package/lib/module/core/api/direct-payment-api.js +413 -0
  84. package/lib/module/core/api/discount-api.js +14 -0
  85. package/lib/module/core/api/gateway-api.js +358 -0
  86. package/lib/module/core/api/payments-api.js +73 -0
  87. package/lib/module/core/api/repositories.js +3 -0
  88. package/lib/module/core/assets/images.js +8 -0
  89. package/lib/module/core/assets/method-logos.js +15 -0
  90. package/lib/module/core/assets/pwa-images.js +9 -0
  91. package/lib/module/core/browser/clipboard.js +27 -0
  92. package/lib/module/core/browser/dom.js +63 -0
  93. package/lib/module/core/browser/hosted-checkout.js +102 -0
  94. package/lib/module/core/browser/index.js +12 -0
  95. package/lib/module/core/browser/qr.js +100 -0
  96. package/lib/module/core/browser/three-ds.js +145 -0
  97. package/lib/module/core/client.js +338 -0
  98. package/lib/module/core/config.js +128 -0
  99. package/lib/module/core/environment.js +29 -0
  100. package/lib/module/core/errors.js +125 -0
  101. package/lib/module/core/events.js +51 -0
  102. package/lib/module/core/flows/controller.js +101 -0
  103. package/lib/module/core/flows/countdown.js +36 -0
  104. package/lib/module/core/flows/direct-bank-transfer.js +231 -0
  105. package/lib/module/core/flows/direct-card.js +349 -0
  106. package/lib/module/core/flows/direct-ewallet.js +119 -0
  107. package/lib/module/core/flows/direct-one-bill.js +167 -0
  108. package/lib/module/core/flows/direct-qr.js +104 -0
  109. package/lib/module/core/flows/direct-rtp.js +297 -0
  110. package/lib/module/core/flows/discount-lookup.js +75 -0
  111. package/lib/module/core/flows/headless.js +90 -0
  112. package/lib/module/core/flows/payment-sheet.js +1315 -0
  113. package/lib/module/core/flows/services.js +27 -0
  114. package/lib/module/core/flows/shared.js +78 -0
  115. package/lib/module/core/http/api-client.js +203 -0
  116. package/lib/module/core/http/endpoints.js +57 -0
  117. package/lib/module/core/http/token-manager.js +41 -0
  118. package/lib/module/core/http/transport.js +126 -0
  119. package/lib/module/core/index.js +52 -0
  120. package/lib/module/core/models/category.js +104 -0
  121. package/lib/module/core/models/discount.js +46 -0
  122. package/lib/module/core/models/payment.js +89 -0
  123. package/lib/module/core/models/session.js +120 -0
  124. package/lib/module/core/server/index.js +11 -0
  125. package/lib/module/core/server/node.js +56 -0
  126. package/lib/module/core/server/proxy.js +191 -0
  127. package/lib/module/core/server/verify.js +115 -0
  128. package/lib/module/core/swichpay.js +68 -0
  129. package/lib/module/core/utils/crypto.js +72 -0
  130. package/lib/module/core/utils/formatters.js +56 -0
  131. package/lib/module/core/utils/json.js +94 -0
  132. package/lib/module/core/utils/log.js +67 -0
  133. package/lib/module/core/utils/runtime.js +28 -0
  134. package/lib/module/core/utils/validators.js +54 -0
  135. package/lib/module/hooks.js +72 -0
  136. package/lib/module/index.js +36 -0
  137. package/lib/module/polyfills.js +4 -0
  138. package/lib/module/presenter.js +58 -0
  139. package/lib/module/provider.js +188 -0
  140. package/lib/module/swichpay.js +187 -0
  141. package/lib/module/theme.js +50 -0
  142. package/lib/module/ui.js +1116 -0
  143. package/lib/module/webviews.js +272 -0
  144. package/lib/typescript/commonjs/HostedCheckout.d.ts +17 -0
  145. package/lib/typescript/commonjs/checkout-webview.d.ts +14 -0
  146. package/lib/typescript/commonjs/checkouts/PaymentSheet.d.ts +14 -0
  147. package/lib/typescript/commonjs/checkouts/direct.d.ts +18 -0
  148. package/lib/typescript/commonjs/context.d.ts +20 -0
  149. package/lib/typescript/commonjs/core/api/direct-payment-api.d.ts +103 -0
  150. package/lib/typescript/commonjs/core/api/discount-api.d.ts +10 -0
  151. package/lib/typescript/commonjs/core/api/gateway-api.d.ts +150 -0
  152. package/lib/typescript/commonjs/core/api/payments-api.d.ts +22 -0
  153. package/lib/typescript/commonjs/core/api/repositories.d.ts +86 -0
  154. package/lib/typescript/commonjs/core/assets/images.d.ts +5 -0
  155. package/lib/typescript/commonjs/core/assets/method-logos.d.ts +12 -0
  156. package/lib/typescript/commonjs/core/assets/pwa-images.d.ts +7 -0
  157. package/lib/typescript/commonjs/core/browser/clipboard.d.ts +3 -0
  158. package/lib/typescript/commonjs/core/browser/dom.d.ts +11 -0
  159. package/lib/typescript/commonjs/core/browser/hosted-checkout.d.ts +27 -0
  160. package/lib/typescript/commonjs/core/browser/index.d.ts +11 -0
  161. package/lib/typescript/commonjs/core/browser/qr.d.ts +18 -0
  162. package/lib/typescript/commonjs/core/browser/three-ds.d.ts +45 -0
  163. package/lib/typescript/commonjs/core/client.d.ts +181 -0
  164. package/lib/typescript/commonjs/core/config.d.ts +86 -0
  165. package/lib/typescript/commonjs/core/environment.d.ts +22 -0
  166. package/lib/typescript/commonjs/core/errors.d.ts +78 -0
  167. package/lib/typescript/commonjs/core/events.d.ts +19 -0
  168. package/lib/typescript/commonjs/core/flows/controller.d.ts +41 -0
  169. package/lib/typescript/commonjs/core/flows/countdown.d.ts +15 -0
  170. package/lib/typescript/commonjs/core/flows/direct-bank-transfer.d.ts +49 -0
  171. package/lib/typescript/commonjs/core/flows/direct-card.d.ts +94 -0
  172. package/lib/typescript/commonjs/core/flows/direct-ewallet.d.ts +39 -0
  173. package/lib/typescript/commonjs/core/flows/direct-one-bill.d.ts +38 -0
  174. package/lib/typescript/commonjs/core/flows/direct-qr.d.ts +25 -0
  175. package/lib/typescript/commonjs/core/flows/direct-rtp.d.ts +72 -0
  176. package/lib/typescript/commonjs/core/flows/discount-lookup.d.ts +37 -0
  177. package/lib/typescript/commonjs/core/flows/headless.d.ts +38 -0
  178. package/lib/typescript/commonjs/core/flows/payment-sheet.d.ts +263 -0
  179. package/lib/typescript/commonjs/core/flows/services.d.ts +22 -0
  180. package/lib/typescript/commonjs/core/flows/shared.d.ts +40 -0
  181. package/lib/typescript/commonjs/core/http/api-client.d.ts +37 -0
  182. package/lib/typescript/commonjs/core/http/endpoints.d.ts +39 -0
  183. package/lib/typescript/commonjs/core/http/token-manager.d.ts +19 -0
  184. package/lib/typescript/commonjs/core/http/transport.d.ts +37 -0
  185. package/lib/typescript/commonjs/core/index.d.ts +42 -0
  186. package/lib/typescript/commonjs/core/models/category.d.ts +35 -0
  187. package/lib/typescript/commonjs/core/models/discount.d.ts +41 -0
  188. package/lib/typescript/commonjs/core/models/payment.d.ts +104 -0
  189. package/lib/typescript/commonjs/core/models/session.d.ts +87 -0
  190. package/lib/typescript/commonjs/core/server/index.d.ts +10 -0
  191. package/lib/typescript/commonjs/core/server/node.d.ts +19 -0
  192. package/lib/typescript/commonjs/core/server/proxy.d.ts +30 -0
  193. package/lib/typescript/commonjs/core/server/verify.d.ts +61 -0
  194. package/lib/typescript/commonjs/core/swichpay.d.ts +40 -0
  195. package/lib/typescript/commonjs/core/utils/crypto.d.ts +19 -0
  196. package/lib/typescript/commonjs/core/utils/formatters.d.ts +19 -0
  197. package/lib/typescript/commonjs/core/utils/json.d.ts +27 -0
  198. package/lib/typescript/commonjs/core/utils/log.d.ts +15 -0
  199. package/lib/typescript/commonjs/core/utils/runtime.d.ts +12 -0
  200. package/lib/typescript/commonjs/core/utils/validators.d.ts +23 -0
  201. package/lib/typescript/commonjs/hooks.d.ts +21 -0
  202. package/lib/typescript/commonjs/index.d.ts +26 -0
  203. package/lib/typescript/commonjs/package.json +1 -0
  204. package/lib/typescript/commonjs/polyfills.d.ts +2 -0
  205. package/lib/typescript/commonjs/presenter.d.ts +25 -0
  206. package/lib/typescript/commonjs/provider.d.ts +22 -0
  207. package/lib/typescript/commonjs/swichpay.d.ts +125 -0
  208. package/lib/typescript/commonjs/theme.d.ts +52 -0
  209. package/lib/typescript/commonjs/ui.d.ts +583 -0
  210. package/lib/typescript/commonjs/webviews.d.ts +40 -0
  211. package/lib/typescript/module/HostedCheckout.d.ts +17 -0
  212. package/lib/typescript/module/checkout-webview.d.ts +14 -0
  213. package/lib/typescript/module/checkouts/PaymentSheet.d.ts +14 -0
  214. package/lib/typescript/module/checkouts/direct.d.ts +18 -0
  215. package/lib/typescript/module/context.d.ts +20 -0
  216. package/lib/typescript/module/core/api/direct-payment-api.d.ts +103 -0
  217. package/lib/typescript/module/core/api/discount-api.d.ts +10 -0
  218. package/lib/typescript/module/core/api/gateway-api.d.ts +150 -0
  219. package/lib/typescript/module/core/api/payments-api.d.ts +22 -0
  220. package/lib/typescript/module/core/api/repositories.d.ts +86 -0
  221. package/lib/typescript/module/core/assets/images.d.ts +5 -0
  222. package/lib/typescript/module/core/assets/method-logos.d.ts +12 -0
  223. package/lib/typescript/module/core/assets/pwa-images.d.ts +7 -0
  224. package/lib/typescript/module/core/browser/clipboard.d.ts +3 -0
  225. package/lib/typescript/module/core/browser/dom.d.ts +11 -0
  226. package/lib/typescript/module/core/browser/hosted-checkout.d.ts +27 -0
  227. package/lib/typescript/module/core/browser/index.d.ts +11 -0
  228. package/lib/typescript/module/core/browser/qr.d.ts +18 -0
  229. package/lib/typescript/module/core/browser/three-ds.d.ts +45 -0
  230. package/lib/typescript/module/core/client.d.ts +181 -0
  231. package/lib/typescript/module/core/config.d.ts +86 -0
  232. package/lib/typescript/module/core/environment.d.ts +22 -0
  233. package/lib/typescript/module/core/errors.d.ts +78 -0
  234. package/lib/typescript/module/core/events.d.ts +19 -0
  235. package/lib/typescript/module/core/flows/controller.d.ts +41 -0
  236. package/lib/typescript/module/core/flows/countdown.d.ts +15 -0
  237. package/lib/typescript/module/core/flows/direct-bank-transfer.d.ts +49 -0
  238. package/lib/typescript/module/core/flows/direct-card.d.ts +94 -0
  239. package/lib/typescript/module/core/flows/direct-ewallet.d.ts +39 -0
  240. package/lib/typescript/module/core/flows/direct-one-bill.d.ts +38 -0
  241. package/lib/typescript/module/core/flows/direct-qr.d.ts +25 -0
  242. package/lib/typescript/module/core/flows/direct-rtp.d.ts +72 -0
  243. package/lib/typescript/module/core/flows/discount-lookup.d.ts +37 -0
  244. package/lib/typescript/module/core/flows/headless.d.ts +38 -0
  245. package/lib/typescript/module/core/flows/payment-sheet.d.ts +263 -0
  246. package/lib/typescript/module/core/flows/services.d.ts +22 -0
  247. package/lib/typescript/module/core/flows/shared.d.ts +40 -0
  248. package/lib/typescript/module/core/http/api-client.d.ts +37 -0
  249. package/lib/typescript/module/core/http/endpoints.d.ts +39 -0
  250. package/lib/typescript/module/core/http/token-manager.d.ts +19 -0
  251. package/lib/typescript/module/core/http/transport.d.ts +37 -0
  252. package/lib/typescript/module/core/index.d.ts +42 -0
  253. package/lib/typescript/module/core/models/category.d.ts +35 -0
  254. package/lib/typescript/module/core/models/discount.d.ts +41 -0
  255. package/lib/typescript/module/core/models/payment.d.ts +104 -0
  256. package/lib/typescript/module/core/models/session.d.ts +87 -0
  257. package/lib/typescript/module/core/server/index.d.ts +10 -0
  258. package/lib/typescript/module/core/server/node.d.ts +19 -0
  259. package/lib/typescript/module/core/server/proxy.d.ts +30 -0
  260. package/lib/typescript/module/core/server/verify.d.ts +61 -0
  261. package/lib/typescript/module/core/swichpay.d.ts +40 -0
  262. package/lib/typescript/module/core/utils/crypto.d.ts +19 -0
  263. package/lib/typescript/module/core/utils/formatters.d.ts +19 -0
  264. package/lib/typescript/module/core/utils/json.d.ts +27 -0
  265. package/lib/typescript/module/core/utils/log.d.ts +15 -0
  266. package/lib/typescript/module/core/utils/runtime.d.ts +12 -0
  267. package/lib/typescript/module/core/utils/validators.d.ts +23 -0
  268. package/lib/typescript/module/hooks.d.ts +21 -0
  269. package/lib/typescript/module/index.d.ts +26 -0
  270. package/lib/typescript/module/polyfills.d.ts +2 -0
  271. package/lib/typescript/module/presenter.d.ts +25 -0
  272. package/lib/typescript/module/provider.d.ts +22 -0
  273. package/lib/typescript/module/swichpay.d.ts +125 -0
  274. package/lib/typescript/module/theme.d.ts +52 -0
  275. package/lib/typescript/module/ui.d.ts +583 -0
  276. package/lib/typescript/module/webviews.d.ts +40 -0
  277. package/package.json +129 -4
@@ -0,0 +1,1315 @@
1
+ "use strict";
2
+
3
+ import { swichpayUserError } from '../errors.js';
4
+ import { PaymentCategory, paymentCategoryCode, paymentCategoryLabel, paymentCategoryLogoNames } from '../models/category.js';
5
+ import { maskedSavedCard, maskedSavedWallet } from '../models/session.js';
6
+ import { decodeJwtClaim } from '../utils/crypto.js';
7
+ import { digitsOnly, formatAmount, formatCountdown, formatExpiry, todayIsoDate } from '../utils/formatters.js';
8
+ import { mapOrNull } from '../utils/json.js';
9
+ import { AccountValidators, CardValidators, parseExpiry } from '../utils/validators.js';
10
+ import { FlowController } from './controller.js';
11
+ import { DiscountLookup } from './discount-lookup.js';
12
+ import { DDC_TIMEOUT_MS } from './direct-card.js';
13
+ import { resolveServices } from './services.js';
14
+ import { hasErrors, isThreeDsReturnUrl, resolveDetails } from './shared.js';
15
+
16
+ /** 10 tries x 3 s is a 30 s ceiling for `CheckCardPaymentStatus`. */
17
+ export const SHEET_STATUS_MAX_ATTEMPTS = 10;
18
+ export const SHEET_STATUS_COOLDOWN_MS = 3_000;
19
+ export const SUCCESS_SCREEN_MS = 1_400;
20
+ export const TOAST_MS = 3_000;
21
+ const MSISDN_PATTERN = /^\d{10,11}$/;
22
+ const IBAN_ERROR = 'Enter a valid IBAN (PK + 22 characters).';
23
+
24
+ /** Categories the sheet has a real form for; the rest show "isn't available yet". */
25
+ export const SHEET_SUPPORTED_CATEGORIES = new Set([PaymentCategory.visaMasterCardPayment, PaymentCategory.ewallet, PaymentCategory.rtpEwalletPayment, PaymentCategory.biller, PaymentCategory.bankAccount, PaymentCategory.dqrcPayment, PaymentCategory.sqrcPayment, PaymentCategory.rtpNowPayment]);
26
+ const EMPTY_DISCOUNT = {
27
+ loading: false,
28
+ result: null
29
+ };
30
+
31
+ /** `widget.banks` scoped to a channel hint and deduped by name; unfiltered when nothing matches. */
32
+ export function banksFor(banks, channelHint) {
33
+ const scoped = banks.filter(b => b.channelCode.toLowerCase().includes(channelHint));
34
+ const source = scoped.length > 0 ? scoped : banks;
35
+ const byName = new Map();
36
+ for (const bank of source) byName.set(bank.bankName, bank);
37
+ return [...byName.values()];
38
+ }
39
+
40
+ /**
41
+ * The built-in payment sheet:
42
+ * creates a session, then drives every category's form, the countdown, attempts, discounts,
43
+ * 3-D Secure and the exit confirmation. Resolves `null` on dismissal or startup failure.
44
+ */
45
+ export class PaymentSheetController extends FlowController {
46
+ sessionCreatedAt = 0;
47
+ countdown = null;
48
+ toastTimer = null;
49
+ cardVendorTransactionId = null;
50
+ cardOrderId = null;
51
+ started = false;
52
+ constructor(client, options) {
53
+ const details = resolveDetails(options.details);
54
+ super(PaymentSheetController.initialState(details), options.onFinish);
55
+ this.client = client;
56
+ this.services = resolveServices(options.services);
57
+ this.categoriesFilter = options.categories ?? null;
58
+ this.timing = {
59
+ ddcTimeoutMs: options.timing?.ddcTimeoutMs ?? DDC_TIMEOUT_MS,
60
+ statusMaxAttempts: options.timing?.statusMaxAttempts ?? SHEET_STATUS_MAX_ATTEMPTS,
61
+ statusCooldownMs: options.timing?.statusCooldownMs ?? SHEET_STATUS_COOLDOWN_MS,
62
+ successScreenMs: options.timing?.successScreenMs ?? SUCCESS_SCREEN_MS,
63
+ toastMs: options.timing?.toastMs ?? TOAST_MS
64
+ };
65
+ const log = client.config.log;
66
+ this.ewalletDiscount = new DiscountLookup(() => this.setState({}), log);
67
+ this.cardDiscount = new DiscountLookup(() => this.setState({}), log);
68
+ }
69
+ static initialState(details) {
70
+ return {
71
+ phase: 'loading',
72
+ startupError: null,
73
+ details,
74
+ session: null,
75
+ logos: {},
76
+ tiles: [],
77
+ expandedCategory: null,
78
+ orderInfoExpanded: true,
79
+ orderInfo: [],
80
+ amountLabel: `${details.currency} ${formatAmount(details.amount)}`,
81
+ secondsLeft: 0,
82
+ timeLeftLabel: '00:00',
83
+ timeIsLow: false,
84
+ remainingAttempts: 0,
85
+ submitting: false,
86
+ locked: false,
87
+ formError: null,
88
+ toast: null,
89
+ exitConfirmOpen: false,
90
+ declinedResult: null,
91
+ payLabel: '',
92
+ banks: {
93
+ bankAccount: [],
94
+ rtpEwallet: [],
95
+ rtpNow: []
96
+ },
97
+ card: {
98
+ number: '',
99
+ expiry: '',
100
+ cvv: '',
101
+ saveCard: false,
102
+ brand: 'unknown',
103
+ selectedSavedCardId: null,
104
+ discount: EMPTY_DISCOUNT,
105
+ verifyingCard: false,
106
+ stepUp: null,
107
+ checkingStatus: false,
108
+ statusMessage: null,
109
+ errors: {},
110
+ payLabel: ''
111
+ },
112
+ ewallet: {
113
+ selectedChannelIndex: null,
114
+ selectedSavedWalletId: null,
115
+ account: '',
116
+ discount: EMPTY_DISCOUNT,
117
+ errors: {},
118
+ payLabel: ''
119
+ },
120
+ rtpEwallet: {
121
+ selectedBankName: null,
122
+ phoneMode: true,
123
+ input: '',
124
+ errors: {}
125
+ },
126
+ bank: {
127
+ selectedBankName: null,
128
+ cnic: '',
129
+ mobile: '',
130
+ account: '',
131
+ otp: '',
132
+ otpRequired: false,
133
+ errors: {}
134
+ },
135
+ oneBill: {
136
+ mobile: '',
137
+ consumerNumber: null,
138
+ errors: {}
139
+ },
140
+ qr: {
141
+ qrString: null,
142
+ loading: false,
143
+ error: null
144
+ },
145
+ rtpNow: {
146
+ method: 'raast',
147
+ mobile: '',
148
+ iban: '',
149
+ selectedBankName: null,
150
+ account: '',
151
+ continueEnabled: false
152
+ },
153
+ submitted: {}
154
+ };
155
+ }
156
+
157
+ // ── Derived state ──────────────────────────────────────────────────────
158
+
159
+ derive(s) {
160
+ const d = s.details;
161
+ const label = amount => `MAKE PAYMENT ${d.currency} ${formatAmount(amount)}`;
162
+ const cardDiscount = this.cardDiscount?.state ?? EMPTY_DISCOUNT;
163
+ const ewalletDiscount = this.ewalletDiscount?.state ?? EMPTY_DISCOUNT;
164
+ const savedCardSelected = s.card.selectedSavedCardId != null;
165
+ const effectiveCardDiscount = savedCardSelected ? EMPTY_DISCOUNT : cardDiscount;
166
+ const fullSeconds = d.expiryMinutes * 60;
167
+ const allBanks = s.session?.banks ?? [];
168
+ const banks = {
169
+ bankAccount: banksFor(allBanks, 'bankaccount'),
170
+ rtpEwallet: banksFor(allBanks, 'rtpewalletpayment'),
171
+ rtpNow: banksFor(allBanks, 'rtpnow')
172
+ };
173
+ const rtpBank = banks.rtpNow.find(b => b.bankName === s.rtpNow.selectedBankName) ?? null;
174
+ const rtpNowContinueEnabled = s.rtpNow.method === 'raast' ? s.rtpNow.mobile.trim().length >= 10 || AccountValidators.isValidPkIban(s.rtpNow.iban) : rtpBank != null && s.rtpNow.account.trim().length >= 8;
175
+ const show = (form, errors) => s.submitted[form] ? errors : {};
176
+ return {
177
+ ...s,
178
+ amountLabel: `${d.currency} ${formatAmount(d.amount)}`,
179
+ orderInfo: [{
180
+ label: 'Date:',
181
+ value: d.date ?? todayIsoDate(new Date(this.services?.now() ?? Date.now()))
182
+ }, {
183
+ label: 'Order Number:',
184
+ value: d.orderNumber
185
+ }, {
186
+ label: 'Merchant Name:',
187
+ value: d.merchantName
188
+ }, {
189
+ label: 'Consumer Name:',
190
+ value: d.consumerName
191
+ }, {
192
+ label: 'Amount:',
193
+ value: `${d.currency} ${formatAmount(d.amount)}`
194
+ }, {
195
+ label: 'Summary:',
196
+ value: d.item
197
+ }],
198
+ timeLeftLabel: formatCountdown(s.secondsLeft),
199
+ timeIsLow: s.secondsLeft * 2 <= fullSeconds,
200
+ locked: s.submitting || s.qr.loading || s.card.checkingStatus || s.card.verifyingCard || s.card.stepUp != null,
201
+ payLabel: label(d.amount),
202
+ banks,
203
+ card: {
204
+ ...s.card,
205
+ brand: CardValidators.detectBrand(s.card.number),
206
+ discount: effectiveCardDiscount,
207
+ payLabel: label(effectiveCardDiscount.result?.finalAmount ?? d.amount),
208
+ errors: show('card', PaymentSheetController.validateCard(s))
209
+ },
210
+ ewallet: {
211
+ ...s.ewallet,
212
+ discount: ewalletDiscount,
213
+ payLabel: label(ewalletDiscount.result?.finalAmount ?? d.amount),
214
+ errors: show('ewallet', PaymentSheetController.validateEwallet(s))
215
+ },
216
+ rtpEwallet: {
217
+ ...s.rtpEwallet,
218
+ errors: show('rtpEwallet', PaymentSheetController.validateRtpEwallet(s))
219
+ },
220
+ bank: {
221
+ ...s.bank,
222
+ errors: s.bank.otpRequired ? show('bankOtp', PaymentSheetController.validateBankOtp(s)) : show('bank', PaymentSheetController.validateBank(s))
223
+ },
224
+ oneBill: {
225
+ ...s.oneBill,
226
+ errors: show('oneBill', PaymentSheetController.validateOneBill(s))
227
+ },
228
+ rtpNow: {
229
+ ...s.rtpNow,
230
+ continueEnabled: rtpNowContinueEnabled
231
+ }
232
+ };
233
+ }
234
+
235
+ // ── Validation (same copy as every SwichPay SDK) ──────────────
236
+
237
+ static validateCard(s) {
238
+ if (s.card.selectedSavedCardId != null) return {};
239
+ const errors = {};
240
+ if (!CardValidators.isValidNumber(s.card.number)) errors.number = 'Enter a valid card number';
241
+ const expiry = parseExpiry(s.card.expiry);
242
+ if (!expiry) errors.expiry = 'MM/YY';else if (!CardValidators.isValidExpiry(expiry.month, expiry.year)) errors.expiry = 'Invalid expiry';
243
+ if (!CardValidators.isValidCvv(s.card.cvv)) errors.cvv = 'Invalid CVC';
244
+ return errors;
245
+ }
246
+ static validateEwallet(s) {
247
+ const trimmed = s.ewallet.account.trim();
248
+ if (trimmed === '') return {
249
+ account: 'Enter your account number.'
250
+ };
251
+ if (s.ewallet.selectedSavedWalletId == null && !MSISDN_PATTERN.test(trimmed)) {
252
+ return {
253
+ account: 'Enter a valid account number.'
254
+ };
255
+ }
256
+ return {};
257
+ }
258
+ static validateRtpEwallet(s) {
259
+ if (!s.rtpEwallet.phoneMode) return AccountValidators.isValidPkIban(s.rtpEwallet.input) ? {} : {
260
+ input: IBAN_ERROR
261
+ };
262
+ return s.rtpEwallet.input.trim().length < 10 ? {
263
+ input: 'Enter a valid mobile number.'
264
+ } : {};
265
+ }
266
+ static validateBank(s) {
267
+ const errors = {};
268
+ if (s.bank.selectedBankName == null) errors.bank = 'Please select a bank.';
269
+ if (s.bank.cnic.length !== 13) errors.cnic = 'Enter a 13-digit CNIC.';
270
+ if (s.bank.mobile.trim() === '') errors.mobile = 'Enter your mobile number.';
271
+ if (s.bank.account.trim() === '') errors.account = 'Enter your account number.';
272
+ return errors;
273
+ }
274
+ static validateBankOtp(s) {
275
+ return s.bank.otp.trim() === '' ? {
276
+ otp: 'Enter the OTP.'
277
+ } : {};
278
+ }
279
+ static validateOneBill(s) {
280
+ return s.oneBill.mobile.trim() === '' ? {
281
+ mobile: 'Enter your mobile number.'
282
+ } : {};
283
+ }
284
+
285
+ // ── Lifecycle ──────────────────────────────────────────────────────────
286
+
287
+ /** Creates the session and loads logos in parallel; call once after creating the controller. */
288
+ async start() {
289
+ if (this.started) return;
290
+ this.started = true;
291
+ let session;
292
+ let logos;
293
+ try {
294
+ const [s, init] = await Promise.all([this.client.startNativeCheckout({
295
+ details: this.getState().details,
296
+ categories: this.categoriesFilter
297
+ }).then(value => {
298
+ this.sessionCreatedAt = this.services.now();
299
+ return value;
300
+ }), this.client.loadMobileAppInit()]);
301
+ session = s;
302
+ logos = init.logos;
303
+ } catch (error) {
304
+ if (this.disposed) return;
305
+ this.setState({
306
+ phase: 'startupError',
307
+ startupError: swichpayUserError(error)
308
+ });
309
+ return;
310
+ }
311
+ if (this.disposed) return;
312
+ const tiles = session.categories.map(category => ({
313
+ category,
314
+ label: paymentCategoryLabel(category),
315
+ logoUrls: paymentCategoryLogoNames(category).map(name => logos[name]).filter(url => typeof url === 'string'),
316
+ supported: SHEET_SUPPORTED_CATEGORIES.has(category)
317
+ }));
318
+ this.setState({
319
+ phase: 'ready',
320
+ session,
321
+ logos,
322
+ tiles,
323
+ remainingAttempts: session.remainingAttempts,
324
+ secondsLeft: this.computeSecondsLeft(session.expiryMinutes),
325
+ ewallet: {
326
+ ...this.getState().ewallet,
327
+ selectedChannelIndex: session.channels.length > 0 ? 0 : null
328
+ }
329
+ });
330
+ this.countdown = this.setIntervalTimer(() => this.tick(), 1000);
331
+ }
332
+ computeSecondsLeft(expiryMinutes) {
333
+ const elapsed = Math.floor((this.services.now() - this.sessionCreatedAt) / 1000);
334
+ return Math.max(0, expiryMinutes * 60 - elapsed);
335
+ }
336
+ tick() {
337
+ const s = this.getState();
338
+ if (s.phase !== 'ready' || !s.session) return;
339
+ const left = this.computeSecondsLeft(s.session.expiryMinutes);
340
+ if (left <= 1 || s.secondsLeft <= 1) {
341
+ this.clearIntervalTimer(this.countdown);
342
+ this.countdown = null;
343
+ this.setState({
344
+ secondsLeft: 0,
345
+ phase: 'expired',
346
+ exitConfirmOpen: false
347
+ });
348
+ return;
349
+ }
350
+ this.setState({
351
+ secondsLeft: left
352
+ });
353
+ }
354
+ onDispose() {
355
+ this.ewalletDiscount.dispose();
356
+ this.cardDiscount.dispose();
357
+ }
358
+ get session() {
359
+ const session = this.getState().session;
360
+ if (!session) throw new Error('The payment sheet has not started.');
361
+ return session;
362
+ }
363
+ categoryId(category) {
364
+ return this.session.categoryIds[category];
365
+ }
366
+
367
+ // ── Messages ───────────────────────────────────────────────────────────
368
+
369
+ showToast(message) {
370
+ this.clearTimer(this.toastTimer);
371
+ this.setState({
372
+ toast: message
373
+ });
374
+ this.toastTimer = this.setTimer(() => this.setState({
375
+ toast: null
376
+ }), this.timing.toastMs);
377
+ }
378
+ showFormError(message) {
379
+ this.setState({
380
+ formError: message
381
+ });
382
+ }
383
+ attemptsExhausted() {
384
+ if (this.getState().remainingAttempts > 0) return false;
385
+ this.showFormError('No payment attempts remaining.');
386
+ return true;
387
+ }
388
+ updateRemainingAttempts(result) {
389
+ if (result.remainingAttempts != null) this.setState({
390
+ remainingAttempts: result.remainingAttempts
391
+ });
392
+ }
393
+
394
+ // ── Navigation ─────────────────────────────────────────────────────────
395
+
396
+ toggleOrderInfo() {
397
+ this.setState(s => ({
398
+ orderInfoExpanded: !s.orderInfoExpanded
399
+ }));
400
+ }
401
+
402
+ /** Blocked while anything is in flight, so two methods never race on shared state. */
403
+ toggleCategory(category) {
404
+ const s = this.getState();
405
+ if (s.phase !== 'ready' || s.locked) return;
406
+ this.setState({
407
+ expandedCategory: s.expandedCategory === category ? null : category,
408
+ qr: {
409
+ qrString: null,
410
+ error: null,
411
+ loading: false
412
+ },
413
+ formError: null
414
+ });
415
+ this.ewalletDiscount.reset();
416
+ this.cardDiscount.reset();
417
+ }
418
+
419
+ /** The "X" / Escape / backdrop: asks "Exit checkout?" while the session is live. */
420
+ requestClose() {
421
+ const s = this.getState();
422
+ if (s.phase === 'expired' || s.phase === 'startupError') {
423
+ this.finish(null);
424
+ return;
425
+ }
426
+ if (s.phase === 'declined') {
427
+ this.finish(s.declinedResult);
428
+ return;
429
+ }
430
+ if (s.phase === 'success') return;
431
+ if (s.phase === 'loading') {
432
+ this.finish(null);
433
+ return;
434
+ }
435
+ this.setState({
436
+ exitConfirmOpen: true
437
+ });
438
+ }
439
+
440
+ /** Backdrop / Escape - same as the close button. */
441
+ dismiss() {
442
+ this.requestClose();
443
+ }
444
+
445
+ /** "Yes, Exit" cancels the session (best effort) and resolves `null`; "No, Continue" stays. */
446
+ confirmExit(exit) {
447
+ if (!exit) {
448
+ this.setState({
449
+ exitConfirmOpen: false
450
+ });
451
+ return;
452
+ }
453
+ const session = this.getState().session;
454
+ if (session) {
455
+ this.client.cancelSession({
456
+ paymentSessionGuid: session.paymentSessionGuid
457
+ }).catch(error => this.client.config.log(`cancelSession: ${String(error)}`));
458
+ }
459
+ this.setState({
460
+ exitConfirmOpen: false
461
+ });
462
+ this.finish(null);
463
+ }
464
+
465
+ /** "Return to Merchant" on the expired screen. */
466
+ returnToMerchant() {
467
+ this.finish(null);
468
+ }
469
+
470
+ /** "Close" on the declined screen. */
471
+ closeDeclined() {
472
+ this.finish(this.getState().declinedResult);
473
+ }
474
+
475
+ /** "OK" on the startup error. */
476
+ dismissStartupError() {
477
+ this.finish(null);
478
+ }
479
+
480
+ /** The tile of a category without a form: "<label> isn't available yet." */
481
+ submitUnsupported(category) {
482
+ this.showFormError(`${paymentCategoryLabel(category)} isn't available yet.`);
483
+ }
484
+ async finishSubmit(result) {
485
+ this.updateRemainingAttempts(result);
486
+ // A late result must not flip an expired session back to success.
487
+ if (this.getState().phase === 'expired') return;
488
+ if (result.isSuccess) {
489
+ this.setState({
490
+ phase: 'success',
491
+ exitConfirmOpen: false
492
+ });
493
+ await this.services.sleep(this.timing.successScreenMs);
494
+ this.finish(result);
495
+ return;
496
+ }
497
+ const s = this.getState();
498
+ if (s.card.stepUp || s.card.checkingStatus) {
499
+ this.setState({
500
+ card: {
501
+ ...s.card,
502
+ stepUp: null,
503
+ checkingStatus: false
504
+ }
505
+ });
506
+ }
507
+ if (result.remainingAttempts === 0) {
508
+ this.setState({
509
+ phase: 'declined',
510
+ declinedResult: result,
511
+ exitConfirmOpen: false
512
+ });
513
+ return;
514
+ }
515
+ this.showFormError(result.message ?? 'Payment failed.');
516
+ }
517
+
518
+ /** Runs a submit with the shared `submitting` / error handling of every submit method. */
519
+ async runSubmit(fn) {
520
+ this.setState({
521
+ submitting: true,
522
+ formError: null
523
+ });
524
+ try {
525
+ await fn();
526
+ } catch (error) {
527
+ if (!this.disposed) this.showFormError(swichpayUserError(error));
528
+ } finally {
529
+ if (this.getState().phase !== 'success') this.setState({
530
+ submitting: false
531
+ });
532
+ }
533
+ }
534
+ canSubmit() {
535
+ const s = this.getState();
536
+ return s.phase === 'ready' && !s.submitting;
537
+ }
538
+
539
+ // ── Card ───────────────────────────────────────────────────────────────
540
+
541
+ patchCard(patch) {
542
+ this.setState(s => ({
543
+ card: {
544
+ ...s.card,
545
+ ...patch
546
+ }
547
+ }));
548
+ }
549
+ setCardNumber(value) {
550
+ if (this.getState().card.selectedSavedCardId != null) return;
551
+ this.patchCard({
552
+ number: digitsOnly(value, 19)
553
+ });
554
+ this.onCardChanged();
555
+ }
556
+ setCardExpiry(value) {
557
+ if (this.getState().card.selectedSavedCardId != null) return;
558
+ this.patchCard({
559
+ expiry: formatExpiry(value)
560
+ });
561
+ this.onCardChanged();
562
+ }
563
+ setCardCvv(value) {
564
+ if (this.getState().card.selectedSavedCardId != null) return;
565
+ this.patchCard({
566
+ cvv: digitsOnly(value, 4)
567
+ });
568
+ this.onCardChanged();
569
+ }
570
+ setSaveCard(saveCard) {
571
+ this.patchCard({
572
+ saveCard
573
+ });
574
+ }
575
+
576
+ /** Tapping a saved card selects it (prefilling masked values); tapping it again clears it. */
577
+ selectSavedCard(id) {
578
+ const s = this.getState();
579
+ if (s.submitting) return;
580
+ if (s.card.selectedSavedCardId === id) {
581
+ this.clearSavedCard();
582
+ return;
583
+ }
584
+ const card = this.session.savedCards.find(c => c.id === id);
585
+ if (!card) return;
586
+ this.patchCard({
587
+ selectedSavedCardId: id,
588
+ number: card.cardNumber,
589
+ expiry: card.expiryDate
590
+ });
591
+ this.onCardChanged();
592
+ }
593
+ clearSavedCard() {
594
+ if (this.getState().submitting) return;
595
+ this.patchCard({
596
+ selectedSavedCardId: null,
597
+ number: '',
598
+ expiry: ''
599
+ });
600
+ this.onCardChanged();
601
+ }
602
+ savedCardLabel(card) {
603
+ return maskedSavedCard(card);
604
+ }
605
+
606
+ /** Discounts never run for a saved card, and only once number, expiry and CVC are all valid. */
607
+ onCardChanged() {
608
+ this.cardDiscount.reset();
609
+ const c = this.getState().card;
610
+ if (c.selectedSavedCardId != null) return;
611
+ const number = c.number.trim();
612
+ const expiry = parseExpiry(c.expiry.trim());
613
+ const cvv = c.cvv.trim();
614
+ if (!CardValidators.isValidNumber(number) || !CardValidators.isValidCvv(cvv)) return;
615
+ if (!expiry || !CardValidators.isValidExpiry(expiry.month, expiry.year)) return;
616
+ this.cardDiscount.scheduleFetch({
617
+ requestKey: `${number}|${c.expiry.trim()}|${cvv}`,
618
+ fetch: () => this.client.getCardDiscount({
619
+ details: this.getState().details,
620
+ cardNumber: number
621
+ }),
622
+ requestedAmount: this.getState().details.amount,
623
+ debugLabel: 'getCardDiscount'
624
+ });
625
+ }
626
+ isThreeDsReturnUrl = url => isThreeDsReturnUrl(url, this.getState().details);
627
+ async submitCard() {
628
+ if (!this.canSubmit()) return;
629
+ this.setState(s => ({
630
+ submitted: {
631
+ ...s.submitted,
632
+ card: true
633
+ }
634
+ }));
635
+ if (hasErrors(PaymentSheetController.validateCard(this.getState()))) return;
636
+ if (this.attemptsExhausted()) return;
637
+ const savedCardId = this.getState().card.selectedSavedCardId;
638
+ const savedCard = savedCardId == null ? null : this.session.savedCards.find(c => c.id === savedCardId) ?? null;
639
+ await this.runSubmit(() => this.attemptCardSubmit(savedCard));
640
+ }
641
+ async attemptCardSubmit(savedCard) {
642
+ const s = this.getState();
643
+ const d = s.details;
644
+ const expiry = parseExpiry(s.card.expiry);
645
+ // A saved card sends its (masked) PAN; expiry/cvv are unused.
646
+ const card = savedCard ? {
647
+ number: savedCard.cardNumber,
648
+ expMonth: 1,
649
+ expYear: 2999,
650
+ cvv: ''
651
+ } : {
652
+ number: s.card.number,
653
+ expMonth: expiry.month,
654
+ expYear: expiry.year,
655
+ cvv: s.card.cvv
656
+ };
657
+ const discount = savedCard ? null : this.cardDiscount.state.result;
658
+ const result = await this.client.processCardPayment({
659
+ paymentSessionGuid: this.session.paymentSessionGuid,
660
+ card,
661
+ // Native always forces this false for a saved card.
662
+ doCardOnFile: savedCard ? false : s.card.saveCard,
663
+ categoryId: this.categoryId(PaymentCategory.visaMasterCardPayment),
664
+ savedCardId: savedCard?.id,
665
+ isSavedCardSelected: savedCard != null,
666
+ clientId: this.session.clientId,
667
+ discountAmount: discount?.discountAmount,
668
+ finalAmount: discount?.finalAmount
669
+ });
670
+ if (this.disposed) return;
671
+ this.updateRemainingAttempts(result);
672
+ const ddcUrl = result.ddcCollectionUrl;
673
+ if (!ddcUrl) {
674
+ // Some acquirers (e.g. Meezan 3DS2) return the OTP page straight from ProcessPayment.
675
+ if (result.stepUpUrl) {
676
+ this.cardVendorTransactionId = result.vendorTransactionId ?? d.customerTransactionId;
677
+ this.cardOrderId = result.orderId;
678
+ this.patchCard({
679
+ stepUp: {
680
+ url: result.stepUpUrl,
681
+ jwt: result.redirectFormFields?.JWT ?? null
682
+ }
683
+ });
684
+ return;
685
+ }
686
+ await this.finishSubmit(result);
687
+ return;
688
+ }
689
+ this.patchCard({
690
+ verifyingCard: true
691
+ });
692
+ let completed;
693
+ try {
694
+ completed = await this.services.runDeviceDataCollection({
695
+ url: ddcUrl,
696
+ formFields: result.redirectFormFields ?? {},
697
+ timeoutMs: this.timing.ddcTimeoutMs
698
+ });
699
+ } finally {
700
+ this.patchCard({
701
+ verifyingCard: false
702
+ });
703
+ }
704
+ if (this.disposed) return;
705
+ if (!completed) {
706
+ this.showFormError('Device verification did not complete in time.');
707
+ return;
708
+ }
709
+ const jwt = result.redirectFormFields?.JWT;
710
+ const sessionId = jwt == null ? null : decodeJwtClaim(jwt, 'ReferenceId');
711
+ if (sessionId == null) {
712
+ this.showFormError('Could not determine a session ID for verification.');
713
+ return;
714
+ }
715
+ const continuation = result.continuation ?? {};
716
+ const rawPaymentSetup = mapOrNull(continuation.paymentSetup) ?? {};
717
+ const paymentSetup = savedCard ? maskedPaymentSetup(rawPaymentSetup, savedCard) : rawPaymentSetup;
718
+ const enroll = await this.client.submitPaymentEnrollment({
719
+ customerTransactionId: typeof continuation.customerTransactionId === 'string' ? continuation.customerTransactionId : d.customerTransactionId,
720
+ billReferenceNo: d.billReferenceNo,
721
+ sessionId,
722
+ paymentSetup,
723
+ doCapture: typeof continuation.doCapture === 'boolean' ? continuation.doCapture : false,
724
+ doCardOnFile: typeof continuation.doCardOnFile === 'boolean' ? continuation.doCardOnFile : false,
725
+ dynamicRedirectUrls: mapOrNull(continuation.dynamicRedirectUrls) ?? {},
726
+ vendorTransactionId: result.vendorTransactionId ?? d.customerTransactionId
727
+ });
728
+ if (this.disposed) return;
729
+ const stepUpJwt = enroll.redirectFormFields?.JWT;
730
+ if (enroll.stepUpUrl && stepUpJwt != null) {
731
+ this.cardVendorTransactionId = result.vendorTransactionId ?? d.customerTransactionId;
732
+ this.cardOrderId = enroll.orderId ?? result.orderId;
733
+ this.patchCard({
734
+ stepUp: {
735
+ url: enroll.stepUpUrl,
736
+ jwt: stepUpJwt
737
+ }
738
+ });
739
+ return;
740
+ }
741
+ await this.finishSubmit(enroll);
742
+ }
743
+
744
+ /**
745
+ * The challenge finished (message, readable return URL, or the manual button): poll
746
+ * `checkCardPaymentStatus` until success, a terminal failure, or the attempt cap.
747
+ */
748
+ async completeThreeDs(eventData = '{"type":"manual"}') {
749
+ if (!this.getState().card.stepUp) return;
750
+ this.client.config.log(`3DS challenge complete: ${eventData}`);
751
+ const tracker = this.cardVendorTransactionId;
752
+ if (!tracker) {
753
+ this.patchCard({
754
+ stepUp: null
755
+ });
756
+ this.showFormError('Could not confirm payment status.');
757
+ return;
758
+ }
759
+ this.patchCard({
760
+ stepUp: null,
761
+ checkingStatus: true,
762
+ statusMessage: 'Checking payment status...'
763
+ });
764
+ try {
765
+ let result = null;
766
+ for (let attempt = 1; attempt <= this.timing.statusMaxAttempts; attempt++) {
767
+ result = await this.client.checkCardPaymentStatus({
768
+ tracker,
769
+ orderId: this.cardOrderId
770
+ });
771
+ if (this.disposed) return;
772
+ const status = result.status.toLowerCase();
773
+ const terminalFailure = status.includes('fail') || status.includes('declin');
774
+ if (result.isSuccess || terminalFailure || attempt === this.timing.statusMaxAttempts) break;
775
+ this.patchCard({
776
+ statusMessage: result.message ?? 'Payment is pending...'
777
+ });
778
+ await this.services.sleep(this.timing.statusCooldownMs);
779
+ if (this.disposed) return;
780
+ }
781
+ this.patchCard({
782
+ checkingStatus: false
783
+ });
784
+ await this.finishSubmit(result);
785
+ } catch (error) {
786
+ if (this.disposed) return;
787
+ this.patchCard({
788
+ checkingStatus: false
789
+ });
790
+ this.showFormError(swichpayUserError(error));
791
+ }
792
+ }
793
+
794
+ // ── E-wallet ───────────────────────────────────────────────────────────
795
+
796
+ patchEwallet(patch) {
797
+ this.setState(s => ({
798
+ ewallet: {
799
+ ...s.ewallet,
800
+ ...patch
801
+ }
802
+ }));
803
+ }
804
+ get selectedChannel() {
805
+ const index = this.getState().ewallet.selectedChannelIndex;
806
+ return index == null ? null : this.getState().session?.channels[index] ?? null;
807
+ }
808
+ setEwalletAccount(value) {
809
+ if (this.getState().ewallet.selectedSavedWalletId != null) return;
810
+ this.patchEwallet({
811
+ account: digitsOnly(value, 11)
812
+ });
813
+ this.onEwalletChanged();
814
+ }
815
+ selectChannel(index) {
816
+ if (this.getState().submitting) return;
817
+ this.patchEwallet({
818
+ selectedSavedWalletId: null,
819
+ selectedChannelIndex: index
820
+ });
821
+ // The lookup is keyed off the provider too - re-evaluate on switch.
822
+ this.onEwalletChanged();
823
+ }
824
+
825
+ /** Prefills the msisdn (read-only, may be masked) and the matching channel. */
826
+ selectSavedWallet(id) {
827
+ if (this.getState().submitting) return;
828
+ const session = this.session;
829
+ const wallet = session.savedWallets.find(w => w.id === id);
830
+ if (!wallet) return;
831
+ const channelIndex = session.channels.findIndex(c => String(c.channelId) === wallet.channel);
832
+ this.patchEwallet({
833
+ selectedSavedWalletId: id,
834
+ selectedChannelIndex: channelIndex >= 0 ? channelIndex : this.getState().ewallet.selectedChannelIndex,
835
+ account: wallet.msisdn
836
+ });
837
+ this.onEwalletChanged();
838
+ }
839
+ savedWalletLabel(wallet) {
840
+ return maskedSavedWallet(wallet);
841
+ }
842
+
843
+ /** The channel a saved wallet belongs to, for its name/logo. */
844
+ channelForSavedWallet(wallet) {
845
+ return this.getState().session?.channels.find(c => String(c.channelId) === wallet.channel) ?? null;
846
+ }
847
+ onEwalletChanged() {
848
+ this.ewalletDiscount.reset();
849
+ const msisdn = this.getState().ewallet.account.trim();
850
+ const channel = this.selectedChannel;
851
+ if (!channel || !MSISDN_PATTERN.test(msisdn)) return;
852
+ this.ewalletDiscount.scheduleFetch({
853
+ requestKey: `${msisdn}|${channel.channelId}`,
854
+ fetch: () => this.client.getEwalletDiscount({
855
+ details: this.getState().details,
856
+ msisdn,
857
+ channelId: channel.channelId
858
+ }),
859
+ requestedAmount: this.getState().details.amount,
860
+ debugLabel: 'getEwalletDiscount'
861
+ });
862
+ }
863
+ async submitEwallet() {
864
+ if (!this.canSubmit()) return;
865
+ this.setState(s => ({
866
+ submitted: {
867
+ ...s.submitted,
868
+ ewallet: true
869
+ }
870
+ }));
871
+ if (hasErrors(PaymentSheetController.validateEwallet(this.getState()))) return;
872
+ if (this.attemptsExhausted()) return;
873
+ const channel = this.selectedChannel;
874
+ if (!channel) {
875
+ this.showFormError('Choose a wallet provider.');
876
+ return;
877
+ }
878
+ await this.runSubmit(async () => {
879
+ const discount = this.ewalletDiscount.state.result;
880
+ const result = await this.client.processEwalletPayment({
881
+ paymentSessionGuid: this.session.paymentSessionGuid,
882
+ channelId: channel.channelId,
883
+ categoryCode: paymentCategoryCode(PaymentCategory.ewallet),
884
+ categoryId: this.categoryId(PaymentCategory.ewallet),
885
+ ewalletType: channel.channelCode,
886
+ msisdn: this.getState().ewallet.account.trim(),
887
+ clientId: this.session.clientId,
888
+ discountAmount: discount?.discountAmount,
889
+ finalAmount: discount?.finalAmount
890
+ });
891
+ if (this.disposed) return;
892
+ await this.finishSubmit(result);
893
+ });
894
+ }
895
+
896
+ // ── RTP E-wallet ───────────────────────────────────────────────────────
897
+
898
+ patchRtpEwallet(patch) {
899
+ this.setState(s => ({
900
+ rtpEwallet: {
901
+ ...s.rtpEwallet,
902
+ ...patch
903
+ }
904
+ }));
905
+ }
906
+ selectRtpEwalletBank(name) {
907
+ if (this.getState().submitting) return;
908
+ this.patchRtpEwallet({
909
+ selectedBankName: name
910
+ });
911
+ }
912
+ setRtpEwalletPhoneMode(phoneMode) {
913
+ if (this.getState().submitting) return;
914
+ this.patchRtpEwallet({
915
+ phoneMode,
916
+ input: ''
917
+ });
918
+ }
919
+ setRtpEwalletInput(value) {
920
+ this.patchRtpEwallet({
921
+ input: value
922
+ });
923
+ }
924
+ async submitRtpEwallet() {
925
+ if (!this.canSubmit()) return;
926
+ this.setState(s => ({
927
+ submitted: {
928
+ ...s.submitted,
929
+ rtpEwallet: true
930
+ }
931
+ }));
932
+ const s = this.getState();
933
+ if (hasErrors(PaymentSheetController.validateRtpEwallet(s))) return;
934
+ if (this.attemptsExhausted()) return;
935
+ const bank = s.banks.rtpEwallet.find(b => b.bankName === s.rtpEwallet.selectedBankName);
936
+ if (!bank) {
937
+ this.showFormError('Choose your bank.');
938
+ return;
939
+ }
940
+ const phone = s.rtpEwallet.phoneMode;
941
+ const value = phone ? s.rtpEwallet.input.trim() : AccountValidators.normalizeIban(s.rtpEwallet.input);
942
+ await this.runSubmit(async () => {
943
+ const result = await this.client.processEwalletPayment({
944
+ paymentSessionGuid: this.session.paymentSessionGuid,
945
+ channelId: bank.channelId,
946
+ categoryCode: paymentCategoryCode(PaymentCategory.rtpEwalletPayment),
947
+ categoryId: this.categoryId(PaymentCategory.rtpEwalletPayment),
948
+ bankCode: bank.bankCode,
949
+ mobileNumber: value,
950
+ accountNumber: value,
951
+ accountNumberAlias: value,
952
+ msisdn: phone ? value : '',
953
+ iban: phone ? '' : value,
954
+ clientId: this.session.clientId
955
+ });
956
+ if (this.disposed) return;
957
+ await this.finishSubmit(result);
958
+ });
959
+ }
960
+
961
+ // ── Bank account ───────────────────────────────────────────────────────
962
+
963
+ patchBank(patch) {
964
+ this.setState(s => ({
965
+ bank: {
966
+ ...s.bank,
967
+ ...patch
968
+ }
969
+ }));
970
+ }
971
+ selectBank(name) {
972
+ this.patchBank({
973
+ selectedBankName: name
974
+ });
975
+ }
976
+ setBankField(field, value) {
977
+ const next = field === 'cnic' ? digitsOnly(value, 13) : field === 'otp' ? digitsOnly(value) : value;
978
+ this.patchBank({
979
+ [field]: next
980
+ });
981
+ }
982
+ selectedBank() {
983
+ const s = this.getState();
984
+ return s.banks.bankAccount.find(b => b.bankName === s.bank.selectedBankName) ?? null;
985
+ }
986
+ async submitBankAccount() {
987
+ if (!this.canSubmit()) return;
988
+ this.setState(s => ({
989
+ submitted: {
990
+ ...s.submitted,
991
+ bank: true
992
+ }
993
+ }));
994
+ if (hasErrors(PaymentSheetController.validateBank(this.getState()))) return;
995
+ if (this.attemptsExhausted()) return;
996
+ const bank = this.selectedBank();
997
+ if (!bank) {
998
+ this.showFormError('Please select a bank.');
999
+ return;
1000
+ }
1001
+ await this.runSubmit(async () => {
1002
+ const b = this.getState().bank;
1003
+ const result = await this.client.processBankAccountPayment({
1004
+ paymentSessionGuid: this.session.paymentSessionGuid,
1005
+ bankCode: bank.bankCode,
1006
+ channelId: bank.channelId,
1007
+ cnic: b.cnic,
1008
+ accountNumber: b.account,
1009
+ msisdn: b.mobile,
1010
+ categoryId: this.categoryId(PaymentCategory.bankAccount),
1011
+ clientId: this.session.clientId
1012
+ });
1013
+ if (this.disposed) return;
1014
+ if (result.otpRequired) {
1015
+ this.patchBank({
1016
+ otpRequired: true
1017
+ });
1018
+ return;
1019
+ }
1020
+ await this.finishSubmit(result);
1021
+ });
1022
+ }
1023
+ async verifyBankOtp() {
1024
+ if (!this.canSubmit()) return;
1025
+ this.setState(s => ({
1026
+ submitted: {
1027
+ ...s.submitted,
1028
+ bankOtp: true
1029
+ }
1030
+ }));
1031
+ if (hasErrors(PaymentSheetController.validateBankOtp(this.getState()))) return;
1032
+ if (this.attemptsExhausted()) return;
1033
+ const bank = this.selectedBank();
1034
+ if (!bank) {
1035
+ this.showFormError('Please select a bank.');
1036
+ return;
1037
+ }
1038
+ await this.runSubmit(async () => {
1039
+ const b = this.getState().bank;
1040
+ const result = await this.client.processBankAccountPayment({
1041
+ paymentSessionGuid: this.session.paymentSessionGuid,
1042
+ bankCode: bank.bankCode,
1043
+ channelId: bank.channelId,
1044
+ cnic: b.cnic,
1045
+ accountNumber: b.account,
1046
+ msisdn: b.mobile,
1047
+ otp: b.otp,
1048
+ categoryId: this.categoryId(PaymentCategory.bankAccount),
1049
+ clientId: this.session.clientId
1050
+ });
1051
+ if (this.disposed) return;
1052
+ await this.finishSubmit(result);
1053
+ });
1054
+ }
1055
+
1056
+ // ── 1Bill ──────────────────────────────────────────────────────────────
1057
+
1058
+ setOneBillMobile(value) {
1059
+ this.setState(s => ({
1060
+ oneBill: {
1061
+ ...s.oneBill,
1062
+ mobile: value
1063
+ }
1064
+ }));
1065
+ }
1066
+ async submitOneBill() {
1067
+ if (!this.canSubmit()) return;
1068
+ this.setState(s => ({
1069
+ submitted: {
1070
+ ...s.submitted,
1071
+ oneBill: true
1072
+ }
1073
+ }));
1074
+ if (hasErrors(PaymentSheetController.validateOneBill(this.getState()))) return;
1075
+ if (this.attemptsExhausted()) return;
1076
+ await this.runSubmit(async () => {
1077
+ const result = await this.client.processBillerPayment({
1078
+ paymentSessionGuid: this.session.paymentSessionGuid,
1079
+ msisdn: this.getState().oneBill.mobile,
1080
+ categoryId: this.categoryId(PaymentCategory.biller),
1081
+ clientId: this.session.clientId
1082
+ });
1083
+ if (this.disposed) return;
1084
+ if (result.consumerNumber) {
1085
+ this.setState(s => ({
1086
+ oneBill: {
1087
+ ...s.oneBill,
1088
+ consumerNumber: result.consumerNumber
1089
+ }
1090
+ }));
1091
+ return;
1092
+ }
1093
+ await this.finishSubmit(result);
1094
+ });
1095
+ }
1096
+
1097
+ /** "Verify Payment" - a "consumer number found" message means it's still pending. */
1098
+ async verifyOneBill() {
1099
+ if (!this.canSubmit()) return;
1100
+ if (this.attemptsExhausted()) return;
1101
+ await this.runSubmit(async () => {
1102
+ const s = this.getState();
1103
+ const result = await this.client.processBillerPayment({
1104
+ paymentSessionGuid: this.session.paymentSessionGuid,
1105
+ msisdn: s.oneBill.mobile,
1106
+ consumerNumber: s.oneBill.consumerNumber,
1107
+ categoryId: this.categoryId(PaymentCategory.biller),
1108
+ clientId: this.session.clientId
1109
+ });
1110
+ if (this.disposed) return;
1111
+ if (result.message?.toLowerCase().includes('consumer number found')) {
1112
+ this.updateRemainingAttempts(result);
1113
+ this.showFormError('Payment is still pending - tap Verify Payment again to check.');
1114
+ return;
1115
+ }
1116
+ await this.finishSubmit(result);
1117
+ });
1118
+ }
1119
+ async copyConsumerNumber() {
1120
+ const number = this.getState().oneBill.consumerNumber;
1121
+ if (!number) return;
1122
+ try {
1123
+ await this.services.copyText(number);
1124
+ this.showToast('Consumer number copied.');
1125
+ } catch {
1126
+ this.showToast('Could not copy - please copy it manually.');
1127
+ }
1128
+ }
1129
+
1130
+ // ── QR ─────────────────────────────────────────────────────────────────
1131
+
1132
+ patchQr(patch) {
1133
+ this.setState(s => ({
1134
+ qr: {
1135
+ ...s.qr,
1136
+ ...patch
1137
+ }
1138
+ }));
1139
+ }
1140
+
1141
+ /** "Generate QR Code" / "Try Again". */
1142
+ async loadQr(category) {
1143
+ const s = this.getState();
1144
+ if (s.phase !== 'ready' || s.qr.loading) return;
1145
+ if (this.attemptsExhausted()) return;
1146
+ this.patchQr({
1147
+ qrString: null,
1148
+ error: null,
1149
+ loading: true
1150
+ });
1151
+ try {
1152
+ const result = await this.client.processQrPayment({
1153
+ paymentSessionGuid: this.session.paymentSessionGuid,
1154
+ categoryCode: paymentCategoryCode(category),
1155
+ categoryId: this.categoryId(category),
1156
+ clientId: this.session.clientId
1157
+ });
1158
+ if (this.disposed) return;
1159
+ const qrString = result.qrString ? result.qrString : null;
1160
+ this.patchQr({
1161
+ loading: false,
1162
+ qrString,
1163
+ error: qrString ? null : result.message ?? 'Could not generate a QR code.'
1164
+ });
1165
+ } catch (error) {
1166
+ if (this.disposed) return;
1167
+ this.patchQr({
1168
+ loading: false,
1169
+ error: swichpayUserError(error)
1170
+ });
1171
+ }
1172
+ }
1173
+
1174
+ /** "I've Paid — Verify". */
1175
+ async verifyQr(category) {
1176
+ if (!this.canSubmit() || this.getState().qr.loading) return;
1177
+ if (this.attemptsExhausted()) return;
1178
+ await this.runSubmit(async () => {
1179
+ const result = await this.client.processQrPayment({
1180
+ paymentSessionGuid: this.session.paymentSessionGuid,
1181
+ categoryCode: paymentCategoryCode(category),
1182
+ isVerify: true,
1183
+ categoryId: this.categoryId(category),
1184
+ clientId: this.session.clientId
1185
+ });
1186
+ if (this.disposed) return;
1187
+ this.setState({
1188
+ submitting: false
1189
+ });
1190
+ await this.finishSubmit(result);
1191
+ });
1192
+ }
1193
+ async downloadQr() {
1194
+ const payload = this.getState().qr.qrString;
1195
+ if (!payload) return;
1196
+ try {
1197
+ await this.services.downloadQr(payload);
1198
+ this.showToast('QR code downloaded.');
1199
+ } catch (error) {
1200
+ this.showFormError(swichpayUserError(error, 'Could not save QR code. Please try again.'));
1201
+ }
1202
+ }
1203
+ async shareQr() {
1204
+ const payload = this.getState().qr.qrString;
1205
+ if (!payload) return;
1206
+ try {
1207
+ const outcome = await this.services.shareQr(payload);
1208
+ if (outcome === 'downloaded') this.showToast('QR code downloaded.');
1209
+ } catch (error) {
1210
+ if (error instanceof Error && error.name === 'AbortError') return;
1211
+ this.showFormError(swichpayUserError(error, 'Could not share QR code. Please try again.'));
1212
+ }
1213
+ }
1214
+
1215
+ // ── RTP Now ────────────────────────────────────────────────────────────
1216
+
1217
+ patchRtpNow(patch) {
1218
+ this.setState(s => ({
1219
+ rtpNow: {
1220
+ ...s.rtpNow,
1221
+ ...patch
1222
+ }
1223
+ }));
1224
+ }
1225
+ setRtpNowMethod(method) {
1226
+ this.patchRtpNow({
1227
+ method
1228
+ });
1229
+ }
1230
+ setRtpNowField(field, value) {
1231
+ this.patchRtpNow({
1232
+ [field]: value
1233
+ });
1234
+ }
1235
+ selectRtpNowBank(name) {
1236
+ this.patchRtpNow({
1237
+ selectedBankName: name
1238
+ });
1239
+ }
1240
+
1241
+ /** Sends only the fields of the selected receive method. */
1242
+ async submitRtpNow() {
1243
+ if (!this.canSubmit()) return;
1244
+ if (this.attemptsExhausted()) return;
1245
+ const s = this.getState();
1246
+ const session = this.session;
1247
+ if (s.rtpNow.method === 'raast') {
1248
+ const mobileNumber = s.rtpNow.mobile.trim();
1249
+ const iban = AccountValidators.normalizeIban(s.rtpNow.iban);
1250
+ if (mobileNumber === '' && iban === '') {
1251
+ this.showFormError('Enter either a Mobile Number or an IBAN.');
1252
+ return;
1253
+ }
1254
+ if (iban !== '' && !AccountValidators.isValidPkIban(iban)) {
1255
+ this.showFormError(IBAN_ERROR);
1256
+ return;
1257
+ }
1258
+ const primary = mobileNumber === '' ? iban : mobileNumber;
1259
+ await this.runSubmit(async () => {
1260
+ const result = await this.client.processRtpNowPayment({
1261
+ paymentSessionGuid: session.paymentSessionGuid,
1262
+ mobileNumber: mobileNumber === '' ? null : mobileNumber,
1263
+ iban: iban === '' ? null : iban,
1264
+ accountNumber: primary,
1265
+ accountNumberAlias: primary,
1266
+ categoryId: this.categoryId(PaymentCategory.rtpNowPayment),
1267
+ clientId: session.clientId
1268
+ });
1269
+ if (this.disposed) return;
1270
+ await this.finishSubmit(result);
1271
+ });
1272
+ return;
1273
+ }
1274
+ const bank = s.banks.rtpNow.find(b => b.bankName === s.rtpNow.selectedBankName);
1275
+ const accountNumber = s.rtpNow.account.trim();
1276
+ if (!bank) {
1277
+ this.showFormError('Please select a bank.');
1278
+ return;
1279
+ }
1280
+ if (accountNumber === '') {
1281
+ this.showFormError('Enter your account number.');
1282
+ return;
1283
+ }
1284
+ await this.runSubmit(async () => {
1285
+ const result = await this.client.processRtpNowPayment({
1286
+ paymentSessionGuid: session.paymentSessionGuid,
1287
+ bankCode: bank.bankCode,
1288
+ channelId: bank.channelId,
1289
+ accountNumber,
1290
+ categoryId: this.categoryId(PaymentCategory.rtpNowPayment),
1291
+ clientId: session.clientId
1292
+ });
1293
+ if (this.disposed) return;
1294
+ await this.finishSubmit(result);
1295
+ });
1296
+ }
1297
+ }
1298
+
1299
+ /**
1300
+ * Fills `payload.{cardNumber,cvc,year,month}` with masked placeholders where the backend left them
1301
+ * null for a saved card - PaymentEnrollment 400s on an incomplete payload.
1302
+ */
1303
+ export function maskedPaymentSetup(paymentSetup, savedCard) {
1304
+ const payload = {
1305
+ ...(mapOrNull(paymentSetup.payload) ?? {})
1306
+ };
1307
+ payload.cardNumber ??= savedCard.cardNumber;
1308
+ payload.cvc ??= '***';
1309
+ payload.year ??= '***';
1310
+ payload.month ??= '***';
1311
+ return {
1312
+ ...paymentSetup,
1313
+ payload
1314
+ };
1315
+ }