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