@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,344 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.SwichPayClient = void 0;
7
+ exports.validateCard = validateCard;
8
+ var _directPaymentApi = require("./api/direct-payment-api.js");
9
+ var _discountApi = require("./api/discount-api.js");
10
+ var _gatewayApi = require("./api/gateway-api.js");
11
+ var _paymentsApi = require("./api/payments-api.js");
12
+ var _config = require("./config.js");
13
+ var _errors = require("./errors.js");
14
+ var _events = require("./events.js");
15
+ var _apiClient = require("./http/api-client.js");
16
+ var _payment = require("./models/payment.js");
17
+ var _crypto = require("./utils/crypto.js");
18
+ var _validators = require("./utils/validators.js");
19
+ /** Throws SwichPay's card validation errors. */
20
+ function validateCard(card) {
21
+ if (card == null || typeof card !== 'object') throw new _errors.SwichPayValidationException('Card details are required.');
22
+ if (!_validators.CardValidators.isValidNumber(card.number)) throw new _errors.SwichPayValidationException('Invalid card number.');
23
+ if (!_validators.CardValidators.isValidExpiry(card.expMonth, card.expYear)) {
24
+ throw new _errors.SwichPayValidationException('Card has expired or invalid expiry.');
25
+ }
26
+ if (!_validators.CardValidators.isValidCvv(card.cvv)) throw new _errors.SwichPayValidationException('Invalid CVV.');
27
+ }
28
+
29
+ /**
30
+ * One live SDK session: config, API layers and the result stream behind `onResult`.
31
+ * Every completed payment attempt is emitted to that stream.
32
+ */
33
+ class SwichPayClient {
34
+ results = new _events.Emitter();
35
+ disposed = false;
36
+ constructor(options, deps = {}) {
37
+ this.config = (0, _config.resolveConfig)(options);
38
+ const api = new _apiClient.ApiClient(this.config);
39
+ this.gateway = deps.gatewayApi ?? new _gatewayApi.GatewayApi(api);
40
+ this.payments = deps.paymentsApi ?? new _paymentsApi.PaymentsApi(api);
41
+ this.direct = deps.directPaymentApi ?? new _directPaymentApi.DirectPaymentApi(api);
42
+ this.discount = deps.discountApi ?? new _discountApi.DiscountApi(api);
43
+ }
44
+ get isDisposed() {
45
+ return this.disposed;
46
+ }
47
+
48
+ /** Listens for every payment result. */
49
+ onResult(listener) {
50
+ return this.results.on(listener);
51
+ }
52
+ emit(result) {
53
+ this.results.emit(result);
54
+ return result;
55
+ }
56
+
57
+ // ── Checkout host (custom card UI) ──
58
+
59
+ async pay(input) {
60
+ const sessionToken = await this.startSession();
61
+ return this.payWithSession({
62
+ sessionToken,
63
+ ...input
64
+ });
65
+ }
66
+
67
+ /** Runs `/init` and returns `clientId`, the token that authenticates it. */
68
+ async startSession() {
69
+ await this.payments.init(this.config.clientId);
70
+ return this.config.clientId;
71
+ }
72
+ async payWithSession(input) {
73
+ validateCard(input.card);
74
+ const details = (0, _payment.resolvePaymentDetails)(input.details);
75
+ const result = await this.payments.pay({
76
+ details,
77
+ card: input.card,
78
+ clientId: this.config.clientId,
79
+ merchantId: this.config.merchantId,
80
+ sessionToken: input.sessionToken
81
+ });
82
+ return this.emit(result);
83
+ }
84
+
85
+ // ── Session-based checkout ──
86
+
87
+ /** Categories and logos enabled for this merchant; fetched fresh each time. */
88
+ loadMobileAppInit() {
89
+ return this.gateway.mobileAppInit(this.config.appId);
90
+ }
91
+ async availableCategories() {
92
+ return (await this.loadMobileAppInit()).categories;
93
+ }
94
+
95
+ /**
96
+ * URL of SwichPay's hosted checkout page. The session always gets every enabled category
97
+ * (matches native); `categories` exists for API symmetry only.
98
+ */
99
+ async createHostedCheckoutUrl(input) {
100
+ const details = (0, _payment.resolvePaymentDetails)(input.details);
101
+ const created = await this.gateway.createPaymentSession(details, await this.availableCategories());
102
+ return created.url;
103
+ }
104
+
105
+ /**
106
+ * Creates a session and fetches its details. `categories` only restricts what the returned
107
+ * details list (what a sheet displays), not what the session supports.
108
+ */
109
+ async startNativeCheckout(input) {
110
+ const details = (0, _payment.resolvePaymentDetails)(input.details);
111
+ const created = await this.gateway.createPaymentSession(details, await this.availableCategories());
112
+ const session = await this.gateway.getPaymentSessionDetails(created.guid);
113
+ if (input.categories == null) return session;
114
+ const allowed = new Set(input.categories);
115
+ return {
116
+ ...session,
117
+ categories: session.categories.filter(c => allowed.has(c))
118
+ };
119
+ }
120
+ async processCardPayment(input) {
121
+ if (input.isSavedCardSelected !== true) validateCard(input.card);
122
+ return this.emit(await this.gateway.processCardPayment(input));
123
+ }
124
+
125
+ /**
126
+ * Discount quote for a card payment (new card entry only - never for a saved card). Never
127
+ * emits. `ipAddress` defaults to `''` - a browser can't read the device IP.
128
+ */
129
+ getCardDiscount(input) {
130
+ const details = (0, _payment.resolvePaymentDetails)(input.details);
131
+ return this.discount.getDiscount({
132
+ amount: details.amount,
133
+ referenceValue: input.cardNumber,
134
+ categoryId: input.categoryId ?? 'CardBins',
135
+ merchantId: this.config.merchantId,
136
+ customerTransactionId: details.customerTransactionId,
137
+ ipAddress: input.ipAddress ?? '',
138
+ discountableAmount: details.amount,
139
+ msisdn: details.msisdn
140
+ });
141
+ }
142
+ async processEwalletPayment(input) {
143
+ return this.emit(await this.gateway.processEwalletPayment(input));
144
+ }
145
+
146
+ /**
147
+ * Discount quote for an e-wallet payment; `channelId` is the wallet's channel (8 EasyPaisa,
148
+ * 10 JazzCash). Never emits. `ipAddress` defaults to `"127.0.0.1"`
149
+ */
150
+ getEwalletDiscount(input) {
151
+ const details = (0, _payment.resolvePaymentDetails)(input.details);
152
+ return this.discount.getDiscount({
153
+ amount: details.amount,
154
+ referenceValue: String(input.channelId),
155
+ categoryId: input.categoryId ?? 'Ewallet',
156
+ merchantId: this.config.merchantId,
157
+ customerTransactionId: details.customerTransactionId,
158
+ ipAddress: input.ipAddress === undefined ? '127.0.0.1' : input.ipAddress ?? '',
159
+ discountableAmount: details.amount,
160
+ msisdn: input.msisdn
161
+ });
162
+ }
163
+
164
+ /** If the result has `otpRequired`, call again with `otp`. */
165
+ async processBankAccountPayment(input) {
166
+ return this.emit(await this.gateway.processBankAccountPayment(input));
167
+ }
168
+
169
+ /** Called twice: first with `msisdn` for the consumer number, then with `consumerNumber` to verify. */
170
+ async processBillerPayment(input) {
171
+ return this.emit(await this.gateway.processBillerPayment(input));
172
+ }
173
+ async submitPaymentEnrollment(input) {
174
+ return this.emit(await this.gateway.submitPaymentEnrollment(input));
175
+ }
176
+
177
+ /**
178
+ * `tracker` is ProcessPayment's `vendorTransactionId`. With `orderId` and a payment-api host,
179
+ * asks `InquireV3` instead (resolves session card payments by `orderId`).
180
+ */
181
+ async checkCardPaymentStatus(input) {
182
+ const hasPaymentApi = !!this.config.hosts.paymentApi;
183
+ const result = input.orderId && hasPaymentApi ? await this.direct.checkDirectCardPaymentStatus(input.orderId) : await this.gateway.checkCardPaymentStatus(input.tracker, input.forceTimeout ?? false);
184
+ return this.emit(result);
185
+ }
186
+ async processQrPayment(input) {
187
+ return this.emit(await this.gateway.processQrPayment(input));
188
+ }
189
+ async processRtpNowPayment(input) {
190
+ return this.emit(await this.gateway.processRtpNowPayment(input));
191
+ }
192
+
193
+ /** For when the user explicitly closes/cancels a payment sheet. */
194
+ cancelSession(input) {
195
+ return this.gateway.cancelSession(input.paymentSessionGuid);
196
+ }
197
+ inquirePaymentSession(input) {
198
+ return this.gateway.inquirePaymentSession(input.paymentSessionGuid);
199
+ }
200
+
201
+ // ── Direct (session-less) payments ──
202
+
203
+ async directEwalletPayment(input) {
204
+ const details = (0, _payment.resolvePaymentDetails)(input.details);
205
+ return this.emit(await this.direct.directEwalletPayment({
206
+ details,
207
+ channelId: input.channelId,
208
+ msisdn: input.msisdn
209
+ }));
210
+ }
211
+
212
+ /** Step 1 of a bank transfer; if `otpRequired`, call `confirmDirectBankTransfer`. Never emits. */
213
+ directBankTransfer(input) {
214
+ const details = (0, _payment.resolvePaymentDetails)(input.details);
215
+ return this.direct.directBankTransfer({
216
+ details,
217
+ bankCode: input.bankCode,
218
+ accountNo: input.accountNo
219
+ });
220
+ }
221
+ async confirmDirectBankTransfer(input) {
222
+ return this.emit(await this.direct.confirmDirectBankTransfer(input));
223
+ }
224
+ fetchDirectBankList() {
225
+ return this.direct.fetchDirectBankList();
226
+ }
227
+
228
+ /** The result's `consumerNumber` is what the customer pays against. Never emits. */
229
+ generateDirectOneBill(input) {
230
+ return this.direct.generateDirectOneBill({
231
+ details: (0, _payment.resolvePaymentDetails)(input.details)
232
+ });
233
+ }
234
+
235
+ /** Emits on success only. */
236
+ async checkDirectOneBillStatus(input) {
237
+ const result = await this.direct.checkDirectOneBillStatus(input.customerTransactionId);
238
+ if (result.isSuccess) this.emit(result);
239
+ return result;
240
+ }
241
+
242
+ /** The result's `qrString` is the payload to render. Never emits. */
243
+ generateDirectQrPayment(input) {
244
+ return this.direct.generateDirectQrPayment((0, _payment.resolvePaymentDetails)(input.details));
245
+ }
246
+
247
+ /** Emits on success only. */
248
+ async checkDirectQrStatus(input) {
249
+ const result = await this.direct.checkDirectQrStatus(input.customerTransactionId);
250
+ if (result.isSuccess) this.emit(result);
251
+ return result;
252
+ }
253
+ fetchDirectRtpNowBanks() {
254
+ return this.direct.fetchDirectRtpNowBanks();
255
+ }
256
+ async directRtpNowPayment(input) {
257
+ const details = (0, _payment.resolvePaymentDetails)(input.details);
258
+ return this.emit(await this.direct.directRtpNowPayment({
259
+ ...input,
260
+ details
261
+ }));
262
+ }
263
+ fetchDirectRtpEwalletBanks() {
264
+ return this.direct.fetchDirectRtpEwalletBanks();
265
+ }
266
+ async directRtpEwalletPayment(input) {
267
+ const details = (0, _payment.resolvePaymentDetails)(input.details);
268
+ return this.emit(await this.direct.directRtpEwalletPayment({
269
+ details,
270
+ bankCode: input.bankCode,
271
+ msisdn: input.msisdn ?? '',
272
+ iban: input.iban ?? ''
273
+ }));
274
+ }
275
+
276
+ // ── Direct card ──
277
+
278
+ /**
279
+ * Submits a direct card payment. Needs a checksum source: `secretHashKey`, `getChecksum`, or a
280
+ * proxy (which signs server-side). Emits unless a device-data-collection step follows.
281
+ */
282
+ async directCardPayment(input) {
283
+ validateCard(input.card);
284
+ const details = (0, _payment.resolvePaymentDetails)(input.details);
285
+ const checksum = await this.checksumFor(details.currency, details.amount, details.customerTransactionId);
286
+ const result = await this.direct.directCardPayment({
287
+ details,
288
+ card: input.card,
289
+ clientId: this.config.clientId,
290
+ checksum,
291
+ merchantId: this.config.merchantId,
292
+ doCardOnFile: input.doCardOnFile ?? false
293
+ });
294
+ if (result.ddcCollectionUrl == null) this.emit(result);
295
+ return result;
296
+ }
297
+ async checksumFor(currency, amount, customerTransactionId) {
298
+ const {
299
+ getChecksum,
300
+ secretHashKey,
301
+ authMode
302
+ } = this.config;
303
+ if (getChecksum) return getChecksum({
304
+ currency,
305
+ amount,
306
+ customerTransactionId
307
+ });
308
+ if (secretHashKey) return (0, _crypto.generateTransactionCheckSum)({
309
+ currency,
310
+ amount,
311
+ customerTransactionId,
312
+ secretHashKey
313
+ });
314
+ // The proxy adds `recievedCheckSum` server-side.
315
+ if (authMode === 'proxy') return '';
316
+ throw new _errors.SwichPayValidationException('Direct card payment requires secretHashKey - pass secretHashKey (or getChecksum, or proxyUrl) to SwichPay.initialize().');
317
+ }
318
+
319
+ /** Completes a direct card payment after device-data-collection. Emits unless a step-up follows. */
320
+ async executeDirectCardTokenizedPayment(input) {
321
+ const result = await this.direct.executeDirectCardTokenizedPayment({
322
+ customerTransactionId: input.customerTransactionId,
323
+ billReferenceNo: input.billReferenceNo,
324
+ vendorTransactionId: input.tracker,
325
+ sessionId: input.sessionId
326
+ });
327
+ if (result.stepUpUrl == null) this.emit(result);
328
+ return result;
329
+ }
330
+
331
+ /** `tracker` is `vendorTransactionId` from `directCardPayment`. Emits unless still pending. */
332
+ async checkDirectCardPaymentStatus(input) {
333
+ const result = await this.direct.checkDirectCardPaymentStatus(input.tracker);
334
+ if (result.status.toLowerCase() !== 'pending') this.emit(result);
335
+ return result;
336
+ }
337
+
338
+ /** Stops result delivery and drops every listener. */
339
+ dispose() {
340
+ this.disposed = true;
341
+ this.results.close();
342
+ }
343
+ }
344
+ exports.SwichPayClient = SwichPayClient;
@@ -0,0 +1,132 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.DEFAULT_TIMEOUTS = void 0;
7
+ exports.resolveConfig = resolveConfig;
8
+ var _environment = require("./environment.js");
9
+ var _errors = require("./errors.js");
10
+ var _log = require("./utils/log.js");
11
+ var _runtime = require("./utils/runtime.js");
12
+ /** An access token returned by a merchant-hosted token endpoint. */
13
+
14
+ /**
15
+ * Options for `SwichPay.initialize()` / `new SwichPayClient()`.
16
+ *
17
+ * The first six are the standard SwichPay merchant settings. The rest are optional,
18
+ * because a browser can't keep a secret and SwichPay's hosts don't send CORS headers to
19
+ * arbitrary origins - see docs/authentication.md.
20
+ */
21
+
22
+ const DEFAULT_TIMEOUTS = exports.DEFAULT_TIMEOUTS = {
23
+ request: 3 * 60 * 1000,
24
+ discount: 10 * 1000
25
+ };
26
+ function requireString(value, name, {
27
+ nonEmpty = false
28
+ } = {}) {
29
+ if (typeof value !== 'string' || nonEmpty && value.trim() === '') {
30
+ throw new _errors.SwichPayValidationException(`SwichPay option "${name}" must be a${nonEmpty ? ' non-empty' : ''} string.`);
31
+ }
32
+ return value;
33
+ }
34
+ function nonEmptyOrNull(value) {
35
+ return value != null && value !== '' ? value : null;
36
+ }
37
+ function trimSlash(url) {
38
+ return url.replace(/\/+$/, '');
39
+ }
40
+
41
+ /** Validates options and resolves hosts, auth mode and defaults. */
42
+ function resolveConfig(options) {
43
+ if (options == null || typeof options !== 'object') {
44
+ throw new _errors.SwichPayValidationException('SwichPay options are required.');
45
+ }
46
+ const clientId = requireString(options.clientId, 'clientId', {
47
+ nonEmpty: true
48
+ });
49
+ const referrer = requireString(options.referrer, 'referrer');
50
+ const appId = requireString(options.appId, 'appId');
51
+ if (typeof options.merchantId !== 'number' || !Number.isInteger(options.merchantId)) {
52
+ throw new _errors.SwichPayValidationException('SwichPay option "merchantId" must be an integer.');
53
+ }
54
+ if (!(0, _environment.isEnvironment)(options.environment)) {
55
+ throw new _errors.SwichPayValidationException('SwichPay option "environment" must be "sandbox" or "production".');
56
+ }
57
+ const environment = options.environment;
58
+ const clientSecret = nonEmptyOrNull(options.clientSecret);
59
+ const secretHashKey = nonEmptyOrNull(options.secretHashKey);
60
+ if ((clientSecret || secretHashKey) && (0, _runtime.isClientRuntime)() && !options.dangerouslyAllowBrowserSecrets) {
61
+ throw new _errors.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.');
62
+ }
63
+ const base = _environment.ENVIRONMENT_HOSTS[environment];
64
+ let hosts = {
65
+ ...base
66
+ };
67
+ const proxyUrl = nonEmptyOrNull(options.proxyUrl);
68
+ if (proxyUrl) {
69
+ const p = trimSlash(proxyUrl);
70
+ hosts = {
71
+ checkout: `${p}/checkout`,
72
+ gateway: `${p}/gateway`,
73
+ auth: `${p}/auth`,
74
+ discount: base.discount ? `${p}/discount` : null,
75
+ paymentApi: base.paymentApi ? `${p}/payment-api` : null
76
+ };
77
+ }
78
+ if (options.hosts) {
79
+ const {
80
+ checkout,
81
+ gateway,
82
+ auth,
83
+ discount,
84
+ paymentApi
85
+ } = options.hosts;
86
+ if (checkout) hosts.checkout = trimSlash(checkout);
87
+ if (gateway) hosts.gateway = trimSlash(gateway);
88
+ if (auth) hosts.auth = trimSlash(auth);
89
+ if (discount !== undefined) hosts.discount = discount === null ? null : trimSlash(discount);
90
+ if (paymentApi !== undefined) hosts.paymentApi = paymentApi === null ? null : trimSlash(paymentApi);
91
+ }
92
+ const baseUrlOverride = nonEmptyOrNull(options.baseUrlOverride);
93
+ if (baseUrlOverride) hosts.checkout = trimSlash(baseUrlOverride);
94
+
95
+ // Production traffic carries card data and bearer tokens: never over plain HTTP. Sandbox may use
96
+ // http:// for a local backend (emulator 10.0.2.2, a LAN IP).
97
+ if (environment === 'production') {
98
+ for (const [name, host] of Object.entries(hosts)) {
99
+ if (host != null && !host.toLowerCase().startsWith('https://')) {
100
+ throw new _errors.SwichPayValidationException(`SwichPay host "${name}" (${host}) must use https:// in production. Check proxyUrl / hosts / baseUrlOverride.`);
101
+ }
102
+ }
103
+ }
104
+ const authMode = proxyUrl ? 'proxy' : options.getAccessToken ? 'token-provider' : clientSecret ? 'client-secret' : 'public-key';
105
+ const log = (0, _log.createLog)(options.logger);
106
+ if (clientSecret && secretHashKey && clientSecret === secretHashKey) {
107
+ log('clientSecret and secretHashKey are the same value - the token endpoint rejects this (invalid_client).');
108
+ }
109
+ const fetchImpl = options.fetch ?? (typeof globalThis.fetch === 'function' ? globalThis.fetch.bind(globalThis) : undefined);
110
+ if (!fetchImpl) {
111
+ throw new _errors.SwichPayValidationException('No fetch implementation available - pass options.fetch.');
112
+ }
113
+ return Object.freeze({
114
+ clientId,
115
+ referrer,
116
+ merchantId: options.merchantId,
117
+ appId,
118
+ environment,
119
+ hosts: Object.freeze(hosts),
120
+ clientSecret,
121
+ secretHashKey,
122
+ authMode,
123
+ getAccessToken: options.getAccessToken ?? null,
124
+ getChecksum: options.getChecksum ?? null,
125
+ fetch: fetchImpl,
126
+ log,
127
+ timeouts: Object.freeze({
128
+ ...DEFAULT_TIMEOUTS,
129
+ ...options.timeouts
130
+ })
131
+ });
132
+ }
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.Environment = exports.ENVIRONMENT_HOSTS = void 0;
7
+ exports.isEnvironment = isEnvironment;
8
+ /** The backend environment a SwichPay client talks to. */
9
+
10
+ const Environment = exports.Environment = {
11
+ sandbox: 'sandbox',
12
+ production: 'production'
13
+ };
14
+ /** SwichPay hosts per environment. */
15
+ const ENVIRONMENT_HOSTS = exports.ENVIRONMENT_HOSTS = {
16
+ sandbox: {
17
+ checkout: 'https://testcheckout.swichnow.com',
18
+ gateway: 'https://sandbox-api.swichnow.com',
19
+ auth: 'https://sandbox-auth.swichnow.com',
20
+ discount: 'https://sandbox-api-discount.swichnow.com',
21
+ paymentApi: 'https://sandbox-paymentapi.swichnow.com'
22
+ },
23
+ production: {
24
+ checkout: 'https://checkout.swichnow.com',
25
+ gateway: 'https://api.swichnow.com',
26
+ auth: 'https://auth.swichnow.com',
27
+ // No production host exists yet - calls fail fast instead of sending live data to sandbox.
28
+ discount: null,
29
+ paymentApi: null
30
+ }
31
+ };
32
+ function isEnvironment(value) {
33
+ return value === 'sandbox' || value === 'production';
34
+ }
@@ -0,0 +1,138 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.SwichPayValidationException = exports.SwichPayNotInitializedException = exports.SwichPayNetworkException = exports.SwichPayException = exports.SwichPayApiException = void 0;
7
+ exports.attemptUsedTransactionId = attemptUsedTransactionId;
8
+ exports.isSwichPayException = isSwichPayException;
9
+ exports.swichpayUserError = swichpayUserError;
10
+ exports.swichpayUserMessage = swichpayUserMessage;
11
+ /**
12
+ * Error hierarchy - every SDK error is a `SwichPayException`.
13
+ * Every SDK call rejects with one of these instead of a raw fetch/parse error.
14
+ */
15
+
16
+ class SwichPayException extends Error {
17
+ /** Discriminator, handy where `instanceof` is awkward (e.g. across bundles). */
18
+
19
+ constructor(message) {
20
+ super(message);
21
+ this.name = new.target.name;
22
+ }
23
+
24
+ /**
25
+ * Short, non-technical text safe to show to the paying user. `message` is technical detail
26
+ * (URLs, HTTP codes, field names) - log it, never show it.
27
+ */
28
+
29
+ toString() {
30
+ return `${this.name}: ${this.message}`;
31
+ }
32
+ }
33
+
34
+ /** Thrown when a method is called before `SwichPay.initialize()`. */
35
+ exports.SwichPayException = SwichPayException;
36
+ class SwichPayNotInitializedException extends SwichPayException {
37
+ kind = 'not_initialized';
38
+ constructor() {
39
+ super('SwichPay.initialize() must be called before use.');
40
+ }
41
+ get userMessage() {
42
+ return 'Payments are not available right now. Please try again later.';
43
+ }
44
+ }
45
+
46
+ /** Thrown for malformed input (bad card number, missing fields, etc.) before any network call. */
47
+ exports.SwichPayNotInitializedException = SwichPayNotInitializedException;
48
+ class SwichPayValidationException extends SwichPayException {
49
+ kind = 'validation';
50
+ get userMessage() {
51
+ return this.message;
52
+ }
53
+ }
54
+
55
+ /** Thrown when the SDK fails to reach the SwichPay API. */
56
+ exports.SwichPayValidationException = SwichPayValidationException;
57
+ class SwichPayNetworkException extends SwichPayException {
58
+ kind = 'network';
59
+ constructor(message, options = {}) {
60
+ super(message);
61
+ this.cause = options.cause;
62
+ }
63
+ get userMessage() {
64
+ return 'Unable to connect. Please check your internet connection and try again.';
65
+ }
66
+ toString() {
67
+ return this.cause == null ? super.toString() : `${super.toString()} Caused by: ${String(this.cause)}`;
68
+ }
69
+ }
70
+ exports.SwichPayNetworkException = SwichPayNetworkException;
71
+ /** Thrown when the SwichPay API returns an error response. */
72
+ class SwichPayApiException extends SwichPayException {
73
+ kind = 'api';
74
+
75
+ /** The response body's own `message` (e.g. "Invalid OTP."), when the server sent one. */
76
+
77
+ /**
78
+ * The response body's own `status` (e.g. `"failed"`, `"pending"`) - a 4xx isn't always a
79
+ * decline: direct card payments answer a vendor-side pending with HTTP 400 + `"pending"`.
80
+ */
81
+
82
+ /** The response body's `orderId`, when the server created an order before erroring. */
83
+
84
+ constructor(message, init) {
85
+ super(message);
86
+ this.statusCode = init.statusCode;
87
+ this.code = init.code ?? null;
88
+ this.serverMessage = init.serverMessage ?? null;
89
+ this.serverStatus = init.serverStatus ?? null;
90
+ this.orderId = init.orderId ?? null;
91
+ }
92
+ get isPending() {
93
+ return this.serverStatus?.toLowerCase() === 'pending';
94
+ }
95
+ get userMessage() {
96
+ const status = this.statusCode;
97
+ if (status === 404) {
98
+ return 'This payment method is currently unavailable. Please try another method or try again later.';
99
+ }
100
+ if (status === 401 || status === 403) {
101
+ return 'This payment could not be authorized. Please contact the merchant.';
102
+ }
103
+ if (status === 408 || status === 429 || status >= 500) {
104
+ return 'The payment service is temporarily unavailable. Please try again in a few minutes.';
105
+ }
106
+ return this.serverMessage ?? 'Something went wrong while processing your payment. Please try again.';
107
+ }
108
+ toString() {
109
+ return `${super.toString()} (HTTP ${this.statusCode}${this.code == null ? '' : `, code ${this.code}`})`;
110
+ }
111
+ }
112
+ exports.SwichPayApiException = SwichPayApiException;
113
+ function isSwichPayException(error) {
114
+ return error instanceof SwichPayException;
115
+ }
116
+
117
+ /** `userMessage` for SwichPay errors, a generic fallback for anything else. */
118
+ function swichpayUserMessage(error) {
119
+ return isSwichPayException(error) ? error.userMessage : 'Something went wrong. Please try again.';
120
+ }
121
+
122
+ /**
123
+ * User-facing text for `error`; `fallback` replaces the generic text for errors that aren't a
124
+ * `SwichPayException`.
125
+ */
126
+ function swichpayUserError(error, fallback) {
127
+ if (fallback != null && !isSwichPayException(error)) return fallback;
128
+ return swichpayUserMessage(error);
129
+ }
130
+
131
+ /**
132
+ * Whether a failed attempt reached the gateway - and so used up the checkout's
133
+ * `customerTransactionId`, which the gateway refuses to see twice. Only a request that never
134
+ * left the device (network) or never got built (validation) is safe to resend.
135
+ */
136
+ function attemptUsedTransactionId(error) {
137
+ return !(error instanceof SwichPayNetworkException) && !(error instanceof SwichPayValidationException);
138
+ }