@madapay/papi 0.0.0-stage → 0.1.1

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.
package/LICENSE ADDED
@@ -0,0 +1,176 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the document
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or exemplary damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
package/README.md CHANGED
@@ -1,3 +1,30 @@
1
- # Temporary Holding Version
1
+ # @madapay/papi
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > Official Papi Payment API aggregator adapter for MadaPay (M2 Milestone).
4
+
5
+ ---
6
+
7
+ ## Trademark Disclaimer
8
+
9
+ **CRITICAL NOTICE:** MadaPay is an open-source software project for Madagascar mobile money integrations and is **not affiliated, associated, authorized, endorsed by, or in any way officially connected with Saudi Payments or the Saudi Arabian national payment system 'mada'**.
10
+
11
+ ---
12
+
13
+ ## Overview
14
+
15
+ `@madapay/papi` provides:
16
+
17
+ - Integration with Papi Payment API v1 (covering Telma MVola, Orange Money, Airtel Money).
18
+ - Create/status lookup (MVola, Airtel prompt flows; Orange temporary code), idempotent creation retries.
19
+ - Secure HMAC `X-Papi-Signature` webhook verification.
20
+ - Normalized error translation.
21
+
22
+ ## Installation
23
+
24
+ ```bash
25
+ pnpm add @madapay/papi @madapay/core
26
+ ```
27
+
28
+ ## License
29
+
30
+ [Apache-2.0](../../LICENSE)
package/dist/index.cjs ADDED
@@ -0,0 +1,418 @@
1
+ 'use strict';
2
+
3
+ var crypto = require('crypto');
4
+ var core = require('@madapay/core');
5
+
6
+ // src/index.ts
7
+ var PROVIDER = "papi";
8
+ function safeProviderError(payload) {
9
+ if (typeof payload !== "object" || payload === null) return {};
10
+ const p = payload;
11
+ const out = {};
12
+ for (const k of ["code", "error", "message"]) {
13
+ if (typeof p[k] === "string") out[`provider_${k}`] = p[k].slice(0, 200);
14
+ }
15
+ return out;
16
+ }
17
+ async function papiRequest(opts) {
18
+ const controller = new AbortController();
19
+ const timer = setTimeout(() => controller.abort(), opts.timeoutMs);
20
+ const onAbort = () => controller.abort();
21
+ opts.signal?.addEventListener("abort", onAbort, { once: true });
22
+ let response;
23
+ try {
24
+ response = await opts.fetchImpl(opts.url, {
25
+ method: opts.method,
26
+ headers: opts.headers,
27
+ body: opts.body === void 0 ? void 0 : JSON.stringify(opts.body),
28
+ signal: controller.signal
29
+ });
30
+ } catch {
31
+ if (opts.signal?.aborted) throw new Error("Operation aborted by caller");
32
+ const timedOut = controller.signal.aborted;
33
+ if (opts.uncertainOnFailure || timedOut) {
34
+ throw new core.ProviderTimeoutError(
35
+ timedOut ? `Papi request timed out after ${opts.timeoutMs}ms` : "Papi request failed after dispatch; outcome is uncertain (network error)",
36
+ { timeoutMs: opts.timeoutMs },
37
+ PROVIDER
38
+ );
39
+ }
40
+ throw new core.ProviderUnavailableError("Papi is unreachable", void 0, PROVIDER);
41
+ } finally {
42
+ clearTimeout(timer);
43
+ opts.signal?.removeEventListener("abort", onAbort);
44
+ }
45
+ const text = await response.text().catch(() => "");
46
+ let payload;
47
+ try {
48
+ payload = text ? JSON.parse(text) : void 0;
49
+ } catch {
50
+ payload = void 0;
51
+ }
52
+ if (response.ok) {
53
+ if (payload === void 0) {
54
+ throw opts.uncertainOnFailure ? new core.ProviderTimeoutError(
55
+ "Papi returned an unreadable success response; outcome is uncertain",
56
+ { status: response.status },
57
+ PROVIDER
58
+ ) : new core.ProviderUnavailableError("Papi returned an unreadable response", void 0, PROVIDER);
59
+ }
60
+ return payload;
61
+ }
62
+ const details = { status: response.status, ...safeProviderError(payload) };
63
+ const s = response.status;
64
+ if (s === 401 || s === 403) {
65
+ throw new core.AuthenticationError("Papi rejected the credentials", details, PROVIDER);
66
+ }
67
+ if (s === 404) throw new core.PaymentNotFoundError("Papi payment not found", details, PROVIDER);
68
+ if (s === 409) {
69
+ throw new core.DuplicatePaymentError(
70
+ "Papi idempotency conflict: same key used with a different payload",
71
+ details,
72
+ PROVIDER
73
+ );
74
+ }
75
+ if (s === 429) throw new core.ProviderUnavailableError("Papi rate limit reached", details, PROVIDER);
76
+ if (s >= 500) {
77
+ if (opts.uncertainOnFailure) {
78
+ throw new core.ProviderTimeoutError(
79
+ "Papi server error after dispatch; outcome is uncertain",
80
+ details,
81
+ PROVIDER
82
+ );
83
+ }
84
+ throw new core.ProviderUnavailableError("Papi server error", details, PROVIDER);
85
+ }
86
+ throw new core.ValidationError("Papi rejected the request", "VALIDATION_FAILED", details, PROVIDER);
87
+ }
88
+
89
+ // src/status.ts
90
+ var STATUS_MAP = {
91
+ PENDING: "pending",
92
+ PROCESSING: "processing",
93
+ SUCCESS: "succeeded",
94
+ FAILED: "failed",
95
+ EXPIRED: "expired",
96
+ CANCELLED: "cancelled"
97
+ };
98
+ function mapPapiStatus(raw) {
99
+ const key = typeof raw === "string" ? raw.toUpperCase() : "";
100
+ const status = STATUS_MAP[key];
101
+ return status ? { status, known: true } : { status: "processing", known: false };
102
+ }
103
+
104
+ // src/index.ts
105
+ var PAPI_BASE_URLS = {
106
+ sandbox: "https://api.sandbox.papi.mg",
107
+ production: "https://api.papi.mg"
108
+ };
109
+ var METHODS = ["mvola", "orange_money", "airtel_money"];
110
+ var PROVIDER2 = "papi";
111
+ function validateConfig(config) {
112
+ if (!config || typeof config.apiKey !== "string" || config.apiKey.trim() === "") {
113
+ throw new core.AuthenticationError("Papi apiKey is required", void 0, PROVIDER2);
114
+ }
115
+ if (config.environment !== "sandbox" && config.environment !== "production") {
116
+ throw new core.ValidationError(
117
+ "Papi environment must be explicitly 'sandbox' or 'production'",
118
+ "VALIDATION_FAILED",
119
+ void 0,
120
+ PROVIDER2
121
+ );
122
+ }
123
+ const baseUrl = (config.baseUrl ?? PAPI_BASE_URLS[config.environment]).replace(/\/+$/, "");
124
+ if (!baseUrl.startsWith("https://")) {
125
+ throw new core.ValidationError(
126
+ "Papi baseUrl must use https",
127
+ "VALIDATION_FAILED",
128
+ void 0,
129
+ PROVIDER2
130
+ );
131
+ }
132
+ const looksSandbox = /sandbox|test|dev/i.test(new URL(baseUrl).hostname);
133
+ if (config.environment === "production" && looksSandbox) {
134
+ throw new core.ValidationError(
135
+ "Papi production environment configured with a sandbox base URL",
136
+ "VALIDATION_FAILED",
137
+ void 0,
138
+ PROVIDER2
139
+ );
140
+ }
141
+ if (config.environment === "sandbox" && !looksSandbox) {
142
+ throw new core.ValidationError(
143
+ "Papi sandbox environment configured with a non-sandbox base URL",
144
+ "VALIDATION_FAILED",
145
+ void 0,
146
+ PROVIDER2
147
+ );
148
+ }
149
+ return baseUrl;
150
+ }
151
+ function asRecord(value) {
152
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
153
+ throw new core.ValidationError(
154
+ "Unexpected Papi response shape",
155
+ "VALIDATION_FAILED",
156
+ void 0,
157
+ PROVIDER2
158
+ );
159
+ }
160
+ return value;
161
+ }
162
+ var PapiPaymentProvider = class {
163
+ id = PROVIDER2;
164
+ name = PROVIDER2;
165
+ apiKey;
166
+ webhookSecret;
167
+ baseUrl;
168
+ environment;
169
+ notificationUrl;
170
+ timeoutMs;
171
+ maxCreationRetries;
172
+ retryInitialDelayMs;
173
+ fetchImpl;
174
+ onUnknownStatus;
175
+ constructor(config) {
176
+ this.baseUrl = validateConfig(config);
177
+ this.apiKey = config.apiKey;
178
+ this.environment = config.environment;
179
+ this.webhookSecret = config.webhookSecret;
180
+ this.notificationUrl = config.notificationUrl;
181
+ this.timeoutMs = config.timeoutMs ?? 15e3;
182
+ this.maxCreationRetries = config.maxCreationRetries ?? 2;
183
+ this.retryInitialDelayMs = config.retryInitialDelayMs ?? 200;
184
+ this.fetchImpl = config.fetch ?? ((url, init) => fetch(url, init));
185
+ this.onUnknownStatus = config.onUnknownStatus;
186
+ }
187
+ /** Never exposes credentials. */
188
+ toJSON() {
189
+ return { id: this.id, environment: this.environment, baseUrl: this.baseUrl };
190
+ }
191
+ /**
192
+ * Capability truth table. `feeQuote` is false: no Papi fee schedule is verified,
193
+ * so no fees are reported or hardcoded (PAPI-07).
194
+ */
195
+ getCapabilities() {
196
+ return {
197
+ payment: true,
198
+ asynchronousConfirmation: true,
199
+ synchronousConfirmation: true,
200
+ // Orange temporary-code flow answers synchronously
201
+ webhooks: true,
202
+ polling: true,
203
+ refunds: false,
204
+ payouts: false,
205
+ paymentLinks: false,
206
+ hostedCheckout: false,
207
+ feeQuote: false,
208
+ cancellation: false,
209
+ supportedMethods: [...METHODS],
210
+ syncConfirmation: true,
211
+ asyncConfirmation: true,
212
+ webhookEvents: true,
213
+ feeCalculation: false,
214
+ idempotentCreation: true
215
+ };
216
+ }
217
+ headers(extra = {}) {
218
+ return {
219
+ Authorization: `Bearer ${this.apiKey}`,
220
+ "Content-Type": "application/json",
221
+ Accept: "application/json",
222
+ ...extra
223
+ };
224
+ }
225
+ buildBody(request) {
226
+ if (!METHODS.includes(request.paymentMethod)) {
227
+ throw new core.UnsupportedOperationError(
228
+ `Papi does not support payment method '${String(request.paymentMethod)}'`,
229
+ { paymentMethod: request.paymentMethod },
230
+ PROVIDER2
231
+ );
232
+ }
233
+ if (!request.idempotencyKey) {
234
+ throw new core.ValidationError(
235
+ "Papi creation requires an idempotency key",
236
+ "VALIDATION_FAILED",
237
+ void 0,
238
+ PROVIDER2
239
+ );
240
+ }
241
+ const providerData = request.providerData ?? {};
242
+ const temporaryCode = providerData.temporaryCode;
243
+ const body = {
244
+ amount: request.amount,
245
+ currency: request.currency,
246
+ merchantPaymentReference: request.reference,
247
+ paymentMethod: request.paymentMethod,
248
+ customer: {
249
+ phone: core.toInternationalFormat(request.customer.phone),
250
+ ...request.customer.name ? { name: request.customer.name } : {},
251
+ ...request.customer.email ? { email: request.customer.email } : {}
252
+ }
253
+ };
254
+ if (this.notificationUrl) body.notificationUrl = this.notificationUrl;
255
+ if (request.description) body.description = request.description;
256
+ if (request.paymentMethod === "orange_money") {
257
+ if (typeof temporaryCode !== "string" || !/^\d{4,8}$/.test(temporaryCode)) {
258
+ throw new core.ValidationError(
259
+ "Orange Money requires providerData.temporaryCode (numeric code generated by the customer)",
260
+ "VALIDATION_FAILED",
261
+ void 0,
262
+ PROVIDER2
263
+ );
264
+ }
265
+ body.temporaryCode = temporaryCode;
266
+ } else if (temporaryCode !== void 0) {
267
+ throw new core.ValidationError(
268
+ "providerData.temporaryCode is only valid for orange_money",
269
+ "VALIDATION_FAILED",
270
+ void 0,
271
+ PROVIDER2
272
+ );
273
+ }
274
+ return body;
275
+ }
276
+ toProviderPayment(payload, fallbackMethod) {
277
+ const p = asRecord(payload);
278
+ const providerReference = p.paymentReference;
279
+ if (typeof providerReference !== "string" || providerReference === "") {
280
+ throw new core.ValidationError(
281
+ "Papi response missing paymentReference",
282
+ "VALIDATION_FAILED",
283
+ void 0,
284
+ PROVIDER2
285
+ );
286
+ }
287
+ const method = METHODS.includes(p.paymentMethod) ? p.paymentMethod : fallbackMethod;
288
+ if (!method || typeof p.amount !== "number") {
289
+ throw new core.ValidationError(
290
+ "Papi response missing amount or paymentMethod",
291
+ "VALIDATION_FAILED",
292
+ void 0,
293
+ PROVIDER2
294
+ );
295
+ }
296
+ const raw = typeof p.paymentStatus === "string" ? p.paymentStatus : String(p.paymentStatus);
297
+ const { status, known } = mapPapiStatus(p.paymentStatus);
298
+ const reference = typeof p.merchantPaymentReference === "string" ? p.merchantPaymentReference : "";
299
+ if (!known) this.onUnknownStatus?.(raw, providerReference);
300
+ return {
301
+ provider: PROVIDER2,
302
+ providerReference,
303
+ reference,
304
+ amount: p.amount,
305
+ currency: "MGA",
306
+ status,
307
+ paymentMethod: method,
308
+ rawProviderStatus: raw
309
+ };
310
+ }
311
+ async createPayment(request) {
312
+ const body = this.buildBody(request);
313
+ const send = () => papiRequest({
314
+ method: "POST",
315
+ url: `${this.baseUrl}/v1/payments`,
316
+ headers: this.headers({ "Idempotency-Key": request.idempotencyKey }),
317
+ body,
318
+ timeoutMs: this.timeoutMs,
319
+ fetchImpl: this.fetchImpl,
320
+ uncertainOnFailure: true
321
+ });
322
+ const payload = await core.executeWithRetry(send, {
323
+ maxRetries: this.maxCreationRetries,
324
+ initialDelayMs: this.retryInitialDelayMs,
325
+ shouldRetry: (e) => {
326
+ const code = e.code;
327
+ return code === "PROVIDER_TIMEOUT" || code === "PROVIDER_UNAVAILABLE";
328
+ }
329
+ });
330
+ return this.toProviderPayment(payload, request.paymentMethod);
331
+ }
332
+ async getPayment(lookupOrRef) {
333
+ const ref = typeof lookupOrRef === "string" ? lookupOrRef : lookupOrRef.providerReference;
334
+ if (!ref) {
335
+ throw new core.UnsupportedOperationError(
336
+ "Papi status lookup requires the provider paymentReference",
337
+ void 0,
338
+ PROVIDER2
339
+ );
340
+ }
341
+ const payload = await core.executeWithRetry(
342
+ () => papiRequest({
343
+ method: "GET",
344
+ url: `${this.baseUrl}/v1/payments/${encodeURIComponent(ref)}`,
345
+ headers: this.headers(),
346
+ timeoutMs: this.timeoutMs,
347
+ fetchImpl: this.fetchImpl
348
+ }),
349
+ {
350
+ maxRetries: 2,
351
+ initialDelayMs: this.retryInitialDelayMs,
352
+ shouldRetry: (e) => {
353
+ const code = e.code;
354
+ return code === "PROVIDER_TIMEOUT" || code === "PROVIDER_UNAVAILABLE";
355
+ }
356
+ }
357
+ );
358
+ return this.toProviderPayment(payload);
359
+ }
360
+ /** Verifies HMAC-SHA256 over the exact raw bytes, then parses. Nothing is parsed before verification. */
361
+ async verifyWebhook(request) {
362
+ if (!this.webhookSecret) {
363
+ throw new core.AuthenticationError("Papi webhookSecret is not configured", void 0, PROVIDER2);
364
+ }
365
+ if (!(request.rawBody instanceof Uint8Array)) {
366
+ throw new core.WebhookVerificationError("Webhook requires raw bytes", void 0, PROVIDER2);
367
+ }
368
+ const headerKey = Object.keys(request.headers).find(
369
+ (k) => k.toLowerCase() === "x-papi-signature"
370
+ );
371
+ const headerValue = headerKey ? request.headers[headerKey] : void 0;
372
+ const signature = Array.isArray(headerValue) ? headerValue[0] : headerValue;
373
+ if (typeof signature !== "string" || !/^[0-9a-fA-F]{64}$/.test(signature.trim())) {
374
+ throw new core.WebhookVerificationError(
375
+ "Missing or malformed X-Papi-Signature",
376
+ void 0,
377
+ PROVIDER2
378
+ );
379
+ }
380
+ const expected = crypto.createHmac("sha256", this.webhookSecret).update(request.rawBody).digest();
381
+ const received = Buffer.from(signature.trim(), "hex");
382
+ if (!crypto.timingSafeEqual(expected, received)) {
383
+ throw new core.WebhookVerificationError("Invalid webhook signature", void 0, PROVIDER2);
384
+ }
385
+ let payload;
386
+ try {
387
+ payload = asRecord(JSON.parse(Buffer.from(request.rawBody).toString("utf8")));
388
+ } catch {
389
+ throw new core.WebhookVerificationError("Webhook payload is not valid JSON", void 0, PROVIDER2);
390
+ }
391
+ if (typeof payload.eventId !== "string" || typeof payload.paymentReference !== "string" || typeof payload.occurredAt !== "string") {
392
+ throw new core.WebhookVerificationError(
393
+ "Webhook payload missing required fields",
394
+ void 0,
395
+ PROVIDER2
396
+ );
397
+ }
398
+ const raw = String(payload.paymentStatus);
399
+ const { status, known } = mapPapiStatus(payload.paymentStatus);
400
+ if (!known) this.onUnknownStatus?.(raw, payload.paymentReference);
401
+ return {
402
+ providerEventId: payload.eventId,
403
+ providerReference: payload.paymentReference,
404
+ reference: typeof payload.merchantPaymentReference === "string" ? payload.merchantPaymentReference : void 0,
405
+ status,
406
+ occurredAt: payload.occurredAt,
407
+ rawProviderStatus: raw,
408
+ environment: this.environment
409
+ };
410
+ }
411
+ };
412
+
413
+ exports.PAPI_BASE_URLS = PAPI_BASE_URLS;
414
+ exports.PapiPaymentProvider = PapiPaymentProvider;
415
+ exports.PapiProvider = PapiPaymentProvider;
416
+ exports.mapPapiStatus = mapPapiStatus;
417
+ //# sourceMappingURL=index.cjs.map
418
+ //# sourceMappingURL=index.cjs.map