@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,128 @@
1
+ "use strict";
2
+
3
+ import { ENVIRONMENT_HOSTS, isEnvironment } from './environment.js';
4
+ import { SwichPayValidationException } from './errors.js';
5
+ import { createLog } from './utils/log.js';
6
+ import { isClientRuntime } from './utils/runtime.js';
7
+
8
+ /** An access token returned by a merchant-hosted token endpoint. */
9
+
10
+ /**
11
+ * Options for `SwichPay.initialize()` / `new SwichPayClient()`.
12
+ *
13
+ * The first six are the standard SwichPay merchant settings. The rest are optional,
14
+ * because a browser can't keep a secret and SwichPay's hosts don't send CORS headers to
15
+ * arbitrary origins - see docs/authentication.md.
16
+ */
17
+
18
+ export const DEFAULT_TIMEOUTS = {
19
+ request: 3 * 60 * 1000,
20
+ discount: 10 * 1000
21
+ };
22
+ function requireString(value, name, {
23
+ nonEmpty = false
24
+ } = {}) {
25
+ if (typeof value !== 'string' || nonEmpty && value.trim() === '') {
26
+ throw new SwichPayValidationException(`SwichPay option "${name}" must be a${nonEmpty ? ' non-empty' : ''} string.`);
27
+ }
28
+ return value;
29
+ }
30
+ function nonEmptyOrNull(value) {
31
+ return value != null && value !== '' ? value : null;
32
+ }
33
+ function trimSlash(url) {
34
+ return url.replace(/\/+$/, '');
35
+ }
36
+
37
+ /** Validates options and resolves hosts, auth mode and defaults. */
38
+ export function resolveConfig(options) {
39
+ if (options == null || typeof options !== 'object') {
40
+ throw new SwichPayValidationException('SwichPay options are required.');
41
+ }
42
+ const clientId = requireString(options.clientId, 'clientId', {
43
+ nonEmpty: true
44
+ });
45
+ const referrer = requireString(options.referrer, 'referrer');
46
+ const appId = requireString(options.appId, 'appId');
47
+ if (typeof options.merchantId !== 'number' || !Number.isInteger(options.merchantId)) {
48
+ throw new SwichPayValidationException('SwichPay option "merchantId" must be an integer.');
49
+ }
50
+ if (!isEnvironment(options.environment)) {
51
+ throw new SwichPayValidationException('SwichPay option "environment" must be "sandbox" or "production".');
52
+ }
53
+ const environment = options.environment;
54
+ const clientSecret = nonEmptyOrNull(options.clientSecret);
55
+ const secretHashKey = nonEmptyOrNull(options.secretHashKey);
56
+ if ((clientSecret || secretHashKey) && isClientRuntime() && !options.dangerouslyAllowBrowserSecrets) {
57
+ throw new SwichPayValidationException('clientSecret/secretHashKey were passed in an app or browser, where anyone can extract them from the bundle. ' + 'Use proxyUrl (see createSwichPayProxy in @swichpay/react-native/server) or getAccessToken/getChecksum ' + 'instead, or set dangerouslyAllowBrowserSecrets: true for local testing only.');
58
+ }
59
+ const base = ENVIRONMENT_HOSTS[environment];
60
+ let hosts = {
61
+ ...base
62
+ };
63
+ const proxyUrl = nonEmptyOrNull(options.proxyUrl);
64
+ if (proxyUrl) {
65
+ const p = trimSlash(proxyUrl);
66
+ hosts = {
67
+ checkout: `${p}/checkout`,
68
+ gateway: `${p}/gateway`,
69
+ auth: `${p}/auth`,
70
+ discount: base.discount ? `${p}/discount` : null,
71
+ paymentApi: base.paymentApi ? `${p}/payment-api` : null
72
+ };
73
+ }
74
+ if (options.hosts) {
75
+ const {
76
+ checkout,
77
+ gateway,
78
+ auth,
79
+ discount,
80
+ paymentApi
81
+ } = options.hosts;
82
+ if (checkout) hosts.checkout = trimSlash(checkout);
83
+ if (gateway) hosts.gateway = trimSlash(gateway);
84
+ if (auth) hosts.auth = trimSlash(auth);
85
+ if (discount !== undefined) hosts.discount = discount === null ? null : trimSlash(discount);
86
+ if (paymentApi !== undefined) hosts.paymentApi = paymentApi === null ? null : trimSlash(paymentApi);
87
+ }
88
+ const baseUrlOverride = nonEmptyOrNull(options.baseUrlOverride);
89
+ if (baseUrlOverride) hosts.checkout = trimSlash(baseUrlOverride);
90
+
91
+ // Production traffic carries card data and bearer tokens: never over plain HTTP. Sandbox may use
92
+ // http:// for a local backend (emulator 10.0.2.2, a LAN IP).
93
+ if (environment === 'production') {
94
+ for (const [name, host] of Object.entries(hosts)) {
95
+ if (host != null && !host.toLowerCase().startsWith('https://')) {
96
+ throw new SwichPayValidationException(`SwichPay host "${name}" (${host}) must use https:// in production. Check proxyUrl / hosts / baseUrlOverride.`);
97
+ }
98
+ }
99
+ }
100
+ const authMode = proxyUrl ? 'proxy' : options.getAccessToken ? 'token-provider' : clientSecret ? 'client-secret' : 'public-key';
101
+ const log = createLog(options.logger);
102
+ if (clientSecret && secretHashKey && clientSecret === secretHashKey) {
103
+ log('clientSecret and secretHashKey are the same value - the token endpoint rejects this (invalid_client).');
104
+ }
105
+ const fetchImpl = options.fetch ?? (typeof globalThis.fetch === 'function' ? globalThis.fetch.bind(globalThis) : undefined);
106
+ if (!fetchImpl) {
107
+ throw new SwichPayValidationException('No fetch implementation available - pass options.fetch.');
108
+ }
109
+ return Object.freeze({
110
+ clientId,
111
+ referrer,
112
+ merchantId: options.merchantId,
113
+ appId,
114
+ environment,
115
+ hosts: Object.freeze(hosts),
116
+ clientSecret,
117
+ secretHashKey,
118
+ authMode,
119
+ getAccessToken: options.getAccessToken ?? null,
120
+ getChecksum: options.getChecksum ?? null,
121
+ fetch: fetchImpl,
122
+ log,
123
+ timeouts: Object.freeze({
124
+ ...DEFAULT_TIMEOUTS,
125
+ ...options.timeouts
126
+ })
127
+ });
128
+ }
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+
3
+ /** The backend environment a SwichPay client talks to. */
4
+
5
+ export const Environment = {
6
+ sandbox: 'sandbox',
7
+ production: 'production'
8
+ };
9
+ /** SwichPay hosts per environment. */
10
+ export const ENVIRONMENT_HOSTS = {
11
+ sandbox: {
12
+ checkout: 'https://testcheckout.swichnow.com',
13
+ gateway: 'https://sandbox-api.swichnow.com',
14
+ auth: 'https://sandbox-auth.swichnow.com',
15
+ discount: 'https://sandbox-api-discount.swichnow.com',
16
+ paymentApi: 'https://sandbox-paymentapi.swichnow.com'
17
+ },
18
+ production: {
19
+ checkout: 'https://checkout.swichnow.com',
20
+ gateway: 'https://api.swichnow.com',
21
+ auth: 'https://auth.swichnow.com',
22
+ // No production host exists yet - calls fail fast instead of sending live data to sandbox.
23
+ discount: null,
24
+ paymentApi: null
25
+ }
26
+ };
27
+ export function isEnvironment(value) {
28
+ return value === 'sandbox' || value === 'production';
29
+ }
@@ -0,0 +1,125 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * Error hierarchy - every SDK error is a `SwichPayException`.
5
+ * Every SDK call rejects with one of these instead of a raw fetch/parse error.
6
+ */
7
+
8
+ export class SwichPayException extends Error {
9
+ /** Discriminator, handy where `instanceof` is awkward (e.g. across bundles). */
10
+
11
+ constructor(message) {
12
+ super(message);
13
+ this.name = new.target.name;
14
+ }
15
+
16
+ /**
17
+ * Short, non-technical text safe to show to the paying user. `message` is technical detail
18
+ * (URLs, HTTP codes, field names) - log it, never show it.
19
+ */
20
+
21
+ toString() {
22
+ return `${this.name}: ${this.message}`;
23
+ }
24
+ }
25
+
26
+ /** Thrown when a method is called before `SwichPay.initialize()`. */
27
+ export class SwichPayNotInitializedException extends SwichPayException {
28
+ kind = 'not_initialized';
29
+ constructor() {
30
+ super('SwichPay.initialize() must be called before use.');
31
+ }
32
+ get userMessage() {
33
+ return 'Payments are not available right now. Please try again later.';
34
+ }
35
+ }
36
+
37
+ /** Thrown for malformed input (bad card number, missing fields, etc.) before any network call. */
38
+ export class SwichPayValidationException extends SwichPayException {
39
+ kind = 'validation';
40
+ get userMessage() {
41
+ return this.message;
42
+ }
43
+ }
44
+
45
+ /** Thrown when the SDK fails to reach the SwichPay API. */
46
+ export class SwichPayNetworkException extends SwichPayException {
47
+ kind = 'network';
48
+ constructor(message, options = {}) {
49
+ super(message);
50
+ this.cause = options.cause;
51
+ }
52
+ get userMessage() {
53
+ return 'Unable to connect. Please check your internet connection and try again.';
54
+ }
55
+ toString() {
56
+ return this.cause == null ? super.toString() : `${super.toString()} Caused by: ${String(this.cause)}`;
57
+ }
58
+ }
59
+ /** Thrown when the SwichPay API returns an error response. */
60
+ export class SwichPayApiException extends SwichPayException {
61
+ kind = 'api';
62
+
63
+ /** The response body's own `message` (e.g. "Invalid OTP."), when the server sent one. */
64
+
65
+ /**
66
+ * The response body's own `status` (e.g. `"failed"`, `"pending"`) - a 4xx isn't always a
67
+ * decline: direct card payments answer a vendor-side pending with HTTP 400 + `"pending"`.
68
+ */
69
+
70
+ /** The response body's `orderId`, when the server created an order before erroring. */
71
+
72
+ constructor(message, init) {
73
+ super(message);
74
+ this.statusCode = init.statusCode;
75
+ this.code = init.code ?? null;
76
+ this.serverMessage = init.serverMessage ?? null;
77
+ this.serverStatus = init.serverStatus ?? null;
78
+ this.orderId = init.orderId ?? null;
79
+ }
80
+ get isPending() {
81
+ return this.serverStatus?.toLowerCase() === 'pending';
82
+ }
83
+ get userMessage() {
84
+ const status = this.statusCode;
85
+ if (status === 404) {
86
+ return 'This payment method is currently unavailable. Please try another method or try again later.';
87
+ }
88
+ if (status === 401 || status === 403) {
89
+ return 'This payment could not be authorized. Please contact the merchant.';
90
+ }
91
+ if (status === 408 || status === 429 || status >= 500) {
92
+ return 'The payment service is temporarily unavailable. Please try again in a few minutes.';
93
+ }
94
+ return this.serverMessage ?? 'Something went wrong while processing your payment. Please try again.';
95
+ }
96
+ toString() {
97
+ return `${super.toString()} (HTTP ${this.statusCode}${this.code == null ? '' : `, code ${this.code}`})`;
98
+ }
99
+ }
100
+ export function isSwichPayException(error) {
101
+ return error instanceof SwichPayException;
102
+ }
103
+
104
+ /** `userMessage` for SwichPay errors, a generic fallback for anything else. */
105
+ export function swichpayUserMessage(error) {
106
+ return isSwichPayException(error) ? error.userMessage : 'Something went wrong. Please try again.';
107
+ }
108
+
109
+ /**
110
+ * User-facing text for `error`; `fallback` replaces the generic text for errors that aren't a
111
+ * `SwichPayException`.
112
+ */
113
+ export function swichpayUserError(error, fallback) {
114
+ if (fallback != null && !isSwichPayException(error)) return fallback;
115
+ return swichpayUserMessage(error);
116
+ }
117
+
118
+ /**
119
+ * Whether a failed attempt reached the gateway - and so used up the checkout's
120
+ * `customerTransactionId`, which the gateway refuses to see twice. Only a request that never
121
+ * left the device (network) or never got built (validation) is safe to resend.
122
+ */
123
+ export function attemptUsedTransactionId(error) {
124
+ return !(error instanceof SwichPayNetworkException) && !(error instanceof SwichPayValidationException);
125
+ }
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+
3
+ /** Returned by `onResult`: call it (or `.cancel()`) to stop listening. */
4
+
5
+ export function createSubscription(off) {
6
+ let active = true;
7
+ const stop = () => {
8
+ if (!active) return;
9
+ active = false;
10
+ off();
11
+ };
12
+ return Object.assign(stop, {
13
+ cancel: stop
14
+ });
15
+ }
16
+
17
+ /**
18
+ * Minimal broadcast emitter. Like a Dart broadcast `StreamController`, events are delivered
19
+ * asynchronously (next microtask), and a throwing listener never affects the others.
20
+ */
21
+ export class Emitter {
22
+ listeners = new Set();
23
+ closed = false;
24
+ get listenerCount() {
25
+ return this.listeners.size;
26
+ }
27
+ on(listener) {
28
+ if (typeof listener !== 'function') throw new TypeError('listener must be a function');
29
+ const wrapped = value => listener(value);
30
+ this.listeners.add(wrapped);
31
+ return createSubscription(() => this.listeners.delete(wrapped));
32
+ }
33
+ emit(value) {
34
+ if (this.closed || this.listeners.size === 0) return;
35
+ const snapshot = [...this.listeners];
36
+ queueMicrotask(() => {
37
+ for (const listener of snapshot) {
38
+ if (!this.listeners.has(listener)) continue;
39
+ try {
40
+ listener(value);
41
+ } catch {
42
+ // Isolated: a broken listener must not break payment flows or other listeners.
43
+ }
44
+ }
45
+ });
46
+ }
47
+ close() {
48
+ this.closed = true;
49
+ this.listeners.clear();
50
+ }
51
+ }
@@ -0,0 +1,101 @@
1
+ "use strict";
2
+
3
+ /** Called once when a checkout finishes; `null` means dismissed without a result. */
4
+
5
+ /**
6
+ * Base for the headless checkout controllers. Holds immutable state (a new object per change, so
7
+ * React's `useSyncExternalStore` and Vue's `shallowRef` can both track it), tracked timers, and
8
+ * a disposed flag that is checked after every `await`.
9
+ */
10
+ export class FlowController {
11
+ listeners = new Set();
12
+ timers = new Set();
13
+ intervals = new Set();
14
+ finished = false;
15
+ _disposed = false;
16
+ constructor(initial, onFinish) {
17
+ this.onFinish = onFinish;
18
+ this.state = initial;
19
+ }
20
+ getState = () => this.state;
21
+ subscribe = listener => {
22
+ this.listeners.add(listener);
23
+ return () => {
24
+ this.listeners.delete(listener);
25
+ };
26
+ };
27
+ get disposed() {
28
+ return this._disposed;
29
+ }
30
+ get isFinished() {
31
+ return this.finished;
32
+ }
33
+ setState(patch) {
34
+ if (this._disposed) return;
35
+ const next = typeof patch === 'function' ? patch(this.state) : patch;
36
+ this.state = this.derive({
37
+ ...this.state,
38
+ ...next
39
+ });
40
+ for (const listener of [...this.listeners]) listener();
41
+ }
42
+
43
+ /** Recomputes derived fields; override to keep labels/flags in sync with the inputs. */
44
+ derive(state) {
45
+ return state;
46
+ }
47
+
48
+ /** Resolves the checkout once; later calls are ignored. */
49
+ finish(result) {
50
+ if (this.finished || this._disposed) return;
51
+ this.finished = true;
52
+ this.onFinish?.(result);
53
+ }
54
+
55
+ /**
56
+ * Backdrop / Escape. Dismissing this way resolves `null`;
57
+ * the payment sheet and the busy card checkout override it.
58
+ */
59
+ dismiss() {
60
+ this.finish(null);
61
+ }
62
+ setTimer(fn, ms) {
63
+ const id = setTimeout(() => {
64
+ this.timers.delete(id);
65
+ if (!this._disposed) fn();
66
+ }, ms);
67
+ this.timers.add(id);
68
+ return id;
69
+ }
70
+ clearTimer(id) {
71
+ if (id == null) return;
72
+ clearTimeout(id);
73
+ this.timers.delete(id);
74
+ }
75
+ setIntervalTimer(fn, ms) {
76
+ const id = setInterval(() => {
77
+ if (this._disposed) return;
78
+ fn();
79
+ }, ms);
80
+ this.intervals.add(id);
81
+ return id;
82
+ }
83
+ clearIntervalTimer(id) {
84
+ if (id == null) return;
85
+ clearInterval(id);
86
+ this.intervals.delete(id);
87
+ }
88
+
89
+ /** Cancels every timer and stops all further state changes. Safe to call twice. */
90
+ dispose() {
91
+ if (this._disposed) return;
92
+ this._disposed = true;
93
+ for (const id of this.timers) clearTimeout(id);
94
+ for (const id of this.intervals) clearInterval(id);
95
+ this.timers.clear();
96
+ this.intervals.clear();
97
+ this.listeners.clear();
98
+ this.onDispose();
99
+ }
100
+ onDispose() {}
101
+ }
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+
3
+ import { formatCountdown } from '../utils/formatters.js';
4
+ import { FlowController } from './controller.js';
5
+ /** A display-only countdown (the PWA page's timer box). Call `start()`; `dispose()` stops it. */
6
+ export class CountdownController extends FlowController {
7
+ timer = null;
8
+ constructor(minutes) {
9
+ const seconds = Math.max(0, Math.round(minutes * 60));
10
+ super({
11
+ secondsLeft: seconds,
12
+ label: formatCountdown(seconds),
13
+ done: seconds === 0
14
+ });
15
+ }
16
+ derive(state) {
17
+ return {
18
+ ...state,
19
+ label: formatCountdown(state.secondsLeft),
20
+ done: state.secondsLeft <= 0
21
+ };
22
+ }
23
+ start() {
24
+ if (this.timer || this.getState().done) return;
25
+ this.timer = this.setIntervalTimer(() => {
26
+ const left = this.getState().secondsLeft - 1;
27
+ this.setState({
28
+ secondsLeft: Math.max(0, left)
29
+ });
30
+ if (left <= 0) {
31
+ this.clearIntervalTimer(this.timer);
32
+ this.timer = null;
33
+ }
34
+ }, 1000);
35
+ }
36
+ }
@@ -0,0 +1,231 @@
1
+ "use strict";
2
+
3
+ import { attemptUsedTransactionId, swichpayUserError } from '../errors.js';
4
+ import { cancelledResult, failedResult } from '../models/payment.js';
5
+ import { digitsOnly } from '../utils/formatters.js';
6
+ import { FlowController } from './controller.js';
7
+ import { directPayLabel, hasErrors, resolveDetails, visibleErrors } from './shared.js';
8
+ export const OTP_RESEND_SECONDS = 60;
9
+ /** Direct bank transfer with OTP confirmation. */
10
+ export class DirectBankTransferController extends FlowController {
11
+ resendTimer = null;
12
+ constructor(client, options) {
13
+ const details = resolveDetails(options.details);
14
+ super({
15
+ details,
16
+ banks: [],
17
+ loadingBanks: true,
18
+ selectedBankCode: null,
19
+ account: '',
20
+ otp: '',
21
+ submitting: false,
22
+ error: null,
23
+ errors: {},
24
+ meta: {
25
+ touched: {},
26
+ submitted: false
27
+ },
28
+ otpChallenge: null,
29
+ resendSecondsLeft: OTP_RESEND_SECONDS,
30
+ usedUpFailure: null,
31
+ payLabel: directPayLabel(details)
32
+ }, options.onFinish);
33
+ this.client = client;
34
+ }
35
+ static validate(s) {
36
+ const errors = {};
37
+ if (s.otpChallenge) {
38
+ if (s.otp.trim().length !== 6) errors.otp = 'Enter the 6-digit OTP.';
39
+ return errors;
40
+ }
41
+ if (s.selectedBankCode == null) errors.bank = 'Choose your bank';
42
+ if (s.account.trim() === '') errors.account = 'Enter your account number.';
43
+ return errors;
44
+ }
45
+ derive(state) {
46
+ return {
47
+ ...state,
48
+ errors: visibleErrors(DirectBankTransferController.validate(state), state.meta)
49
+ };
50
+ }
51
+ async start() {
52
+ try {
53
+ const banks = await this.client.fetchDirectBankList();
54
+ this.setState({
55
+ banks,
56
+ loadingBanks: false
57
+ });
58
+ } catch (error) {
59
+ this.setState({
60
+ error: swichpayUserError(error),
61
+ loadingBanks: false
62
+ });
63
+ }
64
+ }
65
+ touch(field) {
66
+ const meta = this.getState().meta;
67
+ return {
68
+ ...meta,
69
+ touched: {
70
+ ...meta.touched,
71
+ [field]: true
72
+ }
73
+ };
74
+ }
75
+ selectBank(code) {
76
+ if (this.getState().submitting) return;
77
+ this.setState({
78
+ selectedBankCode: code,
79
+ meta: this.touch('bank')
80
+ });
81
+ }
82
+ setAccount(value) {
83
+ this.setState({
84
+ account: value,
85
+ meta: this.touch('account')
86
+ });
87
+ }
88
+ setOtp(value) {
89
+ this.setState({
90
+ otp: digitsOnly(value, 6),
91
+ meta: this.touch('otp')
92
+ });
93
+ }
94
+ startResendCountdown() {
95
+ this.clearIntervalTimer(this.resendTimer);
96
+ this.setState({
97
+ resendSecondsLeft: OTP_RESEND_SECONDS
98
+ });
99
+ this.resendTimer = this.setIntervalTimer(() => {
100
+ const left = this.getState().resendSecondsLeft;
101
+ if (left <= 1) {
102
+ this.clearIntervalTimer(this.resendTimer);
103
+ this.resendTimer = null;
104
+ this.setState({
105
+ resendSecondsLeft: 0
106
+ });
107
+ return;
108
+ }
109
+ this.setState({
110
+ resendSecondsLeft: left - 1
111
+ });
112
+ }, 1000);
113
+ }
114
+ get canResendOtp() {
115
+ const s = this.getState();
116
+ return s.otpChallenge != null && s.resendSecondsLeft === 0 && !s.submitting;
117
+ }
118
+
119
+ /** Step 1 (MAKE PAYMENT), also used by Resend OTP with the already-validated input. */
120
+ async requestOtp() {
121
+ const s = this.getState();
122
+ if (s.submitting) return;
123
+ const onForm = s.otpChallenge == null;
124
+ if (onForm) {
125
+ if (s.usedUpFailure) return;
126
+ this.setState({
127
+ meta: {
128
+ ...s.meta,
129
+ submitted: true
130
+ }
131
+ });
132
+ if (hasErrors(DirectBankTransferController.validate(s))) return;
133
+ }
134
+ const bank = s.banks.find(b => b.code === s.selectedBankCode);
135
+ if (!bank) return;
136
+ this.setState({
137
+ submitting: true,
138
+ error: null
139
+ });
140
+ try {
141
+ const result = await this.client.directBankTransfer({
142
+ details: s.details,
143
+ bankCode: bank.code,
144
+ accountNo: s.account.trim()
145
+ });
146
+ if (this.disposed) return;
147
+ if (result.otpRequired) {
148
+ this.setState({
149
+ otpChallenge: result,
150
+ meta: {
151
+ touched: {},
152
+ submitted: false
153
+ }
154
+ });
155
+ this.startResendCountdown();
156
+ } else if (result.isSuccess) {
157
+ this.finish(result);
158
+ } else {
159
+ this.setState({
160
+ error: result.message ?? 'Bank transfer failed.',
161
+ usedUpFailure: this.getState().otpChallenge == null ? result : this.getState().usedUpFailure
162
+ });
163
+ }
164
+ } catch (error) {
165
+ if (this.disposed) return;
166
+ const message = swichpayUserError(error);
167
+ const used = this.getState().otpChallenge == null && attemptUsedTransactionId(error);
168
+ this.setState({
169
+ error: message,
170
+ usedUpFailure: used ? failedResult(message) : this.getState().usedUpFailure
171
+ });
172
+ } finally {
173
+ this.setState({
174
+ submitting: false
175
+ });
176
+ }
177
+ }
178
+ resendOtp() {
179
+ if (!this.canResendOtp) return Promise.resolve();
180
+ return this.requestOtp();
181
+ }
182
+
183
+ /** Step 2 (CONFIRM). A wrong OTP can be retried. */
184
+ async confirmOtp() {
185
+ const s = this.getState();
186
+ const challenge = s.otpChallenge;
187
+ if (!challenge || s.submitting) return;
188
+ this.setState({
189
+ meta: {
190
+ ...s.meta,
191
+ submitted: true
192
+ }
193
+ });
194
+ if (hasErrors(DirectBankTransferController.validate(s))) return;
195
+ this.setState({
196
+ submitting: true,
197
+ error: null
198
+ });
199
+ try {
200
+ const result = await this.client.confirmDirectBankTransfer({
201
+ customerTransactionId: s.details.customerTransactionId,
202
+ billReferenceNo: s.details.billReferenceNo,
203
+ transactionId: challenge.bankTransactionId ?? '',
204
+ orderId: challenge.orderId ?? '',
205
+ transactionReferenceNo: challenge.transactionReferenceNo ?? '',
206
+ retreivalReferenceNo: challenge.retreivalReferenceNo ?? '',
207
+ otp: s.otp.trim()
208
+ });
209
+ if (this.disposed) return;
210
+ if (result.isSuccess) this.finish(result);else this.setState({
211
+ error: result.message ?? 'Invalid OTP.'
212
+ });
213
+ } catch (error) {
214
+ if (this.disposed) return;
215
+ this.setState({
216
+ error: swichpayUserError(error)
217
+ });
218
+ } finally {
219
+ this.setState({
220
+ submitting: false
221
+ });
222
+ }
223
+ }
224
+ closeWithFailure() {
225
+ const failure = this.getState().usedUpFailure;
226
+ if (failure) this.finish(failure);
227
+ }
228
+ cancel() {
229
+ this.finish(cancelledResult());
230
+ }
231
+ }