local-lite 2.0.0 → 2.0.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/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/payments/adapters.d.ts +49 -0
- package/dist/payments/adapters.js +459 -0
- package/dist/payments/index.d.ts +3 -0
- package/dist/payments/index.js +19 -0
- package/dist/payments/registry.d.ts +18 -0
- package/dist/payments/registry.js +114 -0
- package/dist/payments/server.d.ts +19 -0
- package/dist/payments/server.js +235 -0
- package/dist/payments/types.d.ts +106 -0
- package/dist/payments/types.js +2 -0
- package/package.json +11 -1
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -44,3 +44,4 @@ __exportStar(require("./kv/index.js"), exports);
|
|
|
44
44
|
__exportStar(require("./search/index.js"), exports);
|
|
45
45
|
__exportStar(require("./storage/index.js"), exports);
|
|
46
46
|
__exportStar(require("./scheduler/index.js"), exports);
|
|
47
|
+
__exportStar(require("./payments/index.js"), exports);
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { PaymentProviderAdapter } from './types.js';
|
|
2
|
+
export declare function formatKenyanPhone(phone: string | number): string;
|
|
3
|
+
export interface ManualPaymentAdapterOptions {
|
|
4
|
+
id?: string;
|
|
5
|
+
label?: string;
|
|
6
|
+
description?: string;
|
|
7
|
+
supportedCurrencies?: string[] | '*';
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Offline-capable manual payment adapter (cash, bank transfer, cheque, etc.).
|
|
11
|
+
*/
|
|
12
|
+
export declare function createManualPaymentAdapter(options?: ManualPaymentAdapterOptions): PaymentProviderAdapter;
|
|
13
|
+
export interface DarajaAdapterOptions {
|
|
14
|
+
consumerKey: string;
|
|
15
|
+
consumerSecret: string;
|
|
16
|
+
shortcode: string;
|
|
17
|
+
passkey: string;
|
|
18
|
+
callbackUrl: string;
|
|
19
|
+
env?: 'sandbox' | 'live' | 'production';
|
|
20
|
+
apiUrl?: string;
|
|
21
|
+
partyB?: string;
|
|
22
|
+
transactionType?: string;
|
|
23
|
+
fetch?: typeof fetch;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Safaricom M-Pesa Daraja STK Push adapter (Kenya / KES).
|
|
27
|
+
*/
|
|
28
|
+
export declare function createDarajaAdapter(options: DarajaAdapterOptions): PaymentProviderAdapter;
|
|
29
|
+
export interface PaystackAdapterOptions {
|
|
30
|
+
secretKey: string;
|
|
31
|
+
supportedCurrencies?: string[];
|
|
32
|
+
supportedCountries?: string[] | '*';
|
|
33
|
+
fetch?: typeof fetch;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Paystack Checkout adapter (NGN, GHS, ZAR, KES, USD, etc.).
|
|
37
|
+
*/
|
|
38
|
+
export declare function createPaystackAdapter(options: PaystackAdapterOptions): PaymentProviderAdapter;
|
|
39
|
+
export interface StripeCheckoutAdapterOptions {
|
|
40
|
+
secretKey: string;
|
|
41
|
+
webhookSecret?: string;
|
|
42
|
+
supportedCurrencies?: string[] | '*';
|
|
43
|
+
supportedCountries?: string[] | '*';
|
|
44
|
+
fetch?: typeof fetch;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Stripe Checkout Session adapter for global card/wallet/bank payments.
|
|
48
|
+
*/
|
|
49
|
+
export declare function createStripeCheckoutAdapter(options: StripeCheckoutAdapterOptions): PaymentProviderAdapter;
|
|
@@ -0,0 +1,459 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.formatKenyanPhone = formatKenyanPhone;
|
|
4
|
+
exports.createManualPaymentAdapter = createManualPaymentAdapter;
|
|
5
|
+
exports.createDarajaAdapter = createDarajaAdapter;
|
|
6
|
+
exports.createPaystackAdapter = createPaystackAdapter;
|
|
7
|
+
exports.createStripeCheckoutAdapter = createStripeCheckoutAdapter;
|
|
8
|
+
function toBase64(value) {
|
|
9
|
+
if (typeof Buffer !== 'undefined') {
|
|
10
|
+
return Buffer.from(value, 'utf8').toString('base64');
|
|
11
|
+
}
|
|
12
|
+
if (typeof btoa === 'function') {
|
|
13
|
+
return btoa(value);
|
|
14
|
+
}
|
|
15
|
+
throw new Error('No base64 encoder available in this runtime.');
|
|
16
|
+
}
|
|
17
|
+
function timingSafeEqualHex(a, b) {
|
|
18
|
+
const left = a.trim().toLowerCase();
|
|
19
|
+
const right = b.trim().toLowerCase();
|
|
20
|
+
if (!left || left.length !== right.length)
|
|
21
|
+
return false;
|
|
22
|
+
let diff = 0;
|
|
23
|
+
for (let i = 0; i < left.length; i += 1) {
|
|
24
|
+
diff |= left.charCodeAt(i) ^ right.charCodeAt(i);
|
|
25
|
+
}
|
|
26
|
+
return diff === 0;
|
|
27
|
+
}
|
|
28
|
+
async function hmacHex(algorithm, secret, payload) {
|
|
29
|
+
const subtle = globalThis.crypto?.subtle;
|
|
30
|
+
if (!subtle) {
|
|
31
|
+
throw new Error('Web Crypto subtle API is required for webhook verification.');
|
|
32
|
+
}
|
|
33
|
+
const encoder = new TextEncoder();
|
|
34
|
+
const key = await subtle.importKey('raw', encoder.encode(secret), { name: 'HMAC', hash: algorithm }, false, ['sign']);
|
|
35
|
+
const sig = await subtle.sign('HMAC', key, encoder.encode(payload));
|
|
36
|
+
return Array.from(new Uint8Array(sig))
|
|
37
|
+
.map((b) => b.toString(16).padStart(2, '0'))
|
|
38
|
+
.join('');
|
|
39
|
+
}
|
|
40
|
+
function formatKenyanPhone(phone) {
|
|
41
|
+
if (!phone)
|
|
42
|
+
return '';
|
|
43
|
+
const cleaned = String(phone).replace(/[^\d]/g, '');
|
|
44
|
+
if (cleaned.startsWith('254'))
|
|
45
|
+
return cleaned;
|
|
46
|
+
if (cleaned.startsWith('0'))
|
|
47
|
+
return `254${cleaned.slice(1)}`;
|
|
48
|
+
if (cleaned.length === 9)
|
|
49
|
+
return `254${cleaned}`;
|
|
50
|
+
return cleaned;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Offline-capable manual payment adapter (cash, bank transfer, cheque, etc.).
|
|
54
|
+
*/
|
|
55
|
+
function createManualPaymentAdapter(options = {}) {
|
|
56
|
+
const id = options.id ?? 'manual';
|
|
57
|
+
return {
|
|
58
|
+
id,
|
|
59
|
+
label: options.label ?? 'Manual / Offline Payment',
|
|
60
|
+
description: options.description ??
|
|
61
|
+
'Record cash, bank transfer, or external payment offline.',
|
|
62
|
+
supportedCurrencies: options.supportedCurrencies ?? '*',
|
|
63
|
+
supportedCountries: '*',
|
|
64
|
+
requiresOnline: false,
|
|
65
|
+
async initiate(input) {
|
|
66
|
+
return {
|
|
67
|
+
success: true,
|
|
68
|
+
status: 'completed',
|
|
69
|
+
provider: id,
|
|
70
|
+
actionId: input.actionId,
|
|
71
|
+
providerRef: input.actionId,
|
|
72
|
+
customerMessage: 'Recorded locally.',
|
|
73
|
+
};
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Safaricom M-Pesa Daraja STK Push adapter (Kenya / KES).
|
|
79
|
+
*/
|
|
80
|
+
function createDarajaAdapter(options) {
|
|
81
|
+
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
82
|
+
const baseUrl = (options.apiUrl?.trim() ||
|
|
83
|
+
(options.env === 'live' || options.env === 'production'
|
|
84
|
+
? 'https://api.safaricom.co.ke'
|
|
85
|
+
: 'https://sandbox.safaricom.co.ke')).replace(/\/+$/, '');
|
|
86
|
+
return {
|
|
87
|
+
id: 'daraja',
|
|
88
|
+
label: 'M-Pesa (Safaricom Daraja)',
|
|
89
|
+
description: 'Instant STK Push prompt to a Kenyan M-Pesa number.',
|
|
90
|
+
supportedCurrencies: ['KES'],
|
|
91
|
+
supportedCountries: ['KE'],
|
|
92
|
+
requiresOnline: true,
|
|
93
|
+
async initiate(input) {
|
|
94
|
+
const phone = formatKenyanPhone(input.phone ?? '');
|
|
95
|
+
if (!/^254\d{9}$/.test(phone)) {
|
|
96
|
+
throw new Error('Valid Kenyan phone number (254XXXXXXXXX) is required.');
|
|
97
|
+
}
|
|
98
|
+
const amount = Math.round(input.amount);
|
|
99
|
+
if (!Number.isInteger(amount) || amount < 1 || amount > 250000) {
|
|
100
|
+
throw new Error('M-Pesa amount must be an integer between 1 and 250000.');
|
|
101
|
+
}
|
|
102
|
+
const callbackUrl = (input.callbackUrl ?? options.callbackUrl).trim();
|
|
103
|
+
if (!callbackUrl.startsWith('https://')) {
|
|
104
|
+
throw new Error('Daraja callbackUrl must use HTTPS.');
|
|
105
|
+
}
|
|
106
|
+
const authHeader = `Basic ${toBase64(`${options.consumerKey}:${options.consumerSecret}`)}`;
|
|
107
|
+
const oauthRes = await fetchImpl(`${baseUrl}/oauth/v1/generate?grant_type=client_credentials`, {
|
|
108
|
+
method: 'GET',
|
|
109
|
+
headers: { Authorization: authHeader },
|
|
110
|
+
});
|
|
111
|
+
if (!oauthRes.ok) {
|
|
112
|
+
const text = await oauthRes.text();
|
|
113
|
+
throw new Error(`Daraja OAuth failed (${oauthRes.status}): ${text}`);
|
|
114
|
+
}
|
|
115
|
+
const oauthJson = await oauthRes.json();
|
|
116
|
+
const accessToken = oauthJson?.access_token;
|
|
117
|
+
if (!accessToken) {
|
|
118
|
+
throw new Error('Daraja OAuth did not return an access_token.');
|
|
119
|
+
}
|
|
120
|
+
const timestamp = new Date(Date.now() + 3 * 3600000)
|
|
121
|
+
.toISOString()
|
|
122
|
+
.replace(/[-:TZ.]/g, '')
|
|
123
|
+
.slice(0, 14);
|
|
124
|
+
const password = toBase64(`${options.shortcode}${options.passkey}${timestamp}`);
|
|
125
|
+
const stkRes = await fetchImpl(`${baseUrl}/mpesa/stkpush/v1/processrequest`, {
|
|
126
|
+
method: 'POST',
|
|
127
|
+
headers: {
|
|
128
|
+
Authorization: `Bearer ${accessToken}`,
|
|
129
|
+
'Content-Type': 'application/json',
|
|
130
|
+
},
|
|
131
|
+
body: JSON.stringify({
|
|
132
|
+
BusinessShortCode: options.shortcode,
|
|
133
|
+
Password: password,
|
|
134
|
+
Timestamp: timestamp,
|
|
135
|
+
TransactionType: options.transactionType?.trim() || 'CustomerPayBillOnline',
|
|
136
|
+
Amount: amount,
|
|
137
|
+
PartyA: phone,
|
|
138
|
+
PartyB: options.partyB?.trim() || options.shortcode,
|
|
139
|
+
PhoneNumber: phone,
|
|
140
|
+
CallBackURL: callbackUrl,
|
|
141
|
+
AccountReference: (input.contractId || input.actionId).slice(0, 12),
|
|
142
|
+
TransactionDesc: input.description || 'Payment',
|
|
143
|
+
}),
|
|
144
|
+
});
|
|
145
|
+
const data = await stkRes.json();
|
|
146
|
+
if (!stkRes.ok ||
|
|
147
|
+
data?.ResponseCode !== '0' ||
|
|
148
|
+
!data?.CheckoutRequestID ||
|
|
149
|
+
!data?.MerchantRequestID) {
|
|
150
|
+
throw new Error(data?.errorMessage ||
|
|
151
|
+
data?.ResponseDescription ||
|
|
152
|
+
'Daraja did not confirm payment initiation.');
|
|
153
|
+
}
|
|
154
|
+
return {
|
|
155
|
+
success: true,
|
|
156
|
+
status: 'pending',
|
|
157
|
+
provider: 'daraja',
|
|
158
|
+
actionId: input.actionId,
|
|
159
|
+
providerRef: data.CheckoutRequestID,
|
|
160
|
+
merchantRequestId: data.MerchantRequestID,
|
|
161
|
+
customerMessage: data.CustomerMessage || '',
|
|
162
|
+
raw: data,
|
|
163
|
+
};
|
|
164
|
+
},
|
|
165
|
+
async verifyWebhook(request) {
|
|
166
|
+
const payload = await request.json();
|
|
167
|
+
const callback = payload?.Body?.stkCallback;
|
|
168
|
+
if (!callback || !Number.isInteger(callback.ResultCode)) {
|
|
169
|
+
return {
|
|
170
|
+
verified: false,
|
|
171
|
+
status: 'failed',
|
|
172
|
+
error: 'Invalid Daraja callback payload.',
|
|
173
|
+
rawPayload: payload,
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
if (callback.ResultCode !== 0) {
|
|
177
|
+
return {
|
|
178
|
+
verified: true,
|
|
179
|
+
providerRef: callback.CheckoutRequestID,
|
|
180
|
+
merchantRequestId: callback.MerchantRequestID,
|
|
181
|
+
status: 'failed',
|
|
182
|
+
error: String(callback.ResultDesc || 'Payment failed'),
|
|
183
|
+
rawPayload: callback,
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
const items = callback.CallbackMetadata?.Item;
|
|
187
|
+
if (!Array.isArray(items)) {
|
|
188
|
+
return {
|
|
189
|
+
verified: false,
|
|
190
|
+
providerRef: callback.CheckoutRequestID,
|
|
191
|
+
merchantRequestId: callback.MerchantRequestID,
|
|
192
|
+
status: 'failed',
|
|
193
|
+
error: 'Missing Daraja callback metadata.',
|
|
194
|
+
rawPayload: callback,
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
const readItem = (name) => items.find((entry) => entry?.Name === name)?.Value;
|
|
198
|
+
const receipt = readItem('MpesaReceiptNumber');
|
|
199
|
+
const amount = Number(readItem('Amount'));
|
|
200
|
+
const phone = String(readItem('PhoneNumber') ?? '');
|
|
201
|
+
if (typeof receipt !== 'string' || !receipt || !Number.isFinite(amount)) {
|
|
202
|
+
return {
|
|
203
|
+
verified: false,
|
|
204
|
+
providerRef: callback.CheckoutRequestID,
|
|
205
|
+
merchantRequestId: callback.MerchantRequestID,
|
|
206
|
+
status: 'failed',
|
|
207
|
+
error: 'Incomplete Daraja callback metadata.',
|
|
208
|
+
rawPayload: callback,
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
return {
|
|
212
|
+
verified: true,
|
|
213
|
+
providerRef: callback.CheckoutRequestID,
|
|
214
|
+
merchantRequestId: callback.MerchantRequestID,
|
|
215
|
+
receiptNumber: receipt,
|
|
216
|
+
amount,
|
|
217
|
+
currency: 'KES',
|
|
218
|
+
phone,
|
|
219
|
+
status: 'completed',
|
|
220
|
+
rawPayload: callback,
|
|
221
|
+
};
|
|
222
|
+
},
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Paystack Checkout adapter (NGN, GHS, ZAR, KES, USD, etc.).
|
|
227
|
+
*/
|
|
228
|
+
function createPaystackAdapter(options) {
|
|
229
|
+
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
230
|
+
return {
|
|
231
|
+
id: 'paystack',
|
|
232
|
+
label: 'Paystack (Card / Bank / Mobile Money)',
|
|
233
|
+
description: 'Hosted checkout for cards, bank transfers, and mobile money.',
|
|
234
|
+
supportedCurrencies: options.supportedCurrencies ?? [
|
|
235
|
+
'NGN',
|
|
236
|
+
'GHS',
|
|
237
|
+
'ZAR',
|
|
238
|
+
'KES',
|
|
239
|
+
'USD',
|
|
240
|
+
],
|
|
241
|
+
supportedCountries: options.supportedCountries ?? '*',
|
|
242
|
+
requiresOnline: true,
|
|
243
|
+
async initiate(input) {
|
|
244
|
+
if (!input.email) {
|
|
245
|
+
throw new Error('Customer email is required for Paystack payments.');
|
|
246
|
+
}
|
|
247
|
+
const res = await fetchImpl('https://api.paystack.co/transaction/initialize', {
|
|
248
|
+
method: 'POST',
|
|
249
|
+
headers: {
|
|
250
|
+
Authorization: `Bearer ${options.secretKey}`,
|
|
251
|
+
'Content-Type': 'application/json',
|
|
252
|
+
},
|
|
253
|
+
body: JSON.stringify({
|
|
254
|
+
email: input.email,
|
|
255
|
+
amount: Math.round(input.amount * 100),
|
|
256
|
+
currency: input.currency,
|
|
257
|
+
reference: input.actionId,
|
|
258
|
+
callback_url: input.returnUrl || input.callbackUrl,
|
|
259
|
+
metadata: input.metadata,
|
|
260
|
+
}),
|
|
261
|
+
});
|
|
262
|
+
const data = await res.json();
|
|
263
|
+
if (!res.ok || !data?.status || !data?.data?.authorization_url) {
|
|
264
|
+
throw new Error(data?.message || 'Paystack did not confirm payment initialization.');
|
|
265
|
+
}
|
|
266
|
+
return {
|
|
267
|
+
success: true,
|
|
268
|
+
status: 'pending',
|
|
269
|
+
provider: 'paystack',
|
|
270
|
+
actionId: input.actionId,
|
|
271
|
+
providerRef: data.data.reference || input.actionId,
|
|
272
|
+
checkoutUrl: data.data.authorization_url,
|
|
273
|
+
raw: data,
|
|
274
|
+
};
|
|
275
|
+
},
|
|
276
|
+
async verifyWebhook(request, context) {
|
|
277
|
+
const signature = request.headers.get('x-paystack-signature') || '';
|
|
278
|
+
const rawBody = context?.rawBody ?? (await request.text());
|
|
279
|
+
if (!signature || !rawBody) {
|
|
280
|
+
return {
|
|
281
|
+
verified: false,
|
|
282
|
+
status: 'failed',
|
|
283
|
+
error: 'Missing Paystack signature or payload.',
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
const expected = await hmacHex('SHA-512', options.secretKey, rawBody);
|
|
287
|
+
if (!timingSafeEqualHex(signature, expected)) {
|
|
288
|
+
return {
|
|
289
|
+
verified: false,
|
|
290
|
+
status: 'failed',
|
|
291
|
+
error: 'Invalid Paystack webhook signature.',
|
|
292
|
+
};
|
|
293
|
+
}
|
|
294
|
+
const event = JSON.parse(rawBody);
|
|
295
|
+
const data = event?.data || {};
|
|
296
|
+
const eventName = String(event?.event || '');
|
|
297
|
+
if (eventName === 'charge.success') {
|
|
298
|
+
return {
|
|
299
|
+
verified: true,
|
|
300
|
+
actionId: data.reference,
|
|
301
|
+
providerRef: data.reference,
|
|
302
|
+
receiptNumber: String(data.id || data.reference || ''),
|
|
303
|
+
amount: typeof data.amount === 'number' ? data.amount / 100 : undefined,
|
|
304
|
+
currency: data.currency ? String(data.currency).toUpperCase() : undefined,
|
|
305
|
+
status: 'completed',
|
|
306
|
+
rawPayload: event,
|
|
307
|
+
};
|
|
308
|
+
}
|
|
309
|
+
if (eventName === 'charge.failed') {
|
|
310
|
+
return {
|
|
311
|
+
verified: true,
|
|
312
|
+
actionId: data.reference,
|
|
313
|
+
providerRef: data.reference,
|
|
314
|
+
status: 'failed',
|
|
315
|
+
error: String(data.gateway_response || 'Paystack charge failed.'),
|
|
316
|
+
rawPayload: event,
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
return {
|
|
320
|
+
verified: true,
|
|
321
|
+
actionId: data.reference,
|
|
322
|
+
providerRef: data.reference,
|
|
323
|
+
status: 'pending',
|
|
324
|
+
rawPayload: event,
|
|
325
|
+
};
|
|
326
|
+
},
|
|
327
|
+
};
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* Stripe Checkout Session adapter for global card/wallet/bank payments.
|
|
331
|
+
*/
|
|
332
|
+
function createStripeCheckoutAdapter(options) {
|
|
333
|
+
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
334
|
+
return {
|
|
335
|
+
id: 'stripe',
|
|
336
|
+
label: 'Stripe (Card / Apple Pay / Google Pay)',
|
|
337
|
+
description: 'Global card and digital wallet checkout via Stripe.',
|
|
338
|
+
supportedCurrencies: options.supportedCurrencies ?? '*',
|
|
339
|
+
supportedCountries: options.supportedCountries ?? '*',
|
|
340
|
+
requiresOnline: true,
|
|
341
|
+
async initiate(input) {
|
|
342
|
+
if (!input.returnUrl) {
|
|
343
|
+
throw new Error('returnUrl is required for Stripe Checkout sessions.');
|
|
344
|
+
}
|
|
345
|
+
const params = new URLSearchParams({
|
|
346
|
+
mode: 'payment',
|
|
347
|
+
success_url: input.returnUrl,
|
|
348
|
+
cancel_url: input.returnUrl,
|
|
349
|
+
client_reference_id: input.actionId,
|
|
350
|
+
'line_items[0][price_data][currency]': input.currency.toLowerCase(),
|
|
351
|
+
'line_items[0][price_data][product_data][name]': input.description || 'Payment',
|
|
352
|
+
'line_items[0][price_data][unit_amount]': String(Math.round(input.amount * 100)),
|
|
353
|
+
'line_items[0][quantity]': '1',
|
|
354
|
+
});
|
|
355
|
+
if (input.email) {
|
|
356
|
+
params.set('customer_email', input.email);
|
|
357
|
+
}
|
|
358
|
+
const res = await fetchImpl('https://api.stripe.com/v1/checkout/sessions', {
|
|
359
|
+
method: 'POST',
|
|
360
|
+
headers: {
|
|
361
|
+
Authorization: `Bearer ${options.secretKey}`,
|
|
362
|
+
'Content-Type': 'application/x-www-form-urlencoded',
|
|
363
|
+
},
|
|
364
|
+
body: params.toString(),
|
|
365
|
+
});
|
|
366
|
+
const data = await res.json();
|
|
367
|
+
if (!res.ok || !data?.id || !data?.url) {
|
|
368
|
+
throw new Error(data?.error?.message || 'Stripe did not create a checkout session.');
|
|
369
|
+
}
|
|
370
|
+
return {
|
|
371
|
+
success: true,
|
|
372
|
+
status: 'pending',
|
|
373
|
+
provider: 'stripe',
|
|
374
|
+
actionId: input.actionId,
|
|
375
|
+
providerRef: data.id,
|
|
376
|
+
checkoutUrl: data.url,
|
|
377
|
+
raw: data,
|
|
378
|
+
};
|
|
379
|
+
},
|
|
380
|
+
async verifyWebhook(request, context) {
|
|
381
|
+
if (!options.webhookSecret) {
|
|
382
|
+
return {
|
|
383
|
+
verified: false,
|
|
384
|
+
status: 'failed',
|
|
385
|
+
error: 'Stripe webhookSecret is not configured.',
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
const header = request.headers.get('stripe-signature') || '';
|
|
389
|
+
const rawBody = context?.rawBody ?? (await request.text());
|
|
390
|
+
const parts = Object.fromEntries(header.split(',').map((part) => {
|
|
391
|
+
const [k, v] = part.split('=');
|
|
392
|
+
return [k?.trim(), v?.trim()];
|
|
393
|
+
}));
|
|
394
|
+
const timestamp = parts.t;
|
|
395
|
+
const v1 = parts.v1;
|
|
396
|
+
if (!timestamp || !v1 || !rawBody) {
|
|
397
|
+
return {
|
|
398
|
+
verified: false,
|
|
399
|
+
status: 'failed',
|
|
400
|
+
error: 'Missing Stripe signature or payload.',
|
|
401
|
+
};
|
|
402
|
+
}
|
|
403
|
+
const ageSeconds = Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp));
|
|
404
|
+
if (!Number.isFinite(ageSeconds) || ageSeconds > 300) {
|
|
405
|
+
return {
|
|
406
|
+
verified: false,
|
|
407
|
+
status: 'failed',
|
|
408
|
+
error: 'Stripe webhook timestamp is outside tolerance.',
|
|
409
|
+
};
|
|
410
|
+
}
|
|
411
|
+
const expected = await hmacHex('SHA-256', options.webhookSecret, `${timestamp}.${rawBody}`);
|
|
412
|
+
if (!timingSafeEqualHex(v1, expected)) {
|
|
413
|
+
return {
|
|
414
|
+
verified: false,
|
|
415
|
+
status: 'failed',
|
|
416
|
+
error: 'Invalid Stripe webhook signature.',
|
|
417
|
+
};
|
|
418
|
+
}
|
|
419
|
+
const event = JSON.parse(rawBody);
|
|
420
|
+
const session = event?.data?.object || {};
|
|
421
|
+
const eventType = String(event?.type || '');
|
|
422
|
+
if (eventType === 'checkout.session.completed' ||
|
|
423
|
+
eventType === 'checkout.session.async_payment_succeeded') {
|
|
424
|
+
return {
|
|
425
|
+
verified: true,
|
|
426
|
+
actionId: session.client_reference_id,
|
|
427
|
+
providerRef: session.id,
|
|
428
|
+
receiptNumber: String(session.payment_intent || session.id || ''),
|
|
429
|
+
amount: typeof session.amount_total === 'number'
|
|
430
|
+
? session.amount_total / 100
|
|
431
|
+
: undefined,
|
|
432
|
+
currency: session.currency
|
|
433
|
+
? String(session.currency).toUpperCase()
|
|
434
|
+
: undefined,
|
|
435
|
+
status: 'completed',
|
|
436
|
+
rawPayload: event,
|
|
437
|
+
};
|
|
438
|
+
}
|
|
439
|
+
if (eventType === 'checkout.session.expired' ||
|
|
440
|
+
eventType === 'checkout.session.async_payment_failed') {
|
|
441
|
+
return {
|
|
442
|
+
verified: true,
|
|
443
|
+
actionId: session.client_reference_id,
|
|
444
|
+
providerRef: session.id,
|
|
445
|
+
status: 'failed',
|
|
446
|
+
error: 'Stripe checkout failed or expired.',
|
|
447
|
+
rawPayload: event,
|
|
448
|
+
};
|
|
449
|
+
}
|
|
450
|
+
return {
|
|
451
|
+
verified: true,
|
|
452
|
+
actionId: session.client_reference_id,
|
|
453
|
+
providerRef: session.id,
|
|
454
|
+
status: 'pending',
|
|
455
|
+
rawPayload: event,
|
|
456
|
+
};
|
|
457
|
+
},
|
|
458
|
+
};
|
|
459
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
__exportStar(require("./types.js"), exports);
|
|
18
|
+
__exportStar(require("./registry.js"), exports);
|
|
19
|
+
__exportStar(require("./adapters.js"), exports);
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { PaymentContext, PaymentInitiateInput, PaymentInitiateResult, PaymentMethodOption, PaymentProviderAdapter, PaymentProviderId, PaymentRegistryConfig } from './types.js';
|
|
2
|
+
export interface PaymentRegistry {
|
|
3
|
+
register: (adapter: PaymentProviderAdapter) => void;
|
|
4
|
+
unregister: (id: PaymentProviderId) => boolean;
|
|
5
|
+
configure: (config: Pick<PaymentRegistryConfig, 'enabledProviders' | 'defaultCurrency'>) => void;
|
|
6
|
+
getProvider: (id: PaymentProviderId) => PaymentProviderAdapter | undefined;
|
|
7
|
+
listProviders: () => PaymentProviderAdapter[];
|
|
8
|
+
supports: (id: PaymentProviderId, context?: PaymentContext) => boolean;
|
|
9
|
+
getAvailableOptions: (context?: PaymentContext) => PaymentMethodOption[];
|
|
10
|
+
initiate: (input: Omit<PaymentInitiateInput, 'currency'> & {
|
|
11
|
+
currency?: string;
|
|
12
|
+
}) => Promise<PaymentInitiateResult>;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Creates a configurable payment provider registry that filters available
|
|
16
|
+
* payment methods by currency, country, online status, and enabled provider list.
|
|
17
|
+
*/
|
|
18
|
+
export declare function createPaymentRegistry(initialConfig?: PaymentRegistryConfig): PaymentRegistry;
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createPaymentRegistry = createPaymentRegistry;
|
|
4
|
+
function normalizeCode(value) {
|
|
5
|
+
return String(value ?? '')
|
|
6
|
+
.trim()
|
|
7
|
+
.toUpperCase();
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Creates a configurable payment provider registry that filters available
|
|
11
|
+
* payment methods by currency, country, online status, and enabled provider list.
|
|
12
|
+
*/
|
|
13
|
+
function createPaymentRegistry(initialConfig = {}) {
|
|
14
|
+
const providers = new Map();
|
|
15
|
+
let enabledProviders = initialConfig.enabledProviders
|
|
16
|
+
? new Set(initialConfig.enabledProviders)
|
|
17
|
+
: null;
|
|
18
|
+
let defaultCurrency = initialConfig.defaultCurrency
|
|
19
|
+
? normalizeCode(initialConfig.defaultCurrency)
|
|
20
|
+
: 'USD';
|
|
21
|
+
for (const adapter of initialConfig.providers ?? []) {
|
|
22
|
+
providers.set(adapter.id, adapter);
|
|
23
|
+
}
|
|
24
|
+
function supports(id, context = {}) {
|
|
25
|
+
const adapter = providers.get(id);
|
|
26
|
+
if (!adapter)
|
|
27
|
+
return false;
|
|
28
|
+
const allowedList = context.enabledProviders ?? (enabledProviders ? [...enabledProviders] : null);
|
|
29
|
+
if (allowedList && !allowedList.includes(id)) {
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
32
|
+
const requiresOnline = adapter.requiresOnline ?? true;
|
|
33
|
+
if (requiresOnline && context.isOnline === false) {
|
|
34
|
+
return false;
|
|
35
|
+
}
|
|
36
|
+
const currency = normalizeCode(context.currency ?? defaultCurrency);
|
|
37
|
+
if (currency &&
|
|
38
|
+
adapter.supportedCurrencies !== '*' &&
|
|
39
|
+
!adapter.supportedCurrencies.map(normalizeCode).includes(currency)) {
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
const country = normalizeCode(context.country);
|
|
43
|
+
if (country &&
|
|
44
|
+
adapter.supportedCountries &&
|
|
45
|
+
adapter.supportedCountries !== '*' &&
|
|
46
|
+
!adapter.supportedCountries.map(normalizeCode).includes(country)) {
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
if (adapter.supports && !adapter.supports(context)) {
|
|
50
|
+
return false;
|
|
51
|
+
}
|
|
52
|
+
return true;
|
|
53
|
+
}
|
|
54
|
+
return {
|
|
55
|
+
register(adapter) {
|
|
56
|
+
providers.set(adapter.id, adapter);
|
|
57
|
+
},
|
|
58
|
+
unregister(id) {
|
|
59
|
+
return providers.delete(id);
|
|
60
|
+
},
|
|
61
|
+
configure(config) {
|
|
62
|
+
if (config.enabledProviders !== undefined) {
|
|
63
|
+
enabledProviders = config.enabledProviders
|
|
64
|
+
? new Set(config.enabledProviders)
|
|
65
|
+
: null;
|
|
66
|
+
}
|
|
67
|
+
if (config.defaultCurrency !== undefined) {
|
|
68
|
+
defaultCurrency = normalizeCode(config.defaultCurrency) || defaultCurrency;
|
|
69
|
+
}
|
|
70
|
+
},
|
|
71
|
+
getProvider(id) {
|
|
72
|
+
return providers.get(id);
|
|
73
|
+
},
|
|
74
|
+
listProviders() {
|
|
75
|
+
return [...providers.values()];
|
|
76
|
+
},
|
|
77
|
+
supports,
|
|
78
|
+
getAvailableOptions(context = {}) {
|
|
79
|
+
return [...providers.values()]
|
|
80
|
+
.filter((adapter) => supports(adapter.id, context))
|
|
81
|
+
.map((adapter) => ({
|
|
82
|
+
id: adapter.id,
|
|
83
|
+
label: adapter.label,
|
|
84
|
+
description: adapter.description,
|
|
85
|
+
supportedCurrencies: adapter.supportedCurrencies,
|
|
86
|
+
supportedCountries: adapter.supportedCountries,
|
|
87
|
+
requiresOnline: adapter.requiresOnline ?? true,
|
|
88
|
+
}));
|
|
89
|
+
},
|
|
90
|
+
async initiate(input) {
|
|
91
|
+
const adapter = providers.get(input.provider);
|
|
92
|
+
if (!adapter) {
|
|
93
|
+
throw new Error(`Payment provider "${input.provider}" is not registered.`);
|
|
94
|
+
}
|
|
95
|
+
const currency = normalizeCode(input.currency ?? defaultCurrency);
|
|
96
|
+
if (!currency) {
|
|
97
|
+
throw new Error('Payment currency is required.');
|
|
98
|
+
}
|
|
99
|
+
if (!Number.isFinite(input.amount) || input.amount <= 0) {
|
|
100
|
+
throw new Error('Payment amount must be greater than zero.');
|
|
101
|
+
}
|
|
102
|
+
if (!input.actionId || typeof input.actionId !== 'string') {
|
|
103
|
+
throw new Error('Payment actionId is required.');
|
|
104
|
+
}
|
|
105
|
+
if (!supports(adapter.id, { currency })) {
|
|
106
|
+
throw new Error(`Payment provider "${adapter.id}" does not support currency "${currency}".`);
|
|
107
|
+
}
|
|
108
|
+
return adapter.initiate({
|
|
109
|
+
...input,
|
|
110
|
+
currency,
|
|
111
|
+
});
|
|
112
|
+
},
|
|
113
|
+
};
|
|
114
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { PaymentRegistry } from './registry.js';
|
|
2
|
+
import type { PaymentReservationRecord, PaymentReservationStore, PaymentWebhookResult } from './types.js';
|
|
3
|
+
export declare function sha256Hex(value: string): string;
|
|
4
|
+
export declare function createCallbackToken(): string;
|
|
5
|
+
/**
|
|
6
|
+
* In-memory PaymentReservationStore useful for testing and prototypes.
|
|
7
|
+
*/
|
|
8
|
+
export declare function createMemoryPaymentStore(): PaymentReservationStore;
|
|
9
|
+
export interface PaymentServerHandlerOptions {
|
|
10
|
+
registry: PaymentRegistry;
|
|
11
|
+
store: PaymentReservationStore;
|
|
12
|
+
callbackBaseUrl?: string;
|
|
13
|
+
onCompleted?: (reservation: PaymentReservationRecord, webhook: PaymentWebhookResult) => Promise<void>;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Creates a framework-agnostic Fetch Request handler for idempotent payment
|
|
17
|
+
* initiation and webhook/callback verification across registered providers.
|
|
18
|
+
*/
|
|
19
|
+
export declare function createPaymentServerHandler(options: PaymentServerHandlerOptions): (request: Request) => Promise<Response>;
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.sha256Hex = sha256Hex;
|
|
7
|
+
exports.createCallbackToken = createCallbackToken;
|
|
8
|
+
exports.createMemoryPaymentStore = createMemoryPaymentStore;
|
|
9
|
+
exports.createPaymentServerHandler = createPaymentServerHandler;
|
|
10
|
+
const node_crypto_1 = __importDefault(require("node:crypto"));
|
|
11
|
+
function sha256Hex(value) {
|
|
12
|
+
return node_crypto_1.default.createHash('sha256').update(value).digest('hex');
|
|
13
|
+
}
|
|
14
|
+
function createCallbackToken() {
|
|
15
|
+
return node_crypto_1.default.randomBytes(32).toString('hex');
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* In-memory PaymentReservationStore useful for testing and prototypes.
|
|
19
|
+
*/
|
|
20
|
+
function createMemoryPaymentStore() {
|
|
21
|
+
const byActionId = new Map();
|
|
22
|
+
return {
|
|
23
|
+
async findByActionId(actionId) {
|
|
24
|
+
return byActionId.get(actionId) ?? null;
|
|
25
|
+
},
|
|
26
|
+
async findByCallbackHash(callbackHash) {
|
|
27
|
+
for (const record of byActionId.values()) {
|
|
28
|
+
if (record.callbackHash === callbackHash)
|
|
29
|
+
return record;
|
|
30
|
+
}
|
|
31
|
+
return null;
|
|
32
|
+
},
|
|
33
|
+
async findByProviderRef(providerRef) {
|
|
34
|
+
for (const record of byActionId.values()) {
|
|
35
|
+
if (record.providerRef === providerRef)
|
|
36
|
+
return record;
|
|
37
|
+
}
|
|
38
|
+
return null;
|
|
39
|
+
},
|
|
40
|
+
async reserve(record) {
|
|
41
|
+
if (byActionId.has(record.actionId)) {
|
|
42
|
+
throw new Error(`Action ID "${record.actionId}" is already reserved.`);
|
|
43
|
+
}
|
|
44
|
+
byActionId.set(record.actionId, { ...record });
|
|
45
|
+
},
|
|
46
|
+
async markPending(actionId, update) {
|
|
47
|
+
const existing = byActionId.get(actionId);
|
|
48
|
+
if (!existing)
|
|
49
|
+
return;
|
|
50
|
+
byActionId.set(actionId, {
|
|
51
|
+
...existing,
|
|
52
|
+
status: 'pending',
|
|
53
|
+
providerRef: update.providerRef ?? existing.providerRef,
|
|
54
|
+
merchantRequestId: update.merchantRequestId ?? existing.merchantRequestId,
|
|
55
|
+
customerMessage: update.customerMessage ?? existing.customerMessage,
|
|
56
|
+
});
|
|
57
|
+
},
|
|
58
|
+
async markFinal(actionId, status, error = null) {
|
|
59
|
+
const existing = byActionId.get(actionId);
|
|
60
|
+
if (!existing)
|
|
61
|
+
return;
|
|
62
|
+
byActionId.set(actionId, {
|
|
63
|
+
...existing,
|
|
64
|
+
status,
|
|
65
|
+
error,
|
|
66
|
+
});
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Creates a framework-agnostic Fetch Request handler for idempotent payment
|
|
72
|
+
* initiation and webhook/callback verification across registered providers.
|
|
73
|
+
*/
|
|
74
|
+
function createPaymentServerHandler(options) {
|
|
75
|
+
const { registry, store, callbackBaseUrl, onCompleted } = options;
|
|
76
|
+
async function handleInitiate(request) {
|
|
77
|
+
const body = await request.json();
|
|
78
|
+
const actionId = body?.actionId;
|
|
79
|
+
const provider = body?.provider || 'daraja';
|
|
80
|
+
const amount = Number(body?.amount);
|
|
81
|
+
const currency = String(body?.currency || '').trim().toUpperCase();
|
|
82
|
+
if (typeof actionId !== 'string' ||
|
|
83
|
+
!actionId ||
|
|
84
|
+
actionId.length > 128 ||
|
|
85
|
+
!Number.isFinite(amount) ||
|
|
86
|
+
amount <= 0 ||
|
|
87
|
+
!currency) {
|
|
88
|
+
return Response.json({ error: 'Valid actionId, provider, currency, and amount are required.' }, { status: 400 });
|
|
89
|
+
}
|
|
90
|
+
if (!registry.supports(provider, { currency, isOnline: true })) {
|
|
91
|
+
return Response.json({ error: `Provider "${provider}" is not enabled for ${currency}.` }, { status: 400 });
|
|
92
|
+
}
|
|
93
|
+
const existing = await store.findByActionId(actionId);
|
|
94
|
+
if (existing) {
|
|
95
|
+
if (existing.provider !== provider ||
|
|
96
|
+
existing.currency !== currency ||
|
|
97
|
+
Number(existing.amount) !== amount) {
|
|
98
|
+
return Response.json({ error: 'Action ID is already in use.' }, { status: 409 });
|
|
99
|
+
}
|
|
100
|
+
if (!existing.providerRef && existing.status !== 'completed') {
|
|
101
|
+
return Response.json({ error: 'Payment is already reserved. Reconcile before retrying.' }, { status: 409 });
|
|
102
|
+
}
|
|
103
|
+
return Response.json({
|
|
104
|
+
success: true,
|
|
105
|
+
duplicate: true,
|
|
106
|
+
status: existing.status,
|
|
107
|
+
provider: existing.provider,
|
|
108
|
+
providerRef: existing.providerRef,
|
|
109
|
+
merchantRequestId: existing.merchantRequestId,
|
|
110
|
+
customerMessage: existing.customerMessage,
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
const callbackToken = createCallbackToken();
|
|
114
|
+
const callbackUrl = callbackBaseUrl
|
|
115
|
+
? (() => {
|
|
116
|
+
const url = new URL(callbackBaseUrl);
|
|
117
|
+
url.searchParams.set('callback_token', callbackToken);
|
|
118
|
+
url.searchParams.set('provider', provider);
|
|
119
|
+
return url.toString();
|
|
120
|
+
})()
|
|
121
|
+
: body?.callbackUrl;
|
|
122
|
+
await store.reserve({
|
|
123
|
+
actionId,
|
|
124
|
+
provider,
|
|
125
|
+
currency,
|
|
126
|
+
amount,
|
|
127
|
+
businessId: body?.businessId,
|
|
128
|
+
userId: body?.userId,
|
|
129
|
+
tenantId: body?.tenantId,
|
|
130
|
+
contractId: body?.contractId,
|
|
131
|
+
phone: body?.phone,
|
|
132
|
+
email: body?.email,
|
|
133
|
+
callbackHash: sha256Hex(callbackToken),
|
|
134
|
+
status: 'initializing',
|
|
135
|
+
metadata: body?.metadata,
|
|
136
|
+
});
|
|
137
|
+
try {
|
|
138
|
+
const input = {
|
|
139
|
+
actionId,
|
|
140
|
+
provider,
|
|
141
|
+
amount,
|
|
142
|
+
currency,
|
|
143
|
+
businessId: body?.businessId,
|
|
144
|
+
tenantId: body?.tenantId,
|
|
145
|
+
contractId: body?.contractId,
|
|
146
|
+
userId: body?.userId,
|
|
147
|
+
phone: body?.phone,
|
|
148
|
+
email: body?.email,
|
|
149
|
+
callbackUrl,
|
|
150
|
+
returnUrl: body?.returnUrl,
|
|
151
|
+
description: body?.description,
|
|
152
|
+
metadata: body?.metadata,
|
|
153
|
+
};
|
|
154
|
+
const result = await registry.initiate(input);
|
|
155
|
+
if (result.status === 'completed') {
|
|
156
|
+
await store.markFinal(actionId, 'completed', null);
|
|
157
|
+
}
|
|
158
|
+
else {
|
|
159
|
+
await store.markPending(actionId, {
|
|
160
|
+
providerRef: result.providerRef,
|
|
161
|
+
merchantRequestId: result.merchantRequestId,
|
|
162
|
+
customerMessage: result.customerMessage,
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
return Response.json(result);
|
|
166
|
+
}
|
|
167
|
+
catch (error) {
|
|
168
|
+
await store
|
|
169
|
+
.markFinal(actionId, 'failed', error instanceof Error ? error.message : 'Initiation failed')
|
|
170
|
+
.catch(() => { });
|
|
171
|
+
return Response.json({
|
|
172
|
+
error: error instanceof Error
|
|
173
|
+
? error.message
|
|
174
|
+
: 'Payment initiation failed.',
|
|
175
|
+
}, { status: 502 });
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
async function handleCallback(request) {
|
|
179
|
+
const url = new URL(request.url);
|
|
180
|
+
const token = url.searchParams.get('callback_token');
|
|
181
|
+
let reservation = null;
|
|
182
|
+
if (token && /^[a-f0-9]{64}$/.test(token) && store.findByCallbackHash) {
|
|
183
|
+
reservation = await store.findByCallbackHash(sha256Hex(token));
|
|
184
|
+
}
|
|
185
|
+
const providerId = url.searchParams.get('provider') || reservation?.provider || 'daraja';
|
|
186
|
+
const adapter = registry.getProvider(providerId);
|
|
187
|
+
if (!adapter?.verifyWebhook) {
|
|
188
|
+
return Response.json({ error: 'Unsupported payment callback provider.' }, { status: 400 });
|
|
189
|
+
}
|
|
190
|
+
const webhook = await adapter.verifyWebhook(request);
|
|
191
|
+
if (!webhook.verified) {
|
|
192
|
+
return Response.json({ error: webhook.error || 'Callback could not be verified.' }, { status: 400 });
|
|
193
|
+
}
|
|
194
|
+
if (!reservation && webhook.actionId) {
|
|
195
|
+
reservation = await store.findByActionId(webhook.actionId);
|
|
196
|
+
}
|
|
197
|
+
if (!reservation && webhook.providerRef && store.findByProviderRef) {
|
|
198
|
+
reservation = await store.findByProviderRef(webhook.providerRef);
|
|
199
|
+
}
|
|
200
|
+
if (!reservation) {
|
|
201
|
+
return Response.json({ error: 'Payment reservation not found.' }, { status: 404 });
|
|
202
|
+
}
|
|
203
|
+
if (['completed', 'failed'].includes(reservation.status)) {
|
|
204
|
+
return Response.json({ ResultCode: 0, ResultDesc: 'Already processed' });
|
|
205
|
+
}
|
|
206
|
+
if (webhook.status === 'completed') {
|
|
207
|
+
if (typeof webhook.amount === 'number' &&
|
|
208
|
+
Math.round(webhook.amount * 100) !== Math.round(reservation.amount * 100)) {
|
|
209
|
+
return Response.json({ error: 'Callback amount mismatch.' }, { status: 400 });
|
|
210
|
+
}
|
|
211
|
+
if (webhook.currency &&
|
|
212
|
+
webhook.currency.toUpperCase() !== reservation.currency.toUpperCase()) {
|
|
213
|
+
return Response.json({ error: 'Callback currency mismatch.' }, { status: 400 });
|
|
214
|
+
}
|
|
215
|
+
if (onCompleted) {
|
|
216
|
+
await onCompleted(reservation, webhook);
|
|
217
|
+
}
|
|
218
|
+
await store.markFinal(reservation.actionId, 'completed', null);
|
|
219
|
+
}
|
|
220
|
+
else if (webhook.status === 'failed') {
|
|
221
|
+
await store.markFinal(reservation.actionId, 'failed', webhook.error || 'Payment failed');
|
|
222
|
+
}
|
|
223
|
+
return Response.json({ ResultCode: 0, ResultDesc: 'Accepted' });
|
|
224
|
+
}
|
|
225
|
+
return async (request) => {
|
|
226
|
+
if (request.method !== 'POST') {
|
|
227
|
+
return Response.json({ error: 'Method Not Allowed' }, { status: 405 });
|
|
228
|
+
}
|
|
229
|
+
const pathname = new URL(request.url).pathname;
|
|
230
|
+
if (pathname.endsWith('/callback')) {
|
|
231
|
+
return handleCallback(request);
|
|
232
|
+
}
|
|
233
|
+
return handleInitiate(request);
|
|
234
|
+
};
|
|
235
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
export type PaymentProviderId = 'daraja' | 'stripe' | 'paystack' | 'flutterwave' | 'manual' | (string & {});
|
|
2
|
+
export type PaymentStatus = 'initializing' | 'pending' | 'completed' | 'failed' | 'unknown';
|
|
3
|
+
export interface PaymentContext {
|
|
4
|
+
currency?: string;
|
|
5
|
+
country?: string;
|
|
6
|
+
isOnline?: boolean;
|
|
7
|
+
enabledProviders?: string[];
|
|
8
|
+
}
|
|
9
|
+
export interface PaymentMethodOption {
|
|
10
|
+
id: PaymentProviderId;
|
|
11
|
+
label: string;
|
|
12
|
+
description?: string;
|
|
13
|
+
supportedCurrencies: string[] | '*';
|
|
14
|
+
supportedCountries?: string[] | '*';
|
|
15
|
+
requiresOnline: boolean;
|
|
16
|
+
}
|
|
17
|
+
export interface PaymentInitiateInput {
|
|
18
|
+
actionId: string;
|
|
19
|
+
provider: PaymentProviderId;
|
|
20
|
+
amount: number;
|
|
21
|
+
currency: string;
|
|
22
|
+
businessId?: string;
|
|
23
|
+
tenantId?: string;
|
|
24
|
+
contractId?: string;
|
|
25
|
+
userId?: string;
|
|
26
|
+
phone?: string;
|
|
27
|
+
email?: string;
|
|
28
|
+
callbackUrl?: string;
|
|
29
|
+
returnUrl?: string;
|
|
30
|
+
description?: string;
|
|
31
|
+
metadata?: Record<string, unknown>;
|
|
32
|
+
}
|
|
33
|
+
export interface PaymentInitiateResult {
|
|
34
|
+
success: boolean;
|
|
35
|
+
status: PaymentStatus;
|
|
36
|
+
provider: PaymentProviderId;
|
|
37
|
+
actionId: string;
|
|
38
|
+
duplicate?: boolean;
|
|
39
|
+
providerRef?: string;
|
|
40
|
+
merchantRequestId?: string;
|
|
41
|
+
checkoutUrl?: string;
|
|
42
|
+
customerMessage?: string;
|
|
43
|
+
raw?: unknown;
|
|
44
|
+
}
|
|
45
|
+
export interface PaymentWebhookResult {
|
|
46
|
+
verified: boolean;
|
|
47
|
+
actionId?: string;
|
|
48
|
+
providerRef?: string;
|
|
49
|
+
merchantRequestId?: string;
|
|
50
|
+
receiptNumber?: string;
|
|
51
|
+
amount?: number;
|
|
52
|
+
currency?: string;
|
|
53
|
+
phone?: string;
|
|
54
|
+
status: 'completed' | 'failed' | 'pending';
|
|
55
|
+
error?: string;
|
|
56
|
+
rawPayload?: unknown;
|
|
57
|
+
}
|
|
58
|
+
export interface PaymentProviderAdapter {
|
|
59
|
+
id: PaymentProviderId;
|
|
60
|
+
label: string;
|
|
61
|
+
description?: string;
|
|
62
|
+
supportedCurrencies: string[] | '*';
|
|
63
|
+
supportedCountries?: string[] | '*';
|
|
64
|
+
requiresOnline?: boolean;
|
|
65
|
+
supports?: (context: PaymentContext) => boolean;
|
|
66
|
+
initiate: (input: PaymentInitiateInput) => Promise<PaymentInitiateResult>;
|
|
67
|
+
verifyWebhook?: (request: Request, context?: {
|
|
68
|
+
rawBody?: string;
|
|
69
|
+
}) => Promise<PaymentWebhookResult>;
|
|
70
|
+
}
|
|
71
|
+
export interface PaymentRegistryConfig {
|
|
72
|
+
providers?: PaymentProviderAdapter[];
|
|
73
|
+
enabledProviders?: string[];
|
|
74
|
+
defaultCurrency?: string;
|
|
75
|
+
}
|
|
76
|
+
export interface PaymentReservationRecord {
|
|
77
|
+
actionId: string;
|
|
78
|
+
provider: PaymentProviderId;
|
|
79
|
+
currency: string;
|
|
80
|
+
amount: number;
|
|
81
|
+
businessId?: string;
|
|
82
|
+
userId?: string;
|
|
83
|
+
tenantId?: string;
|
|
84
|
+
contractId?: string;
|
|
85
|
+
phone?: string;
|
|
86
|
+
email?: string;
|
|
87
|
+
callbackHash?: string;
|
|
88
|
+
providerRef?: string;
|
|
89
|
+
merchantRequestId?: string;
|
|
90
|
+
customerMessage?: string;
|
|
91
|
+
status: PaymentStatus;
|
|
92
|
+
error?: string | null;
|
|
93
|
+
metadata?: Record<string, unknown>;
|
|
94
|
+
}
|
|
95
|
+
export interface PaymentReservationStore {
|
|
96
|
+
findByActionId: (actionId: string) => Promise<PaymentReservationRecord | null>;
|
|
97
|
+
findByCallbackHash?: (callbackHash: string) => Promise<PaymentReservationRecord | null>;
|
|
98
|
+
findByProviderRef?: (providerRef: string) => Promise<PaymentReservationRecord | null>;
|
|
99
|
+
reserve: (record: PaymentReservationRecord) => Promise<void>;
|
|
100
|
+
markPending: (actionId: string, update: {
|
|
101
|
+
providerRef?: string;
|
|
102
|
+
merchantRequestId?: string;
|
|
103
|
+
customerMessage?: string;
|
|
104
|
+
}) => Promise<void>;
|
|
105
|
+
markFinal: (actionId: string, status: Extract<PaymentStatus, 'completed' | 'failed' | 'unknown'>, error?: string | null) => Promise<void>;
|
|
106
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "local-lite",
|
|
3
|
-
"version": "2.0.
|
|
3
|
+
"version": "2.0.1",
|
|
4
4
|
"description": "Never let a lost connection break a promise. Local-first sync that faithfully keeps data safe until you're back online.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -155,6 +155,16 @@
|
|
|
155
155
|
"types": "./dist/email/index.d.ts",
|
|
156
156
|
"import": "./dist/email/index.js",
|
|
157
157
|
"default": "./dist/email/index.js"
|
|
158
|
+
},
|
|
159
|
+
"./payments": {
|
|
160
|
+
"types": "./dist/payments/index.d.ts",
|
|
161
|
+
"import": "./dist/payments/index.js",
|
|
162
|
+
"default": "./dist/payments/index.js"
|
|
163
|
+
},
|
|
164
|
+
"./payments/server": {
|
|
165
|
+
"types": "./dist/payments/server.d.ts",
|
|
166
|
+
"import": "./dist/payments/server.js",
|
|
167
|
+
"default": "./dist/payments/server.js"
|
|
158
168
|
}
|
|
159
169
|
},
|
|
160
170
|
"scripts": {
|