@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,31 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.defaultFlowServices = void 0;
7
+ exports.resolveServices = resolveServices;
8
+ var _clipboard = require("../browser/clipboard.js");
9
+ var _threeDs = require("../browser/three-ds.js");
10
+ var _qr = require("../browser/qr.js");
11
+ var _crypto = require("../utils/crypto.js");
12
+ /**
13
+ * Side effects the checkout controllers need. The defaults use browser APIs, touched only when
14
+ * called (never at import), so controllers are SSR-safe. Tests pass fakes.
15
+ */
16
+
17
+ const defaultFlowServices = exports.defaultFlowServices = {
18
+ runDeviceDataCollection: _threeDs.runDeviceDataCollection,
19
+ copyText: _clipboard.copyText,
20
+ downloadQr: payload => (0, _qr.downloadQrCode)(payload),
21
+ shareQr: payload => (0, _qr.shareQrCode)(payload),
22
+ uuid: _crypto.generateUuidV4,
23
+ sleep: ms => new Promise(resolve => setTimeout(resolve, ms)),
24
+ now: () => Date.now()
25
+ };
26
+ function resolveServices(overrides) {
27
+ return {
28
+ ...defaultFlowServices,
29
+ ...overrides
30
+ };
31
+ }
@@ -0,0 +1,90 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.SUPPORT_PHONE = exports.RETRY_BLOCKED_MESSAGE = exports.PENDING_APPROVAL_TITLE = void 0;
7
+ exports.directPayLabel = directPayLabel;
8
+ exports.formatDateDMY = formatDateDMY;
9
+ exports.hasErrors = hasErrors;
10
+ exports.isThreeDsReturnUrl = isThreeDsReturnUrl;
11
+ exports.pwaHeaderCells = pwaHeaderCells;
12
+ exports.pwaPayLabel = pwaPayLabel;
13
+ exports.resolveDetails = resolveDetails;
14
+ exports.visibleErrors = visibleErrors;
15
+ var _payment = require("../models/payment.js");
16
+ var _formatters = require("../utils/formatters.js");
17
+ function visibleErrors(all, meta) {
18
+ const out = {};
19
+ for (const key of Object.keys(all)) {
20
+ if (meta.submitted || meta.touched[key]) out[key] = all[key];
21
+ }
22
+ return out;
23
+ }
24
+ function hasErrors(errors) {
25
+ return Object.values(errors).some(e => e != null);
26
+ }
27
+
28
+ /** Common options for every checkout controller. */
29
+
30
+ function resolveDetails(details) {
31
+ return (0, _payment.resolvePaymentDetails)(details);
32
+ }
33
+
34
+ /** The direct sheets' pay button: `MAKE PAYMENT PKR 1000` (amount rounded to a whole number). */
35
+ function directPayLabel(details) {
36
+ return `MAKE PAYMENT ${details.currency} ${(0, _formatters.formatAmountWhole)(details.amount)}`;
37
+ }
38
+
39
+ /**
40
+ * Redirect-based 3-D Secure challenges (no `postMessage`) finish by navigating back to SwichPay /
41
+ * JazzCash, to Meezan's `/3ds2/challenge/` page, or to the merchant's redirect URLs.
42
+ */
43
+ function isThreeDsReturnUrl(url, details) {
44
+ const host = url.hostname.toLowerCase();
45
+ if (host.endsWith('swichnow.com') || host.endsWith('jazzcash.com.pk')) return true;
46
+ if (url.pathname.includes('/3ds2/challenge/')) return true;
47
+ const asString = url.href;
48
+ return [details.successRedirectUrl, details.failedRedirectUrl].some(prefix => prefix !== '' && asString.startsWith(prefix));
49
+ }
50
+ const PENDING_APPROVAL_TITLE = exports.PENDING_APPROVAL_TITLE = 'Payment Initiated';
51
+ const RETRY_BLOCKED_MESSAGE = exports.RETRY_BLOCKED_MESSAGE = 'To try again, close this and start a new payment.';
52
+ const SUPPORT_PHONE = exports.SUPPORT_PHONE = '+92 319 1234567';
53
+
54
+ /** Visual style of the built-in checkouts: `default` (payment sheet) or `classic` (SwichPay payment page). */
55
+
56
+ /** `dd-MM-yyyy`, as the PWA payment page shows dates. */
57
+ function formatDateDMY(isoDate, now = new Date()) {
58
+ const match = /^(\d{4})-(\d{2})-(\d{2})/.exec(isoDate ?? '');
59
+ if (match) return `${match[3]}-${match[2]}-${match[1]}`;
60
+ const two = n => String(n).padStart(2, '0');
61
+ return `${two(now.getDate())}-${two(now.getMonth() + 1)}-${now.getFullYear()}`;
62
+ }
63
+
64
+ /** The six fields of the PWA page header, in its order (Swich.CardPayment HostedCheckOut.cshtml). */
65
+ function pwaHeaderCells(details) {
66
+ return [{
67
+ label: 'Merchant Name',
68
+ value: details.merchantName
69
+ }, {
70
+ label: 'Consumer Name',
71
+ value: details.consumerName
72
+ }, {
73
+ label: 'Date',
74
+ value: formatDateDMY(details.date)
75
+ }, {
76
+ label: 'Order Number',
77
+ value: details.orderNumber
78
+ }, {
79
+ label: 'Amount',
80
+ value: `${details.currency} ${(0, _formatters.formatAmount)(details.amount)}`
81
+ }, {
82
+ label: 'Summary',
83
+ value: details.description || details.item
84
+ }];
85
+ }
86
+
87
+ /** The PWA's pay button text: `Make Payment PKR 10`. */
88
+ function pwaPayLabel(currency, amount) {
89
+ return `Make Payment ${currency} ${(0, _formatters.formatAmount)(amount)}`;
90
+ }
@@ -0,0 +1,208 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.ApiClient = void 0;
7
+ exports.fetchClientCredentialsToken = fetchClientCredentialsToken;
8
+ var _errors = require("../errors.js");
9
+ var _endpoints = require("./endpoints.js");
10
+ var _tokenManager = require("./token-manager.js");
11
+ var _transport = require("./transport.js");
12
+ /** OAuth2 `client_credentials` exchange. */
13
+ async function fetchClientCredentialsToken(input) {
14
+ const log = input.log ?? (() => {});
15
+ log(`Fetching OAuth access token for ${input.clientId}`);
16
+ const response = await (0, _transport.sendRequest)(input.fetch, {
17
+ method: 'POST',
18
+ url: `${input.authHost}${_endpoints.Endpoints.token}`,
19
+ form: {
20
+ grant_type: 'client_credentials',
21
+ client_id: input.clientId,
22
+ client_secret: input.clientSecret
23
+ },
24
+ timeoutMs: input.timeoutMs ?? 3 * 60 * 1000
25
+ }, log);
26
+ const token = response.json.access_token;
27
+ if (typeof token !== 'string' || token === '') {
28
+ throw new _errors.SwichPayApiException('Token endpoint response had no access_token.', {
29
+ statusCode: response.status
30
+ });
31
+ }
32
+ const expiresIn = typeof response.json.expires_in === 'number' ? Math.trunc(response.json.expires_in) : 3600;
33
+ log(`Obtained access token, expires in ${expiresIn}s`);
34
+ return {
35
+ accessToken: token,
36
+ expiresIn
37
+ };
38
+ }
39
+ /**
40
+ * Thin wrapper around the SwichPay hosts: picks the host and headers per
41
+ * call, authenticates per the configured auth mode, and replays once with a fresh token on 401.
42
+ */
43
+ class ApiClient {
44
+ constructor(config) {
45
+ this.config = config;
46
+ this.tokens = ApiClient.createTokenManager(config);
47
+ }
48
+ static createTokenManager(config) {
49
+ if (config.authMode === 'token-provider' && config.getAccessToken) {
50
+ const provider = config.getAccessToken;
51
+ return new _tokenManager.TokenManager(async () => {
52
+ let token;
53
+ try {
54
+ token = await provider();
55
+ } catch (error) {
56
+ if ((0, _errors.isSwichPayException)(error)) throw error;
57
+ throw new _errors.SwichPayApiException(`getAccessToken() failed: ${String(error)}`, {
58
+ statusCode: 401
59
+ });
60
+ }
61
+ const normalized = typeof token === 'string' ? {
62
+ accessToken: token
63
+ } : token;
64
+ if (!normalized || typeof normalized.accessToken !== 'string' || normalized.accessToken === '') {
65
+ throw new _errors.SwichPayApiException('getAccessToken() returned no access token.', {
66
+ statusCode: 401
67
+ });
68
+ }
69
+ return normalized;
70
+ });
71
+ }
72
+ if (config.authMode === 'client-secret' && config.clientSecret) {
73
+ const clientSecret = config.clientSecret;
74
+ return new _tokenManager.TokenManager(() => fetchClientCredentialsToken({
75
+ fetch: config.fetch,
76
+ authHost: config.hosts.auth,
77
+ clientId: config.clientId,
78
+ clientSecret,
79
+ timeoutMs: config.timeouts.request,
80
+ log: config.log
81
+ }));
82
+ }
83
+ return null;
84
+ }
85
+
86
+ /** `Authorization: Bearer` when a token source exists, `x-public-key` otherwise, nothing via a proxy. */
87
+ async authHeaders() {
88
+ if (this.config.authMode === 'proxy') return {};
89
+ if (this.tokens) return {
90
+ Authorization: `Bearer ${await this.tokens.getToken()}`
91
+ };
92
+ return {
93
+ 'x-public-key': this.config.clientId
94
+ };
95
+ }
96
+ async gatewayHeaders() {
97
+ return {
98
+ 'Content-Type': 'application/json',
99
+ // The `gateway/payin/...` endpoints misbehave without it.
100
+ referrer: this.config.appId,
101
+ ...(await this.authHeaders())
102
+ };
103
+ }
104
+ requireHost(host, feature) {
105
+ if (host) return host;
106
+ throw new _errors.SwichPayValidationException(`${feature} is not available in ${this.config.environment} yet.`);
107
+ }
108
+ async request(req, isAuthRetry = false) {
109
+ const httpRequest = {
110
+ method: req.method,
111
+ url: `${req.baseUrl}${req.path}`,
112
+ query: req.query,
113
+ headers: req.headers,
114
+ json: req.json,
115
+ timeoutMs: req.timeoutMs ?? this.config.timeouts.request,
116
+ referrer: this.config.referrer
117
+ };
118
+ try {
119
+ return (await (0, _transport.sendRequest)(this.config.fetch, httpRequest, this.config.log)).json;
120
+ } catch (error) {
121
+ // A cached token the server no longer accepts would otherwise fail every call until its
122
+ // local expiry: drop it and replay once with a fresh one. Safe for POSTs too - a 401 is
123
+ // rejected before the request is processed.
124
+ if (error instanceof _errors.SwichPayApiException && error.statusCode === 401 && !isAuthRetry && this.tokens && 'Authorization' in req.headers) {
125
+ this.config.log('401 with a cached token - refreshing it and retrying once');
126
+ this.tokens.invalidate();
127
+ const fresh = await this.tokens.getToken();
128
+ return this.request({
129
+ ...req,
130
+ headers: {
131
+ ...req.headers,
132
+ Authorization: `Bearer ${fresh}`
133
+ }
134
+ }, true);
135
+ }
136
+ throw error;
137
+ }
138
+ }
139
+
140
+ /** Checkout host. `extraHeaders` carries the per-endpoint public-key header. */
141
+ async post(path, body, extraHeaders = {}) {
142
+ return this.request({
143
+ method: 'POST',
144
+ baseUrl: this.config.hosts.checkout,
145
+ path,
146
+ json: body,
147
+ headers: {
148
+ 'Content-Type': 'application/json',
149
+ Referer: this.config.referrer,
150
+ ...extraHeaders
151
+ }
152
+ });
153
+ }
154
+
155
+ /** Gateway host GET. */
156
+ async get(path, query = {}) {
157
+ return this.request({
158
+ method: 'GET',
159
+ baseUrl: this.config.hosts.gateway,
160
+ path,
161
+ query,
162
+ headers: {
163
+ Accept: 'application/json',
164
+ ...(await this.gatewayHeaders())
165
+ }
166
+ });
167
+ }
168
+
169
+ /** Gateway host POST. */
170
+ async postToGateway(path, body) {
171
+ return this.request({
172
+ method: 'POST',
173
+ baseUrl: this.config.hosts.gateway,
174
+ path,
175
+ json: body,
176
+ headers: await this.gatewayHeaders()
177
+ });
178
+ }
179
+
180
+ /** Payment API host (direct card flow). */
181
+ async postToPaymentApi(path, body) {
182
+ const baseUrl = this.requireHost(this.config.hosts.paymentApi, 'Direct card payment');
183
+ return this.request({
184
+ method: 'POST',
185
+ baseUrl,
186
+ path,
187
+ json: body,
188
+ headers: await this.gatewayHeaders()
189
+ });
190
+ }
191
+
192
+ /** Discount host; short timeout since it runs while the user types. */
193
+ async postToDiscount(path, body) {
194
+ const baseUrl = this.requireHost(this.config.hosts.discount, 'Discount lookup');
195
+ return this.request({
196
+ method: 'POST',
197
+ baseUrl,
198
+ path,
199
+ json: body,
200
+ headers: {
201
+ 'Content-Type': 'application/json',
202
+ ...(await this.authHeaders())
203
+ },
204
+ timeoutMs: this.config.timeouts.discount
205
+ });
206
+ }
207
+ }
208
+ exports.ApiClient = ApiClient;
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.SERVICE_ENDPOINTS = exports.PROXY_SEGMENTS = exports.Endpoints = void 0;
7
+ /** Every SwichPay API endpoint path the SDK calls. */
8
+ const Endpoints = exports.Endpoints = {
9
+ // ── Checkout host ──
10
+ /** Validates the client id / referrer pair. */
11
+ init: '/init',
12
+ /** `SwichPay.pay` card payment. */
13
+ iframePayment: '/iframe/Payment',
14
+ // ── Auth host ──
15
+ token: '/connect/token',
16
+ // ── Gateway host ──
17
+ mobileAppInit: '/gateway/paymentsession/mobileappinit',
18
+ createPaymentSession: '/gateway/paymentsession/initiate',
19
+ processPayment: '/gateway/PaymentSession/ProcessPayment',
20
+ paymentEnrollment: '/gateway/PaymentSession/PaymentEnrollment',
21
+ checkCardPaymentStatus: '/gateway/PaymentSession/CheckCardPaymentStatus',
22
+ inquirePaymentSession: '/gateway/paymentsession/inquire',
23
+ getPaymentSession: '/gateway/paymentsession/get',
24
+ cancelPaymentSession: '/gateway/paymentsession/cancel',
25
+ directEwallet: '/gateway/payin/purchase/ewallet',
26
+ directBankOtp: '/gateway/payin/bank/otp',
27
+ directBankConfirm: '/gateway/payin/bank/transfer',
28
+ directBankList: '/gateway/payin/get/banks',
29
+ directRtpNowBanks: '/gateway/payin/rtp/now/get/banks',
30
+ directRtpEwalletBanks: '/gateway/payin/get/walletbanks',
31
+ /** RTP Now *and* RTP E-wallet (same path, different body). */
32
+ directRtpPurchase: '/gateway/payin/v2.0/purchase/rtp/now',
33
+ directQrGenerate: '/gateway/payin/purchase/qr/dynamic',
34
+ directQrInquire: '/gateway/payin/purchase/qr/dynamic/inquire',
35
+ directBiller: '/gateway/payin/purchase/biller',
36
+ directBillerInquire: '/gateway/payin/inquire',
37
+ // ── Payment API host (direct card) ──
38
+ directCardPayment: '/api/Payment/PaymentV3',
39
+ /** Not `/api/Payment/TokenizedPaymentV3` (404s - verified against SwichPay's swagger). */
40
+ directCardTokenizedPayment: '/api/Payment/v3/CompleteTokenPayment',
41
+ directCardInquire: '/api/Payment/InquireV3',
42
+ // ── Discount host ──
43
+ getDiscount: '/api/Discount/GetDiscount'
44
+ };
45
+ /** Which endpoints live on which host - also the server proxy's allowlist. */
46
+ const SERVICE_ENDPOINTS = exports.SERVICE_ENDPOINTS = {
47
+ checkout: [Endpoints.init, Endpoints.iframePayment],
48
+ auth: [Endpoints.token],
49
+ gateway: [Endpoints.mobileAppInit, Endpoints.createPaymentSession, Endpoints.processPayment, Endpoints.paymentEnrollment, Endpoints.checkCardPaymentStatus, Endpoints.inquirePaymentSession, Endpoints.getPaymentSession, Endpoints.cancelPaymentSession, Endpoints.directEwallet, Endpoints.directBankOtp, Endpoints.directBankConfirm, Endpoints.directBankList, Endpoints.directRtpNowBanks, Endpoints.directRtpEwalletBanks, Endpoints.directRtpPurchase, Endpoints.directQrGenerate, Endpoints.directQrInquire, Endpoints.directBiller, Endpoints.directBillerInquire],
50
+ paymentApi: [Endpoints.directCardPayment, Endpoints.directCardTokenizedPayment, Endpoints.directCardInquire],
51
+ discount: [Endpoints.getDiscount]
52
+ };
53
+
54
+ /** URL path segment used by `proxyUrl` for each service. */
55
+ const PROXY_SEGMENTS = exports.PROXY_SEGMENTS = {
56
+ checkout: 'checkout',
57
+ gateway: 'gateway',
58
+ auth: 'auth',
59
+ paymentApi: 'payment-api',
60
+ discount: 'discount'
61
+ };
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.TokenManager = exports.TOKEN_EXPIRY_BUFFER_MS = void 0;
7
+ /** Refresh this long before the real expiry, so a request never starts on a dying token. */
8
+ const TOKEN_EXPIRY_BUFFER_MS = exports.TOKEN_EXPIRY_BUFFER_MS = 60_000;
9
+
10
+ /**
11
+ * Caches a bearer token until shortly before it expires and shares one in-flight fetch between
12
+ * concurrent callers. Used by the client and the proxy.
13
+ */
14
+ class TokenManager {
15
+ cached = null;
16
+ expiresAt = 0;
17
+ inFlight = null;
18
+ constructor(fetchToken, now = Date.now) {
19
+ this.fetchToken = fetchToken;
20
+ this.now = now;
21
+ }
22
+ async getToken() {
23
+ if (this.cached != null && this.now() < this.expiresAt) return this.cached;
24
+ if (this.inFlight) return this.inFlight;
25
+ const fetch = (async () => {
26
+ const token = await this.fetchToken();
27
+ const expiresIn = typeof token.expiresIn === 'number' && Number.isFinite(token.expiresIn) ? token.expiresIn : 3600;
28
+ this.cached = token.accessToken;
29
+ this.expiresAt = this.now() + expiresIn * 1000 - TOKEN_EXPIRY_BUFFER_MS;
30
+ return token.accessToken;
31
+ })();
32
+ this.inFlight = fetch;
33
+ try {
34
+ return await fetch;
35
+ } finally {
36
+ this.inFlight = null;
37
+ }
38
+ }
39
+
40
+ /** Drops the cached token (a 401 means the server no longer accepts it). */
41
+ invalidate() {
42
+ this.cached = null;
43
+ this.expiresAt = 0;
44
+ }
45
+ }
46
+ exports.TokenManager = TokenManager;
@@ -0,0 +1,134 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.MAX_GET_RETRIES = void 0;
7
+ exports.apiErrorMessage = apiErrorMessage;
8
+ exports.apiExceptionFrom = apiExceptionFrom;
9
+ exports.buildUrl = buildUrl;
10
+ exports.sendRequest = sendRequest;
11
+ var _errors = require("../errors.js");
12
+ var _log = require("../utils/log.js");
13
+ var _json = require("../utils/json.js");
14
+ var _runtime = require("../utils/runtime.js");
15
+ /** GET retries after the first attempt, on connection errors / 5xx only. */
16
+ const MAX_GET_RETRIES = exports.MAX_GET_RETRIES = 2;
17
+ function buildUrl(url, query) {
18
+ if (!query || Object.keys(query).length === 0) return url;
19
+ const qs = new URLSearchParams(query).toString();
20
+ return `${url}${url.includes('?') ? '&' : '?'}${qs}`;
21
+ }
22
+
23
+ /**
24
+ * Picks the error message: `message`, then ASP.NET
25
+ * `errors` (field-level detail), then `title`, then a generic default.
26
+ */
27
+ function apiErrorMessage(json) {
28
+ const message = json.message;
29
+ if (typeof message === 'string' && message !== '') return message;
30
+ const errors = json.errors;
31
+ if ((0, _json.isJsonMap)(errors) && Object.keys(errors).length > 0) {
32
+ return Object.entries(errors).map(([key, value]) => `${key}: ${Array.isArray(value) ? value.map(v => (0, _json.str)(v) ?? 'null').join(' ') : (0, _json.str)(value) ?? 'null'}`).join(' ');
33
+ }
34
+ const title = json.title;
35
+ if (typeof title === 'string' && title !== '') return title;
36
+ return 'SwichPay API error';
37
+ }
38
+ function apiExceptionFrom(status, json) {
39
+ return new _errors.SwichPayApiException(apiErrorMessage(json), {
40
+ statusCode: status,
41
+ // `code` isn't reliably a string - some endpoints return a raw JSON number.
42
+ code: (0, _json.str)(json.code),
43
+ serverMessage: (0, _json.nonBlankString)(json.message),
44
+ serverStatus: (0, _json.str)(json.status),
45
+ orderId: (0, _json.nonBlankString)(json.orderId)
46
+ });
47
+ }
48
+ function sameOriginReferrer(referrer) {
49
+ if (!referrer || !(0, _runtime.isBrowser)()) return undefined;
50
+ try {
51
+ const url = new URL(referrer, window.location.href);
52
+ return url.origin === window.location.origin ? url.href : undefined;
53
+ } catch {
54
+ return undefined;
55
+ }
56
+ }
57
+ class TimeoutError extends Error {}
58
+ async function sendOnce(fetchImpl, request, url) {
59
+ const controller = new AbortController();
60
+ const timer = setTimeout(() => controller.abort(new TimeoutError('timeout')), request.timeoutMs);
61
+ const headers = {
62
+ ...request.headers
63
+ };
64
+ let body;
65
+ if (request.json !== undefined) {
66
+ body = JSON.stringify(request.json);
67
+ } else if (request.form !== undefined) {
68
+ body = new URLSearchParams(request.form).toString();
69
+ headers['Content-Type'] = 'application/x-www-form-urlencoded';
70
+ }
71
+ try {
72
+ const init = {
73
+ method: request.method,
74
+ headers,
75
+ body,
76
+ signal: controller.signal
77
+ };
78
+ const referrer = sameOriginReferrer(request.referrer);
79
+ if (referrer) {
80
+ init.referrer = referrer;
81
+ init.referrerPolicy = 'unsafe-url';
82
+ }
83
+ const response = await fetchImpl(url, init);
84
+ const text = await response.text();
85
+ return {
86
+ status: response.status,
87
+ text
88
+ };
89
+ } catch (error) {
90
+ if (controller.signal.aborted) throw new TimeoutError('timeout');
91
+ throw error;
92
+ } finally {
93
+ clearTimeout(timer);
94
+ }
95
+ }
96
+
97
+ /**
98
+ * Sends one HTTP request: bounded GET-only retry on
99
+ * connection errors and 5xx, every non-2xx mapped to `SwichPayApiException`, every transport
100
+ * failure mapped to `SwichPayNetworkException`, and lenient JSON parsing.
101
+ */
102
+ async function sendRequest(fetchImpl, request, log) {
103
+ const url = buildUrl(request.url, request.query);
104
+ log(`${request.method} ${url} headers=${(0, _log.safeJson)((0, _log.redactHeaders)(request.headers ?? {}))} data=${(0, _log.safeJson)((0, _log.redactForLog)(request.json ?? null))}`);
105
+ const maxAttempts = request.method === 'GET' ? 1 + MAX_GET_RETRIES : 1;
106
+ let lastError;
107
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
108
+ let result;
109
+ try {
110
+ result = await sendOnce(fetchImpl, request, url);
111
+ } catch (error) {
112
+ const timedOut = error instanceof TimeoutError;
113
+ lastError = new _errors.SwichPayNetworkException(`Failed to reach SwichPay API at ${url} (${timedOut ? 'timeout' : 'connectionError'})`, {
114
+ cause: error
115
+ });
116
+ // A receive timeout isn't retried; a connection error is.
117
+ if (!timedOut && attempt < maxAttempts) continue;
118
+ throw lastError;
119
+ }
120
+ const json = (0, _json.parseJsonObject)(result.text);
121
+ if (result.status >= 200 && result.status < 300) {
122
+ log(`response ${result.status}: ${(0, _log.safeJson)((0, _log.redactForLog)(json))}`);
123
+ return {
124
+ status: result.status,
125
+ json
126
+ };
127
+ }
128
+ log(`error response ${result.status} ${url}: ${Object.keys(json).length === 0 ? result.text : (0, _log.safeJson)((0, _log.redactForLog)(json))}`);
129
+ lastError = apiExceptionFrom(result.status, json);
130
+ if (result.status >= 500 && attempt < maxAttempts) continue;
131
+ throw lastError;
132
+ }
133
+ throw lastError;
134
+ }