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