@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,194 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.createSwichPayProxy = createSwichPayProxy;
7
+ var _config = require("../config.js");
8
+ var _errors = require("../errors.js");
9
+ var _apiClient = require("../http/api-client.js");
10
+ var _endpoints = require("../http/endpoints.js");
11
+ var _tokenManager = require("../http/token-manager.js");
12
+ var _crypto = require("../utils/crypto.js");
13
+ var _json = require("../utils/json.js");
14
+ /** `(request, path)` → response. `path` is what follows the proxy's mount point, e.g. `/gateway/gateway/paymentsession/get`. */
15
+
16
+ /** Request headers forwarded from the browser; everything else (cookies, auth) is dropped. */
17
+ const FORWARDED_HEADERS = ['content-type', 'accept', 'x-public-key', 'publickey'];
18
+ const SEGMENT_TO_SERVICE = new Map(Object.entries(_endpoints.PROXY_SEGMENTS).map(([service, segment]) => [segment, service]));
19
+ function json(status, body) {
20
+ return new Response(JSON.stringify(body), {
21
+ status,
22
+ headers: {
23
+ 'content-type': 'application/json'
24
+ }
25
+ });
26
+ }
27
+
28
+ /**
29
+ * A server-side proxy for the web SDK's `proxyUrl` mode. It forwards only SwichPay's own
30
+ * endpoint paths to the configured environment and adds what a browser can't safely send: the
31
+ * OAuth bearer token (from `clientSecret`), the `Referer`/`referrer` headers and, for direct card
32
+ * payments, the `recievedCheckSum` signed with `secretHashKey`.
33
+ */
34
+ function createSwichPayProxy(options) {
35
+ const config = (0, _config.resolveConfig)({
36
+ ...options,
37
+ proxyUrl: undefined,
38
+ getAccessToken: undefined,
39
+ getChecksum: undefined
40
+ });
41
+ if (!options.authorize && !options.dangerouslyAllowUnauthenticated) {
42
+ throw new _errors.SwichPayValidationException('createSwichPayProxy needs `authorize` (check your user session) - or dangerouslyAllowUnauthenticated: true for local testing only.');
43
+ }
44
+ if (config.secretHashKey && !options.verifyAmount && !options.dangerouslySignAnyAmount) {
45
+ throw new _errors.SwichPayValidationException('createSwichPayProxy with secretHashKey needs `verifyAmount` (check the amount against your order) - ' + 'or dangerouslySignAnyAmount: true for local testing only.');
46
+ }
47
+ if (config.environment === 'production' && (options.dangerouslyAllowUnauthenticated || options.dangerouslySignAnyAmount)) {
48
+ config.log('proxy: WARNING - a dangerously* option is set in production.');
49
+ }
50
+ const tokens = config.clientSecret ? new _tokenManager.TokenManager(() => (0, _apiClient.fetchClientCredentialsToken)({
51
+ fetch: config.fetch,
52
+ authHost: config.hosts.auth,
53
+ clientId: config.clientId,
54
+ clientSecret: config.clientSecret,
55
+ timeoutMs: config.timeouts.request,
56
+ log: config.log
57
+ })) : null;
58
+ const hostFor = service => config.hosts[service];
59
+ return async function swichPayProxy(request, path) {
60
+ const method = request.method.toUpperCase();
61
+ if (method !== 'GET' && method !== 'POST') return json(405, {
62
+ message: 'Method not allowed.'
63
+ });
64
+ const clean = `/${path.replace(/^\/+/, '')}`;
65
+ const slash = clean.indexOf('/', 1);
66
+ const segment = slash === -1 ? clean.slice(1) : clean.slice(1, slash);
67
+ const endpoint = slash === -1 ? '' : clean.slice(slash);
68
+ const service = SEGMENT_TO_SERVICE.get(segment);
69
+ if (!service || service === 'auth' || !_endpoints.SERVICE_ENDPOINTS[service].includes(endpoint)) {
70
+ return json(404, {
71
+ message: 'Not a SwichPay endpoint.'
72
+ });
73
+ }
74
+ const host = hostFor(service);
75
+ if (!host) return json(404, {
76
+ message: `This endpoint is not available in ${config.environment} yet.`
77
+ });
78
+ if (options.authorize) {
79
+ const rejected = await options.authorize(request);
80
+ if (rejected instanceof Response) return rejected;
81
+ }
82
+ const headers = {};
83
+ for (const name of FORWARDED_HEADERS) {
84
+ const value = request.headers.get(name);
85
+ if (value != null) headers[name] = value;
86
+ }
87
+ if (service === 'checkout') headers.Referer = config.referrer;
88
+ if (service === 'gateway' || service === 'paymentApi') headers.referrer = config.appId;
89
+ let body;
90
+ if (method === 'POST') {
91
+ body = await request.text();
92
+ if (service === 'paymentApi' && endpoint === _endpoints.Endpoints.directCardPayment && config.secretHashKey) {
93
+ const signed = await signDirectCardBody(body, config.secretHashKey, payment => options.verifyAmount ? options.verifyAmount(payment, request) : true);
94
+ if (signed == null) {
95
+ config.log('proxy: verifyAmount rejected a direct card payment');
96
+ return json(400, {
97
+ message: 'Payment amount does not match the order.',
98
+ status: 'failed'
99
+ });
100
+ }
101
+ body = signed;
102
+ }
103
+ }
104
+ const search = new URL(request.url).search;
105
+ const upstreamUrl = `${host}${endpoint}${search}`;
106
+ const needsAuth = service !== 'checkout';
107
+ const send = async fresh => {
108
+ const h = {
109
+ ...headers
110
+ };
111
+ if (needsAuth) {
112
+ if (tokens) {
113
+ if (fresh) tokens.invalidate();
114
+ h.Authorization = `Bearer ${await tokens.getToken()}`;
115
+ } else {
116
+ h['x-public-key'] = config.clientId;
117
+ }
118
+ }
119
+ const controller = new AbortController();
120
+ const timer = setTimeout(() => controller.abort(), service === 'discount' ? config.timeouts.discount : config.timeouts.request);
121
+ try {
122
+ return await config.fetch(upstreamUrl, {
123
+ method,
124
+ headers: h,
125
+ body,
126
+ signal: controller.signal
127
+ });
128
+ } finally {
129
+ clearTimeout(timer);
130
+ }
131
+ };
132
+ let upstream;
133
+ try {
134
+ upstream = await send(false);
135
+ if (upstream.status === 401 && needsAuth && tokens) {
136
+ config.log('proxy: 401 with a cached token - refreshing it and retrying once');
137
+ upstream = await send(true);
138
+ }
139
+ } catch (error) {
140
+ config.log(`proxy: ${upstreamUrl} failed: ${String(error)}`);
141
+ if ((0, _errors.isSwichPayException)(error)) {
142
+ // The token exchange failed - an authorization problem (401), never leak the secret.
143
+ return json(401, {
144
+ message: 'SwichPay authentication failed.',
145
+ status: 'failed'
146
+ });
147
+ }
148
+ return json(502, {
149
+ message: 'Failed to reach SwichPay API.',
150
+ status: 'failed'
151
+ });
152
+ }
153
+ const text = await upstream.text();
154
+ return new Response(text, {
155
+ status: upstream.status,
156
+ headers: {
157
+ 'content-type': upstream.headers.get('content-type') ?? 'application/json'
158
+ }
159
+ });
160
+ };
161
+ }
162
+
163
+ /**
164
+ * Sets `recievedCheckSum` from the body's own currency/amount/customerTransactionId once `verify`
165
+ * approves them. `null` = rejected. A body without those fields is forwarded unsigned (SwichPay
166
+ * refuses it).
167
+ */
168
+ async function signDirectCardBody(body, secretHashKey, verify) {
169
+ let parsed;
170
+ try {
171
+ parsed = JSON.parse(body);
172
+ } catch {
173
+ return body;
174
+ }
175
+ if (!(0, _json.isJsonMap)(parsed)) return body;
176
+ const {
177
+ currency,
178
+ amount,
179
+ customerTransactionId
180
+ } = parsed;
181
+ if (typeof currency !== 'string' || typeof amount !== 'number' || typeof customerTransactionId !== 'string') return body;
182
+ if ((await verify({
183
+ currency,
184
+ amount,
185
+ customerTransactionId
186
+ })) !== true) return null;
187
+ parsed.recievedCheckSum = await (0, _crypto.generateTransactionCheckSum)({
188
+ currency,
189
+ amount,
190
+ customerTransactionId,
191
+ secretHashKey
192
+ });
193
+ return JSON.stringify(parsed);
194
+ }
@@ -0,0 +1,122 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.classifyInquiry = classifyInquiry;
7
+ exports.createCheckoutSessionCreator = createCheckoutSessionCreator;
8
+ exports.createPaymentVerifier = createPaymentVerifier;
9
+ exports.evaluateInquiry = evaluateInquiry;
10
+ exports.lazyServerClient = lazyServerClient;
11
+ var _client = require("../client.js");
12
+ var _errors = require("../errors.js");
13
+ /** What to do with the order: fulfil (`success`), cancel (`failed`) or wait and re-check (`pending`). */
14
+
15
+ /** Statuses SwichPay reports for a payment that will not complete. Anything else unpaid is `pending`. */
16
+ const FINAL_FAILURE = new Set(['failed', 'failure', 'fail', 'declined', 'rejected', 'cancelled', 'canceled', 'expired', 'error', 'reversed']);
17
+
18
+ /**
19
+ * Maps an inquiry to an order decision. Conservative on purpose: unknown statuses are `pending`,
20
+ * so an order is never fulfilled without a confirmed success and never cancelled without a
21
+ * confirmed failure.
22
+ */
23
+ function classifyInquiry(inquiry) {
24
+ if (inquiry.isSuccess) return 'success';
25
+ const status = (inquiry.status ?? '').trim().toLowerCase();
26
+ return FINAL_FAILURE.has(status) ? 'failed' : 'pending';
27
+ }
28
+ function evaluateInquiry(inquiry, input) {
29
+ const status = classifyInquiry(inquiry);
30
+ if (status === 'failed') return {
31
+ status,
32
+ verified: false,
33
+ reason: 'declined',
34
+ inquiry
35
+ };
36
+ if (status === 'pending') return {
37
+ status,
38
+ verified: false,
39
+ reason: 'not_final',
40
+ inquiry
41
+ };
42
+ if (input.expectedAmount !== undefined && Math.abs(inquiry.amount - input.expectedAmount) > 0.005) {
43
+ return {
44
+ status: 'failed',
45
+ verified: false,
46
+ reason: 'amount_mismatch',
47
+ inquiry
48
+ };
49
+ }
50
+ if (input.expectedOrderId !== undefined && inquiry.orderId != null && inquiry.orderId !== input.expectedOrderId) {
51
+ return {
52
+ status: 'failed',
53
+ verified: false,
54
+ reason: 'order_mismatch',
55
+ inquiry
56
+ };
57
+ }
58
+ return {
59
+ status: 'success',
60
+ verified: true,
61
+ reason: null,
62
+ inquiry
63
+ };
64
+ }
65
+
66
+ /** Options for a server-side client, or a function that returns them (read lazily, on first use). */
67
+
68
+ /** A lazily created, server-side `SwichPayClient` authenticated with `clientSecret`. */
69
+ function lazyServerClient(source, purpose) {
70
+ let client = null;
71
+ return () => {
72
+ if (!client) {
73
+ const options = typeof source === 'function' ? source() : source;
74
+ if (!options.clientSecret) {
75
+ throw new _errors.SwichPayValidationException(`${purpose} needs clientSecret (server-side only).`);
76
+ }
77
+ client = new _client.SwichPayClient(options);
78
+ }
79
+ return client;
80
+ };
81
+ }
82
+
83
+ /**
84
+ * Server-side transaction verification with SwichPay's existing inquire API. Call it where the
85
+ * customer returns (`successRedirectUrl` / `failedRedirectUrl`) and fulfil the order only when
86
+ * `verified` is `true`. Never trust the redirect alone: anyone can open that URL.
87
+ *
88
+ * Network and authentication errors are thrown (as `SwichPayException`s), not reported as
89
+ * `failed`, so a SwichPay outage never cancels a paid order.
90
+ */
91
+ function createPaymentVerifier(source) {
92
+ const client = lazyServerClient(source, 'Payment verification');
93
+ return async input => {
94
+ const guid = input.paymentSessionGuid?.trim();
95
+ if (!guid) throw new _errors.SwichPayValidationException('paymentSessionGuid is required.');
96
+ const inquiry = await client().inquirePaymentSession({
97
+ paymentSessionGuid: guid
98
+ });
99
+ return evaluateInquiry(inquiry, input);
100
+ };
101
+ }
102
+ /**
103
+ * Creates a payment session server-side with SwichPay's existing
104
+ * `POST /gateway/paymentsession/initiate` and returns the hosted checkout URL plus the session
105
+ * GUID. Save the GUID with the order, then redirect the customer to `url`.
106
+ */
107
+ function createCheckoutSessionCreator(source) {
108
+ const client = lazyServerClient(source, 'Creating a checkout session');
109
+ return async input => {
110
+ const url = await client().createHostedCheckoutUrl(input);
111
+ const paymentSessionGuid = new URL(url).searchParams.get('Id');
112
+ if (!paymentSessionGuid) {
113
+ throw new _errors.SwichPayApiException('paymentsession/initiate url did not include an Id.', {
114
+ statusCode: 200
115
+ });
116
+ }
117
+ return {
118
+ url,
119
+ paymentSessionGuid
120
+ };
121
+ };
122
+ }
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.SwichPay = void 0;
7
+ var _client = require("./client.js");
8
+ var _errors = require("./errors.js");
9
+ let current = null;
10
+
11
+ /**
12
+ * Static facade. UI methods (`presentPaymentSheet`, ...)
13
+ * live in `@swichpay/react` and `@swichpay/nuxt`, which need a framework to render.
14
+ */
15
+ const SwichPay = exports.SwichPay = {
16
+ /**
17
+ * Call once, as early as possible. Calling again replaces (and disposes) the previous client.
18
+ * Returns the client for direct access to every method.
19
+ */
20
+ initialize(options, deps) {
21
+ const next = new _client.SwichPayClient(options, deps);
22
+ current?.dispose();
23
+ current = next;
24
+ return next;
25
+ },
26
+ /** Makes an existing client the live one (used by `<SwichPayProvider options>`). */
27
+ attach(client) {
28
+ current = client;
29
+ },
30
+ /** Clears the live client if it is `client` (without disposing it). */
31
+ detach(client) {
32
+ if (current === client) current = null;
33
+ },
34
+ /** The live client; throws `SwichPayNotInitializedException` before `initialize`. */
35
+ get client() {
36
+ if (!current || current.isDisposed) throw new _errors.SwichPayNotInitializedException();
37
+ return current;
38
+ },
39
+ get isInitialized() {
40
+ return current != null && !current.isDisposed;
41
+ },
42
+ /** Submits a card payment directly against your own form. */
43
+ pay(input) {
44
+ return run(() => SwichPay.client.pay(input));
45
+ },
46
+ /** Listens for every payment result. Returns an unsubscribe function (also `.cancel()`). */
47
+ onResult(callback) {
48
+ return SwichPay.client.onResult(callback);
49
+ },
50
+ /** Payment method categories enabled for this merchant. */
51
+ availableCategories() {
52
+ return run(() => SwichPay.client.availableCategories());
53
+ },
54
+ /** Queries a session's current status. */
55
+ inquirePaymentSession(input) {
56
+ return run(() => SwichPay.client.inquirePaymentSession(input));
57
+ },
58
+ /** Disposes the live client; the facade is uninitialized afterwards. */
59
+ dispose() {
60
+ current?.dispose();
61
+ current = null;
62
+ }
63
+ };
64
+
65
+ /** Turns synchronous throws (e.g. not initialized) into rejections, like a Dart `Future`. */
66
+ function run(fn) {
67
+ try {
68
+ return fn();
69
+ } catch (error) {
70
+ return Promise.reject(error);
71
+ }
72
+ }
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.decodeJwtClaim = decodeJwtClaim;
7
+ exports.generateTransactionCheckSum = generateTransactionCheckSum;
8
+ exports.generateUuidV4 = generateUuidV4;
9
+ var _errors = require("../errors.js");
10
+ function subtle() {
11
+ const s = globalThis.crypto?.subtle;
12
+ if (!s) {
13
+ throw new _errors.SwichPayValidationException('Web Crypto (crypto.subtle) is unavailable - it needs a secure context (https or localhost) or Node 18+.');
14
+ }
15
+ return s;
16
+ }
17
+ function bytesToBase64(bytes) {
18
+ let binary = '';
19
+ for (const b of bytes) binary += String.fromCharCode(b);
20
+ return btoa(binary);
21
+ }
22
+
23
+ /**
24
+ * Same as every SwichPay SDK's `generateTransactionCheckSum`: base64 of
25
+ * HMAC-SHA256(secretHashKey, "Currency~Amount~CustomerTransactionId"), amount fixed to 2 decimals.
26
+ */
27
+ async function generateTransactionCheckSum(input) {
28
+ const canonical = `${input.currency.trim()}~${input.amount.toFixed(2)}~${input.customerTransactionId.trim()}`;
29
+ const encoder = new TextEncoder();
30
+ const key = await subtle().importKey('raw', encoder.encode(input.secretHashKey), {
31
+ name: 'HMAC',
32
+ hash: 'SHA-256'
33
+ }, false, ['sign']);
34
+ const signature = await subtle().sign('HMAC', key, encoder.encode(canonical));
35
+ return bytesToBase64(new Uint8Array(signature));
36
+ }
37
+
38
+ /**
39
+ * Random UUID v4 (RTP Now's `rtpId`). These are unique references, not
40
+ * secrets: without `crypto.getRandomValues` (Expo Go has no native crypto module) it falls back
41
+ * to `Math.random`. Install `react-native-get-random-values` for crypto-quality ids.
42
+ */
43
+ function generateUuidV4() {
44
+ const c = globalThis.crypto;
45
+ if (c && typeof c.randomUUID === 'function') return c.randomUUID();
46
+ const bytes = new Uint8Array(16);
47
+ if (c && typeof c.getRandomValues === 'function') c.getRandomValues(bytes);else for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);
48
+ bytes[6] = bytes[6] & 0x0f | 0x40;
49
+ bytes[8] = bytes[8] & 0x3f | 0x80;
50
+ const hex = Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('');
51
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
52
+ }
53
+
54
+ /** UTF-8 bytes to text; works without `TextDecoder` (older Hermes / React Native). */
55
+ function utf8Decode(bytes) {
56
+ if (typeof TextDecoder !== 'undefined') return new TextDecoder().decode(bytes);
57
+ let encoded = '';
58
+ for (const byte of bytes) encoded += `%${byte.toString(16).padStart(2, '0')}`;
59
+ return decodeURIComponent(encoded);
60
+ }
61
+
62
+ /** Decodes a string `claim` from a JWT's payload without verifying its signature. */
63
+ function decodeJwtClaim(jwt, claim) {
64
+ const parts = jwt.split('.');
65
+ if (parts.length !== 3) return null;
66
+ try {
67
+ let b64 = parts[1].replace(/-/g, '+').replace(/_/g, '/');
68
+ while (b64.length % 4 !== 0) b64 += '=';
69
+ const binary = atob(b64);
70
+ const bytes = Uint8Array.from(binary, ch => ch.charCodeAt(0));
71
+ const data = JSON.parse(utf8Decode(bytes));
72
+ if (typeof data !== 'object' || data === null) return null;
73
+ const value = data[claim];
74
+ return typeof value === 'string' ? value : null;
75
+ } catch {
76
+ return null;
77
+ }
78
+ }
@@ -0,0 +1,68 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.dartDoubleString = dartDoubleString;
7
+ exports.digitsOnly = digitsOnly;
8
+ exports.formatAmount = formatAmount;
9
+ exports.formatAmountWhole = formatAmountWhole;
10
+ exports.formatCardNumber = formatCardNumber;
11
+ exports.formatCountdown = formatCountdown;
12
+ exports.formatExpiry = formatExpiry;
13
+ exports.maskForDisplay = maskForDisplay;
14
+ exports.todayIsoDate = todayIsoDate;
15
+ /** Card number in 4-digit groups (`4242 4242 4242 4242`), capped at 19 digits. */
16
+ function formatCardNumber(input) {
17
+ const digits = digitsOnly(input, 19);
18
+ return digits.replace(/(\d{4})(?=\d)/g, '$1 ');
19
+ }
20
+
21
+ /** Expiry as `MM/YY` while typing. */
22
+ function formatExpiry(input) {
23
+ const digits = digitsOnly(input, 4);
24
+ return digits.length > 2 ? `${digits.slice(0, 2)}/${digits.slice(2)}` : digits;
25
+ }
26
+
27
+ /** Strips non-digits and optionally caps the length. */
28
+ function digitsOnly(input, maxLength) {
29
+ const digits = String(input ?? '').replace(/\D/g, '');
30
+ return maxLength == null ? digits : digits.slice(0, maxLength);
31
+ }
32
+
33
+ /** Display amount like Dart's `num.toString()` for the payment sheet (`1000`, `10.5`). */
34
+ function formatAmount(amount) {
35
+ return String(amount);
36
+ }
37
+
38
+ /** Dart's `toStringAsFixed(0)`, used by the direct sheets' pay buttons. */
39
+ function formatAmountWhole(amount) {
40
+ return amount.toFixed(0);
41
+ }
42
+
43
+ /** Dart's `num.toDouble().toString()` - `1000` becomes `"1000.0"` (RTP E-wallet wire format). */
44
+ function dartDoubleString(amount) {
45
+ if (!Number.isFinite(amount)) return String(amount);
46
+ return Number.isInteger(amount) ? `${amount}.0` : String(amount);
47
+ }
48
+
49
+ /** Today as `yyyy-MM-dd` in local time. */
50
+ function todayIsoDate(now = new Date()) {
51
+ const two = n => String(n).padStart(2, '0');
52
+ return `${now.getFullYear()}-${two(now.getMonth() + 1)}-${two(now.getDate())}`;
53
+ }
54
+
55
+ /** `mm:ss` for countdowns. */
56
+ function formatCountdown(totalSeconds) {
57
+ const s = Math.max(0, Math.floor(totalSeconds));
58
+ const two = n => String(n).padStart(2, '0');
59
+ return `${two(Math.floor(s / 60))}:${two(s % 60)}`;
60
+ }
61
+
62
+ /** `"<first 4 digits>***<last 4 digits>"`, regardless of whether already masked. */
63
+ function maskForDisplay(value) {
64
+ const digits = String(value ?? '').replace(/\D/g, '');
65
+ if (digits.length <= 4) return value;
66
+ const prefix = digits.length >= 8 ? digits.slice(0, 4) : '';
67
+ return `${prefix}***${digits.slice(-4)}`;
68
+ }
@@ -0,0 +1,110 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.boolOrNull = boolOrNull;
7
+ exports.deepFindString = deepFindString;
8
+ exports.intOrNull = intOrNull;
9
+ exports.isJsonMap = isJsonMap;
10
+ exports.listOfMaps = listOfMaps;
11
+ exports.mapOrNull = mapOrNull;
12
+ exports.nonBlankString = nonBlankString;
13
+ exports.normalizedCode = normalizedCode;
14
+ exports.numOr = numOr;
15
+ exports.parseJsonObject = parseJsonObject;
16
+ exports.str = str;
17
+ exports.stringMap = stringMap;
18
+ exports.stringOrNull = stringOrNull;
19
+ /**
20
+ * Defensive JSON helpers. The SwichPay backend mixes types for nominally-typed fields (numeric
21
+ * codes, `data: false` where an object is documented), so every read coerces instead of casting -
22
+ * same policy as every SwichPay SDK.
23
+ */
24
+
25
+ function isJsonMap(value) {
26
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
27
+ }
28
+
29
+ /** `value` as a JSON object, or `null` when it's anything else. */
30
+ function mapOrNull(value) {
31
+ return isJsonMap(value) ? value : null;
32
+ }
33
+
34
+ /** Parses a response body leniently: empty or non-object JSON becomes `{}`. */
35
+ function parseJsonObject(text) {
36
+ if (text === '') return {};
37
+ try {
38
+ const decoded = JSON.parse(text);
39
+ return isJsonMap(decoded) ? decoded : {};
40
+ } catch {
41
+ return {};
42
+ }
43
+ }
44
+
45
+ /** Any non-null value as a string (Dart `value.toString()` for primitives). */
46
+ function str(value) {
47
+ if (value == null) return null;
48
+ if (typeof value === 'string') return value;
49
+ if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') return String(value);
50
+ return JSON.stringify(value);
51
+ }
52
+
53
+ /** A string only when the value is a non-blank string. */
54
+ function nonBlankString(value) {
55
+ return typeof value === 'string' && value.trim() !== '' ? value : null;
56
+ }
57
+
58
+ /** `code` may arrive as a raw JSON number instead of a `"0000"`-style string. */
59
+ function normalizedCode(code) {
60
+ if (code == null) return null;
61
+ if (typeof code === 'string') return code.trim();
62
+ if (typeof code === 'number') return String(Math.trunc(code));
63
+ return str(code);
64
+ }
65
+ function intOrNull(value) {
66
+ return typeof value === 'number' && Number.isFinite(value) ? Math.trunc(value) : null;
67
+ }
68
+ function numOr(value, fallback) {
69
+ if (typeof value === 'number' && Number.isFinite(value)) return value;
70
+ if (typeof value === 'string' && value.trim() !== '') {
71
+ const parsed = Number(value);
72
+ if (Number.isFinite(parsed)) return parsed;
73
+ }
74
+ return fallback;
75
+ }
76
+ function stringOrNull(value) {
77
+ return typeof value === 'string' ? value : null;
78
+ }
79
+ function boolOrNull(value) {
80
+ return typeof value === 'boolean' ? value : null;
81
+ }
82
+ function listOfMaps(value) {
83
+ return Array.isArray(value) ? value.filter(isJsonMap) : [];
84
+ }
85
+
86
+ /** First string value under `key` at any nesting depth. */
87
+ function deepFindString(json, key) {
88
+ if (isJsonMap(json)) {
89
+ const direct = json[key];
90
+ if (typeof direct === 'string') return direct;
91
+ for (const value of Object.values(json)) {
92
+ const found = deepFindString(value, key);
93
+ if (found != null) return found;
94
+ }
95
+ } else if (Array.isArray(json)) {
96
+ for (const item of json) {
97
+ const found = deepFindString(item, key);
98
+ if (found != null) return found;
99
+ }
100
+ }
101
+ return null;
102
+ }
103
+
104
+ /** Map values coerced to strings (for `formFields`). */
105
+ function stringMap(map) {
106
+ if (!map) return null;
107
+ const out = {};
108
+ for (const [key, value] of Object.entries(map)) out[key] = str(value) ?? 'null';
109
+ return out;
110
+ }