iskubixi 1.1.0 → 1.2.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.
- package/CHANGELOG.md +26 -0
- package/README.md +125 -720
- package/dist/index.d.ts +6 -2
- package/dist/index.js +9 -1
- package/dist/iskubixi.d.ts +3 -1
- package/dist/iskubixi.js +165 -16
- package/dist/providers/payment-provider.d.ts +17 -0
- package/dist/providers/paypal-payment-provider.d.ts +41 -0
- package/dist/providers/paypal-payment-provider.js +457 -0
- package/dist/providers/provider-http.d.ts +15 -0
- package/dist/providers/provider-http.js +140 -0
- package/dist/providers/stripe-payment-provider.d.ts +43 -0
- package/dist/providers/stripe-payment-provider.js +339 -0
- package/dist/providers/waafipay-payment-provider.d.ts +1 -0
- package/dist/providers/waafipay-payment-provider.js +4 -0
- package/dist/types/configuration.d.ts +3 -1
- package/dist/types/payment.d.ts +7 -1
- package/dist/types/provider-capabilities.d.ts +2 -1
- package/docs/api-reference.md +93 -0
- package/docs/architecture.md +25 -0
- package/docs/authentication.md +36 -0
- package/docs/biometric-adapters.md +44 -107
- package/docs/configuration.md +57 -0
- package/docs/contributing.md +30 -0
- package/docs/custom-providers.md +50 -0
- package/docs/errors.md +35 -0
- package/docs/examples.md +46 -0
- package/docs/getting-started.md +64 -0
- package/docs/idempotency.md +26 -0
- package/docs/index.md +56 -0
- package/docs/installation.md +28 -0
- package/docs/javascript.md +22 -0
- package/docs/limitations.md +31 -0
- package/docs/passkeys.md +38 -0
- package/docs/payment-authorization.md +33 -141
- package/docs/payment-lifecycle.md +34 -0
- package/docs/payment-verification.md +18 -0
- package/docs/payments.md +68 -0
- package/docs/provider-development.md +33 -0
- package/docs/providers.md +123 -0
- package/docs/qr-payments.md +42 -0
- package/docs/refunds.md +20 -0
- package/docs/security.md +37 -0
- package/docs/storage.md +36 -0
- package/docs/testing.md +24 -0
- package/docs/troubleshooting.md +28 -0
- package/docs/typescript.md +25 -0
- package/docs/webhook-security.md +22 -0
- package/docs/webhooks.md +59 -0
- package/examples/javascript/payment-authorization.js +1 -0
- package/examples/typescript/payment-providers.ts +83 -0
- package/package.json +18 -2
|
@@ -0,0 +1,457 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
3
|
+
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
4
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
|
5
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
6
|
+
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
7
|
+
};
|
|
8
|
+
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
|
9
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
10
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
11
|
+
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
12
|
+
};
|
|
13
|
+
var _PayPalRestClient_clientId, _PayPalRestClient_clientSecret, _PayPalRestClient_baseUrl, _PayPalRestClient_http, _PayPalRestClient_accessToken, _PayPalRestClient_accessTokenExpiresAt, _PayPalRestClient_tokenRequest, _PayPalPaymentProvider_client, _PayPalWebhookAdapter_client, _PayPalWebhookAdapter_webhookId;
|
|
14
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
+
exports.PayPalWebhookAdapter = exports.PayPalPaymentProviderFactory = exports.PayPalPaymentProvider = void 0;
|
|
16
|
+
const node_crypto_1 = require("node:crypto");
|
|
17
|
+
const errors_1 = require("../errors");
|
|
18
|
+
const provider_http_1 = require("./provider-http");
|
|
19
|
+
const errors_2 = require("../errors");
|
|
20
|
+
function readCredentials(credentials) {
|
|
21
|
+
const clientId = credentials.clientId;
|
|
22
|
+
const clientSecret = credentials.clientSecret;
|
|
23
|
+
if (typeof clientId !== "string" ||
|
|
24
|
+
clientId.trim() === "" ||
|
|
25
|
+
typeof clientSecret !== "string" ||
|
|
26
|
+
clientSecret.trim() === "") {
|
|
27
|
+
throw new errors_1.ConfigurationError("PayPal client ID and client secret are required.");
|
|
28
|
+
}
|
|
29
|
+
return { clientId, clientSecret };
|
|
30
|
+
}
|
|
31
|
+
function moneyToString(amount, currency) {
|
|
32
|
+
const minorUnits = (0, provider_http_1.toMinorUnits)(amount, currency);
|
|
33
|
+
const exponent = (0, provider_http_1.currencyExponent)(currency);
|
|
34
|
+
if (exponent === 0) {
|
|
35
|
+
return String(minorUnits);
|
|
36
|
+
}
|
|
37
|
+
const factor = 10 ** exponent;
|
|
38
|
+
const whole = Math.floor(minorUnits / factor);
|
|
39
|
+
const fraction = String(minorUnits % factor).padStart(exponent, "0");
|
|
40
|
+
return `${whole}.${fraction}`;
|
|
41
|
+
}
|
|
42
|
+
function moneyFromString(value, currency) {
|
|
43
|
+
if (typeof value !== "string" ||
|
|
44
|
+
!/^\d+(?:\.\d+)?$/.test(value)) {
|
|
45
|
+
throw new errors_1.ProviderError("PayPal returned an invalid order amount.");
|
|
46
|
+
}
|
|
47
|
+
const exponent = (0, provider_http_1.currencyExponent)(currency);
|
|
48
|
+
const [whole, fraction = ""] = value.split(".");
|
|
49
|
+
if (fraction.length > exponent) {
|
|
50
|
+
throw new errors_1.ProviderError("PayPal returned an amount with unsupported currency precision.");
|
|
51
|
+
}
|
|
52
|
+
const minorUnits = Number(whole) * (10 ** exponent) +
|
|
53
|
+
Number(fraction.padEnd(exponent, "0") || "0");
|
|
54
|
+
if (!Number.isSafeInteger(minorUnits) || minorUnits <= 0) {
|
|
55
|
+
throw new errors_1.ProviderError("PayPal returned an invalid order amount.");
|
|
56
|
+
}
|
|
57
|
+
return minorUnits / (10 ** exponent);
|
|
58
|
+
}
|
|
59
|
+
function paymentStatus(orderStatus, captureStatus) {
|
|
60
|
+
if (orderStatus === "VOIDED") {
|
|
61
|
+
return "joojiyay";
|
|
62
|
+
}
|
|
63
|
+
if (orderStatus !== "COMPLETED") {
|
|
64
|
+
if (orderStatus === "CREATED" ||
|
|
65
|
+
orderStatus === "SAVED" ||
|
|
66
|
+
orderStatus === "APPROVED" ||
|
|
67
|
+
orderStatus === "PAYER_ACTION_REQUIRED") {
|
|
68
|
+
return "sugaya";
|
|
69
|
+
}
|
|
70
|
+
throw new errors_1.ProviderError("PayPal returned an unsupported order status.");
|
|
71
|
+
}
|
|
72
|
+
if (captureStatus === "COMPLETED") {
|
|
73
|
+
return "guuleystay";
|
|
74
|
+
}
|
|
75
|
+
if (captureStatus === "PENDING") {
|
|
76
|
+
return "sugaya";
|
|
77
|
+
}
|
|
78
|
+
if (captureStatus === "DECLINED" || captureStatus === "FAILED") {
|
|
79
|
+
return "fashilmay";
|
|
80
|
+
}
|
|
81
|
+
throw new errors_1.ProviderError("PayPal completed order response omitted a valid capture status.");
|
|
82
|
+
}
|
|
83
|
+
function orderDetails(value) {
|
|
84
|
+
if (!(0, provider_http_1.record)(value) ||
|
|
85
|
+
typeof value.id !== "string" ||
|
|
86
|
+
value.id.trim() === "" ||
|
|
87
|
+
typeof value.status !== "string" ||
|
|
88
|
+
!Array.isArray(value.purchase_units) ||
|
|
89
|
+
!(0, provider_http_1.record)(value.purchase_units[0])) {
|
|
90
|
+
throw new errors_1.ProviderError("PayPal returned an invalid order response.");
|
|
91
|
+
}
|
|
92
|
+
const purchaseUnit = value.purchase_units[0];
|
|
93
|
+
const amount = (0, provider_http_1.record)(purchaseUnit.amount) ? purchaseUnit.amount : undefined;
|
|
94
|
+
const currencyCode = amount?.currency_code;
|
|
95
|
+
if (typeof currencyCode !== "string" || !/^[A-Za-z]{3}$/.test(currencyCode)) {
|
|
96
|
+
throw new errors_1.ProviderError("PayPal returned invalid order currency details.");
|
|
97
|
+
}
|
|
98
|
+
const currency = currencyCode.toUpperCase();
|
|
99
|
+
const payments = (0, provider_http_1.record)(purchaseUnit.payments) ? purchaseUnit.payments : undefined;
|
|
100
|
+
const captures = Array.isArray(payments?.captures) ? payments.captures : [];
|
|
101
|
+
const capture = (0, provider_http_1.record)(captures[0]) ? captures[0] : undefined;
|
|
102
|
+
const captureId = capture?.id;
|
|
103
|
+
const captureStatus = capture?.status;
|
|
104
|
+
const reference = purchaseUnit.reference_id;
|
|
105
|
+
if (typeof reference !== "string" || reference.trim() === "") {
|
|
106
|
+
throw new errors_1.ProviderError("PayPal order response omitted the payment reference.");
|
|
107
|
+
}
|
|
108
|
+
const payment = {
|
|
109
|
+
id: value.id,
|
|
110
|
+
amount: moneyFromString(amount?.value, currency),
|
|
111
|
+
currency,
|
|
112
|
+
reference,
|
|
113
|
+
status: paymentStatus(value.status, captureStatus),
|
|
114
|
+
providerStatus: typeof captureStatus === "string" ? captureStatus : value.status
|
|
115
|
+
};
|
|
116
|
+
const links = Array.isArray(value.links) ? value.links : [];
|
|
117
|
+
const approvalUrl = links
|
|
118
|
+
.filter(provider_http_1.record)
|
|
119
|
+
.find((link) => link.rel === "approve" || link.rel === "payer-action");
|
|
120
|
+
const redirectUrl = (0, provider_http_1.httpsRedirect)(approvalUrl?.href);
|
|
121
|
+
return {
|
|
122
|
+
payment: redirectUrl
|
|
123
|
+
? { ...payment, nextAction: { type: "redirect", url: redirectUrl } }
|
|
124
|
+
: payment,
|
|
125
|
+
...(typeof captureId === "string" && captureId.trim() !== ""
|
|
126
|
+
? { captureId }
|
|
127
|
+
: {})
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
function refundStatus(value) {
|
|
131
|
+
if (value === "COMPLETED") {
|
|
132
|
+
return "guuleystay";
|
|
133
|
+
}
|
|
134
|
+
if (value === "PENDING") {
|
|
135
|
+
return "sugaya";
|
|
136
|
+
}
|
|
137
|
+
if (value === "FAILED" || value === "CANCELLED") {
|
|
138
|
+
return "fashilmay";
|
|
139
|
+
}
|
|
140
|
+
throw new errors_1.ProviderError("PayPal returned an unsupported refund status.");
|
|
141
|
+
}
|
|
142
|
+
function requestIdempotencyKey(value) {
|
|
143
|
+
return (0, node_crypto_1.createHash)("sha256").update(value).digest("hex").slice(0, 32);
|
|
144
|
+
}
|
|
145
|
+
class PayPalRestClient {
|
|
146
|
+
constructor(options) {
|
|
147
|
+
_PayPalRestClient_clientId.set(this, void 0);
|
|
148
|
+
_PayPalRestClient_clientSecret.set(this, void 0);
|
|
149
|
+
_PayPalRestClient_baseUrl.set(this, void 0);
|
|
150
|
+
_PayPalRestClient_http.set(this, void 0);
|
|
151
|
+
_PayPalRestClient_accessToken.set(this, void 0);
|
|
152
|
+
_PayPalRestClient_accessTokenExpiresAt.set(this, 0);
|
|
153
|
+
_PayPalRestClient_tokenRequest.set(this, void 0);
|
|
154
|
+
if (options.environment !== "sandbox" && options.environment !== "live") {
|
|
155
|
+
throw new errors_1.ConfigurationError("PayPal environment must be sandbox or live.");
|
|
156
|
+
}
|
|
157
|
+
if (!Number.isInteger(options.timeoutMs ?? 15000) ||
|
|
158
|
+
(options.timeoutMs ?? 15000) <= 0) {
|
|
159
|
+
throw new errors_1.ConfigurationError("PayPal request timeout must be a positive integer.");
|
|
160
|
+
}
|
|
161
|
+
__classPrivateFieldSet(this, _PayPalRestClient_clientId, options.clientId, "f");
|
|
162
|
+
__classPrivateFieldSet(this, _PayPalRestClient_clientSecret, options.clientSecret, "f");
|
|
163
|
+
__classPrivateFieldSet(this, _PayPalRestClient_baseUrl, options.environment === "sandbox"
|
|
164
|
+
? "https://api-m.sandbox.paypal.com"
|
|
165
|
+
: "https://api-m.paypal.com", "f");
|
|
166
|
+
__classPrivateFieldSet(this, _PayPalRestClient_http, new provider_http_1.ProviderHttpClient({
|
|
167
|
+
provider: "paypal",
|
|
168
|
+
fetch: options.fetch,
|
|
169
|
+
timeoutMs: options.timeoutMs
|
|
170
|
+
}), "f");
|
|
171
|
+
}
|
|
172
|
+
async requestJson(path, operation, method, body, idempotencyKey, notFoundIsEmpty = false) {
|
|
173
|
+
const token = await this.accessToken();
|
|
174
|
+
const headers = {
|
|
175
|
+
authorization: `Bearer ${token}`,
|
|
176
|
+
"content-type": "application/json"
|
|
177
|
+
};
|
|
178
|
+
if (idempotencyKey !== undefined) {
|
|
179
|
+
headers["PayPal-Request-Id"] = requestIdempotencyKey(idempotencyKey);
|
|
180
|
+
}
|
|
181
|
+
return __classPrivateFieldGet(this, _PayPalRestClient_http, "f").requestJson(`${__classPrivateFieldGet(this, _PayPalRestClient_baseUrl, "f")}${path}`, {
|
|
182
|
+
method,
|
|
183
|
+
headers,
|
|
184
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) })
|
|
185
|
+
}, operation, notFoundIsEmpty);
|
|
186
|
+
}
|
|
187
|
+
async accessToken() {
|
|
188
|
+
const now = Date.now();
|
|
189
|
+
if (__classPrivateFieldGet(this, _PayPalRestClient_accessToken, "f") !== undefined &&
|
|
190
|
+
now < __classPrivateFieldGet(this, _PayPalRestClient_accessTokenExpiresAt, "f")) {
|
|
191
|
+
return __classPrivateFieldGet(this, _PayPalRestClient_accessToken, "f");
|
|
192
|
+
}
|
|
193
|
+
if (__classPrivateFieldGet(this, _PayPalRestClient_tokenRequest, "f")) {
|
|
194
|
+
return __classPrivateFieldGet(this, _PayPalRestClient_tokenRequest, "f");
|
|
195
|
+
}
|
|
196
|
+
const tokenRequest = this.requestToken();
|
|
197
|
+
__classPrivateFieldSet(this, _PayPalRestClient_tokenRequest, tokenRequest, "f");
|
|
198
|
+
try {
|
|
199
|
+
return await tokenRequest;
|
|
200
|
+
}
|
|
201
|
+
finally {
|
|
202
|
+
if (__classPrivateFieldGet(this, _PayPalRestClient_tokenRequest, "f") === tokenRequest) {
|
|
203
|
+
__classPrivateFieldSet(this, _PayPalRestClient_tokenRequest, undefined, "f");
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
async requestToken() {
|
|
208
|
+
const encodedCredentials = Buffer.from(`${__classPrivateFieldGet(this, _PayPalRestClient_clientId, "f")}:${__classPrivateFieldGet(this, _PayPalRestClient_clientSecret, "f")}`, "utf8").toString("base64");
|
|
209
|
+
const body = await __classPrivateFieldGet(this, _PayPalRestClient_http, "f").requestJson(`${__classPrivateFieldGet(this, _PayPalRestClient_baseUrl, "f")}/v1/oauth2/token`, {
|
|
210
|
+
method: "POST",
|
|
211
|
+
headers: {
|
|
212
|
+
authorization: `Basic ${encodedCredentials}`,
|
|
213
|
+
"content-type": "application/x-www-form-urlencoded"
|
|
214
|
+
},
|
|
215
|
+
body: "grant_type=client_credentials"
|
|
216
|
+
}, "obtain access token");
|
|
217
|
+
if (!(0, provider_http_1.record)(body) ||
|
|
218
|
+
typeof body.access_token !== "string" ||
|
|
219
|
+
body.access_token.trim() === "" ||
|
|
220
|
+
typeof body.expires_in !== "number" ||
|
|
221
|
+
!Number.isFinite(body.expires_in) ||
|
|
222
|
+
body.expires_in <= 0) {
|
|
223
|
+
throw new errors_1.ProviderError("PayPal returned an invalid OAuth access token response.");
|
|
224
|
+
}
|
|
225
|
+
__classPrivateFieldSet(this, _PayPalRestClient_accessToken, body.access_token, "f");
|
|
226
|
+
__classPrivateFieldSet(this, _PayPalRestClient_accessTokenExpiresAt, Date.now() +
|
|
227
|
+
Math.max(0, body.expires_in - 30) * 1000, "f");
|
|
228
|
+
return __classPrivateFieldGet(this, _PayPalRestClient_accessToken, "f");
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
_PayPalRestClient_clientId = new WeakMap(), _PayPalRestClient_clientSecret = new WeakMap(), _PayPalRestClient_baseUrl = new WeakMap(), _PayPalRestClient_http = new WeakMap(), _PayPalRestClient_accessToken = new WeakMap(), _PayPalRestClient_accessTokenExpiresAt = new WeakMap(), _PayPalRestClient_tokenRequest = new WeakMap();
|
|
232
|
+
function clientFromCredentials(credentials, options) {
|
|
233
|
+
return new PayPalRestClient({
|
|
234
|
+
...readCredentials(credentials),
|
|
235
|
+
...options
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
class PayPalPaymentProvider {
|
|
239
|
+
constructor(credentials, options) {
|
|
240
|
+
this.capabilities = Object.freeze({
|
|
241
|
+
paymentCreation: true,
|
|
242
|
+
paymentLookup: true,
|
|
243
|
+
paymentVerification: true,
|
|
244
|
+
paymentConfirmation: true,
|
|
245
|
+
paymentCancellation: false,
|
|
246
|
+
refundCreation: true,
|
|
247
|
+
refundStatusLookup: true,
|
|
248
|
+
paymentIdempotency: true
|
|
249
|
+
});
|
|
250
|
+
_PayPalPaymentProvider_client.set(this, void 0);
|
|
251
|
+
if (!options || typeof options !== "object") {
|
|
252
|
+
throw new errors_1.ConfigurationError("PayPal provider options are required.");
|
|
253
|
+
}
|
|
254
|
+
__classPrivateFieldSet(this, _PayPalPaymentProvider_client, clientFromCredentials(credentials, options), "f");
|
|
255
|
+
}
|
|
256
|
+
async createPayment(request) {
|
|
257
|
+
if (request.reference.length > 256) {
|
|
258
|
+
throw new errors_1.ValidationError("PayPal payment reference cannot exceed 256 characters.");
|
|
259
|
+
}
|
|
260
|
+
const order = await __classPrivateFieldGet(this, _PayPalPaymentProvider_client, "f").requestJson("/v2/checkout/orders", "create payment", "POST", {
|
|
261
|
+
intent: "CAPTURE",
|
|
262
|
+
purchase_units: [{
|
|
263
|
+
reference_id: request.reference,
|
|
264
|
+
amount: {
|
|
265
|
+
currency_code: request.currency,
|
|
266
|
+
value: moneyToString(request.amount, request.currency)
|
|
267
|
+
}
|
|
268
|
+
}]
|
|
269
|
+
}, request.idempotencyKey);
|
|
270
|
+
const details = orderDetails(order);
|
|
271
|
+
if (details.payment.amount !== request.amount ||
|
|
272
|
+
details.payment.currency !== request.currency ||
|
|
273
|
+
details.payment.reference !== request.reference) {
|
|
274
|
+
throw new errors_1.ProviderError("PayPal order did not match the payment request.");
|
|
275
|
+
}
|
|
276
|
+
return details.payment;
|
|
277
|
+
}
|
|
278
|
+
async findPayment(request) {
|
|
279
|
+
const order = await __classPrivateFieldGet(this, _PayPalPaymentProvider_client, "f").requestJson(`/v2/checkout/orders/${encodeURIComponent(request.paymentId)}`, "retrieve payment", "GET", undefined, undefined, true);
|
|
280
|
+
return order === undefined ? undefined : orderDetails(order).payment;
|
|
281
|
+
}
|
|
282
|
+
async verifyPayment(request) {
|
|
283
|
+
const payment = await this.findPayment(request);
|
|
284
|
+
return payment
|
|
285
|
+
? { exists: true, payment, source: "adapter" }
|
|
286
|
+
: { exists: false, source: "adapter" };
|
|
287
|
+
}
|
|
288
|
+
async confirmPayment(request) {
|
|
289
|
+
const order = await __classPrivateFieldGet(this, _PayPalPaymentProvider_client, "f").requestJson(`/v2/checkout/orders/${encodeURIComponent(request.paymentId)}/capture`, "capture payment", "POST", {}, request.idempotencyKey);
|
|
290
|
+
const details = orderDetails(order);
|
|
291
|
+
if (details.payment.id !== request.paymentId) {
|
|
292
|
+
throw new errors_1.ProviderError("PayPal capture response returned a different order ID.");
|
|
293
|
+
}
|
|
294
|
+
return details.payment;
|
|
295
|
+
}
|
|
296
|
+
async refundPayment(request) {
|
|
297
|
+
const order = await __classPrivateFieldGet(this, _PayPalPaymentProvider_client, "f").requestJson(`/v2/checkout/orders/${encodeURIComponent(request.paymentId)}`, "retrieve payment for refund", "GET");
|
|
298
|
+
const details = orderDetails(order);
|
|
299
|
+
if (details.payment.status !== "guuleystay" || details.captureId === undefined) {
|
|
300
|
+
throw new errors_1.PaymentError("PayPal refunds require a completed capture.");
|
|
301
|
+
}
|
|
302
|
+
const refund = await __classPrivateFieldGet(this, _PayPalPaymentProvider_client, "f").requestJson(`/v2/payments/captures/${encodeURIComponent(details.captureId)}/refund`, "refund payment", "POST", {}, request.idempotencyKey);
|
|
303
|
+
if (!(0, provider_http_1.record)(refund) || typeof refund.id !== "string" || refund.id.trim() === "") {
|
|
304
|
+
throw new errors_1.ProviderError("PayPal returned an invalid refund response.");
|
|
305
|
+
}
|
|
306
|
+
return { id: refund.id, status: refundStatus(refund.status) };
|
|
307
|
+
}
|
|
308
|
+
async findRefundStatus(request) {
|
|
309
|
+
const refund = await __classPrivateFieldGet(this, _PayPalPaymentProvider_client, "f").requestJson(`/v2/payments/refunds/${encodeURIComponent(request.refundId)}`, "retrieve refund", "GET", undefined, undefined, true);
|
|
310
|
+
if (refund === undefined) {
|
|
311
|
+
return undefined;
|
|
312
|
+
}
|
|
313
|
+
if (!(0, provider_http_1.record)(refund) || typeof refund.id !== "string" || refund.id.trim() === "") {
|
|
314
|
+
throw new errors_1.ProviderError("PayPal returned an invalid refund status response.");
|
|
315
|
+
}
|
|
316
|
+
return { id: refund.id, status: refundStatus(refund.status) };
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
exports.PayPalPaymentProvider = PayPalPaymentProvider;
|
|
320
|
+
_PayPalPaymentProvider_client = new WeakMap();
|
|
321
|
+
class PayPalPaymentProviderFactory {
|
|
322
|
+
constructor(options) {
|
|
323
|
+
this.options = options;
|
|
324
|
+
}
|
|
325
|
+
create(credentials) {
|
|
326
|
+
return new PayPalPaymentProvider(credentials, this.options);
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
exports.PayPalPaymentProviderFactory = PayPalPaymentProviderFactory;
|
|
330
|
+
function headerValue(headers, name) {
|
|
331
|
+
const values = Object.entries(headers)
|
|
332
|
+
.filter(([header]) => header.toLowerCase() === name.toLowerCase())
|
|
333
|
+
.map(([, value]) => value);
|
|
334
|
+
return values.length === 1 && typeof values[0] === "string"
|
|
335
|
+
? values[0]
|
|
336
|
+
: undefined;
|
|
337
|
+
}
|
|
338
|
+
function safePayPalCertificateUrl(value) {
|
|
339
|
+
try {
|
|
340
|
+
const url = new URL(value);
|
|
341
|
+
return url.protocol === "https:" &&
|
|
342
|
+
[
|
|
343
|
+
"api.paypal.com",
|
|
344
|
+
"api-m.paypal.com",
|
|
345
|
+
"api.sandbox.paypal.com",
|
|
346
|
+
"api-m.sandbox.paypal.com"
|
|
347
|
+
]
|
|
348
|
+
.includes(url.hostname) &&
|
|
349
|
+
url.username === "" &&
|
|
350
|
+
url.password === "";
|
|
351
|
+
}
|
|
352
|
+
catch {
|
|
353
|
+
return false;
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
class PayPalWebhookAdapter {
|
|
357
|
+
constructor(credentials, options) {
|
|
358
|
+
_PayPalWebhookAdapter_client.set(this, void 0);
|
|
359
|
+
_PayPalWebhookAdapter_webhookId.set(this, void 0);
|
|
360
|
+
if (!options ||
|
|
361
|
+
typeof options.webhookId !== "string" ||
|
|
362
|
+
options.webhookId.trim() === "") {
|
|
363
|
+
throw new errors_1.ConfigurationError("PayPal webhook ID is required.");
|
|
364
|
+
}
|
|
365
|
+
__classPrivateFieldSet(this, _PayPalWebhookAdapter_client, clientFromCredentials(credentials, options), "f");
|
|
366
|
+
__classPrivateFieldSet(this, _PayPalWebhookAdapter_webhookId, options.webhookId, "f");
|
|
367
|
+
}
|
|
368
|
+
async verifyAndParse(request) {
|
|
369
|
+
if (!request ||
|
|
370
|
+
request.bixiye !== "paypal" ||
|
|
371
|
+
!(request.rawBody instanceof Uint8Array) ||
|
|
372
|
+
request.rawBody.byteLength === 0 ||
|
|
373
|
+
!request.headers ||
|
|
374
|
+
typeof request.headers !== "object" ||
|
|
375
|
+
Array.isArray(request.headers)) {
|
|
376
|
+
throw new errors_2.WebhookVerificationError("PayPal webhook request is invalid.");
|
|
377
|
+
}
|
|
378
|
+
const authAlgo = headerValue(request.headers, "paypal-auth-algo");
|
|
379
|
+
const certUrl = headerValue(request.headers, "paypal-cert-url");
|
|
380
|
+
const transmissionId = headerValue(request.headers, "paypal-transmission-id");
|
|
381
|
+
const transmissionSignature = headerValue(request.headers, "paypal-transmission-sig");
|
|
382
|
+
const transmissionTime = headerValue(request.headers, "paypal-transmission-time");
|
|
383
|
+
if (!authAlgo ||
|
|
384
|
+
!certUrl ||
|
|
385
|
+
!safePayPalCertificateUrl(certUrl) ||
|
|
386
|
+
!transmissionId ||
|
|
387
|
+
!transmissionSignature ||
|
|
388
|
+
!transmissionTime) {
|
|
389
|
+
throw new errors_2.WebhookVerificationError("PayPal webhook signature headers are invalid.");
|
|
390
|
+
}
|
|
391
|
+
let event;
|
|
392
|
+
try {
|
|
393
|
+
event = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(request.rawBody));
|
|
394
|
+
}
|
|
395
|
+
catch {
|
|
396
|
+
throw new errors_2.WebhookVerificationError("PayPal webhook body is invalid.");
|
|
397
|
+
}
|
|
398
|
+
if (!(0, provider_http_1.record)(event) ||
|
|
399
|
+
typeof event.id !== "string" ||
|
|
400
|
+
event.id.trim() === "" ||
|
|
401
|
+
typeof event.event_type !== "string") {
|
|
402
|
+
throw new errors_2.WebhookVerificationError("PayPal webhook event envelope is invalid.");
|
|
403
|
+
}
|
|
404
|
+
const verification = await __classPrivateFieldGet(this, _PayPalWebhookAdapter_client, "f").requestJson("/v1/notifications/verify-webhook-signature", "verify webhook signature", "POST", {
|
|
405
|
+
auth_algo: authAlgo,
|
|
406
|
+
cert_url: certUrl,
|
|
407
|
+
transmission_id: transmissionId,
|
|
408
|
+
transmission_sig: transmissionSignature,
|
|
409
|
+
transmission_time: transmissionTime,
|
|
410
|
+
webhook_id: __classPrivateFieldGet(this, _PayPalWebhookAdapter_webhookId, "f"),
|
|
411
|
+
webhook_event: event
|
|
412
|
+
});
|
|
413
|
+
if (!(0, provider_http_1.record)(verification) || verification.verification_status !== "SUCCESS") {
|
|
414
|
+
throw new errors_2.WebhookVerificationError("PayPal webhook signature verification failed.");
|
|
415
|
+
}
|
|
416
|
+
if (event.event_type !== "PAYMENT.CAPTURE.COMPLETED" &&
|
|
417
|
+
event.event_type !== "PAYMENT.CAPTURE.PENDING" &&
|
|
418
|
+
event.event_type !== "PAYMENT.CAPTURE.DENIED") {
|
|
419
|
+
return { bixiye: "paypal", dhacdoId: event.id, laIskaIndhoTiray: true };
|
|
420
|
+
}
|
|
421
|
+
if (!(0, provider_http_1.record)(event.resource)) {
|
|
422
|
+
throw new errors_2.WebhookVerificationError("PayPal capture webhook resource is invalid.");
|
|
423
|
+
}
|
|
424
|
+
const related = (0, provider_http_1.record)(event.resource.supplementary_data)
|
|
425
|
+
? event.resource.supplementary_data
|
|
426
|
+
: undefined;
|
|
427
|
+
const relatedIds = related && (0, provider_http_1.record)(related.related_ids)
|
|
428
|
+
? related.related_ids
|
|
429
|
+
: undefined;
|
|
430
|
+
const orderId = relatedIds?.order_id;
|
|
431
|
+
const amount = (0, provider_http_1.record)(event.resource.amount) ? event.resource.amount : undefined;
|
|
432
|
+
const currency = amount?.currency_code;
|
|
433
|
+
if (typeof orderId !== "string" ||
|
|
434
|
+
orderId.trim() === "" ||
|
|
435
|
+
amount === undefined ||
|
|
436
|
+
typeof amount.value !== "string" ||
|
|
437
|
+
typeof currency !== "string" ||
|
|
438
|
+
!/^[A-Za-z]{3}$/.test(currency)) {
|
|
439
|
+
throw new errors_2.WebhookVerificationError("PayPal capture webhook details are invalid.");
|
|
440
|
+
}
|
|
441
|
+
const paymentStatus = event.event_type === "PAYMENT.CAPTURE.COMPLETED"
|
|
442
|
+
? "guuleystay"
|
|
443
|
+
: event.event_type === "PAYMENT.CAPTURE.DENIED"
|
|
444
|
+
? "fashilmay"
|
|
445
|
+
: "sugaya";
|
|
446
|
+
return {
|
|
447
|
+
bixiye: "paypal",
|
|
448
|
+
dhacdoId: event.id,
|
|
449
|
+
xaalad: paymentStatus,
|
|
450
|
+
lacagId: orderId,
|
|
451
|
+
qadarka: moneyFromString(amount.value, currency.toUpperCase()),
|
|
452
|
+
lacagta: currency.toUpperCase()
|
|
453
|
+
};
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
exports.PayPalWebhookAdapter = PayPalWebhookAdapter;
|
|
457
|
+
_PayPalWebhookAdapter_client = new WeakMap(), _PayPalWebhookAdapter_webhookId = new WeakMap();
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export interface ProviderHttpClientOptions {
|
|
2
|
+
provider: string;
|
|
3
|
+
fetch?: typeof fetch;
|
|
4
|
+
timeoutMs?: number;
|
|
5
|
+
}
|
|
6
|
+
export declare class ProviderHttpClient {
|
|
7
|
+
#private;
|
|
8
|
+
constructor(options: ProviderHttpClientOptions);
|
|
9
|
+
requestJson(url: string, init: RequestInit, operation: string, notFoundIsEmpty?: boolean): Promise<unknown | undefined>;
|
|
10
|
+
}
|
|
11
|
+
export declare function toMinorUnits(amount: number, currency: string): number;
|
|
12
|
+
export declare function currencyExponent(currency: string): number;
|
|
13
|
+
export declare function fromMinorUnits(amount: unknown, currency: string): number;
|
|
14
|
+
export declare function httpsRedirect(value: unknown): string | undefined;
|
|
15
|
+
export declare function record(value: unknown): value is Record<string, unknown>;
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
3
|
+
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
4
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
|
5
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
6
|
+
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
7
|
+
};
|
|
8
|
+
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
|
9
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
10
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
11
|
+
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
12
|
+
};
|
|
13
|
+
var _ProviderHttpClient_provider, _ProviderHttpClient_fetch, _ProviderHttpClient_timeoutMs;
|
|
14
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
+
exports.ProviderHttpClient = void 0;
|
|
16
|
+
exports.toMinorUnits = toMinorUnits;
|
|
17
|
+
exports.currencyExponent = currencyExponent;
|
|
18
|
+
exports.fromMinorUnits = fromMinorUnits;
|
|
19
|
+
exports.httpsRedirect = httpsRedirect;
|
|
20
|
+
exports.record = record;
|
|
21
|
+
const errors_1 = require("../errors");
|
|
22
|
+
const defaultTimeoutMs = 15000;
|
|
23
|
+
const zeroDecimalCurrencies = new Set([
|
|
24
|
+
"BIF", "CLP", "DJF", "GNF", "ISK", "JPY", "KMF", "KRW", "PYG",
|
|
25
|
+
"RWF", "UGX", "VND", "VUV", "XAF", "XOF", "XPF"
|
|
26
|
+
]);
|
|
27
|
+
const threeDecimalCurrencies = new Set([
|
|
28
|
+
"BHD", "IQD", "JOD", "KWD", "LYD", "OMR", "TND"
|
|
29
|
+
]);
|
|
30
|
+
class ProviderHttpClient {
|
|
31
|
+
constructor(options) {
|
|
32
|
+
_ProviderHttpClient_provider.set(this, void 0);
|
|
33
|
+
_ProviderHttpClient_fetch.set(this, void 0);
|
|
34
|
+
_ProviderHttpClient_timeoutMs.set(this, void 0);
|
|
35
|
+
if (!options || typeof options.provider !== "string" || options.provider.trim() === "") {
|
|
36
|
+
throw new errors_1.ConfigurationError("Provider HTTP client name is required.");
|
|
37
|
+
}
|
|
38
|
+
__classPrivateFieldSet(this, _ProviderHttpClient_provider, options.provider, "f");
|
|
39
|
+
__classPrivateFieldSet(this, _ProviderHttpClient_fetch, options.fetch ?? globalThis.fetch, "f");
|
|
40
|
+
__classPrivateFieldSet(this, _ProviderHttpClient_timeoutMs, options.timeoutMs ?? defaultTimeoutMs, "f");
|
|
41
|
+
if (typeof __classPrivateFieldGet(this, _ProviderHttpClient_fetch, "f") !== "function") {
|
|
42
|
+
throw new errors_1.ConfigurationError("Fetch is required for this payment provider.");
|
|
43
|
+
}
|
|
44
|
+
if (!Number.isInteger(__classPrivateFieldGet(this, _ProviderHttpClient_timeoutMs, "f")) || __classPrivateFieldGet(this, _ProviderHttpClient_timeoutMs, "f") <= 0) {
|
|
45
|
+
throw new errors_1.ConfigurationError("Provider request timeout must be a positive integer.");
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
async requestJson(url, init, operation, notFoundIsEmpty = false) {
|
|
49
|
+
const controller = new AbortController();
|
|
50
|
+
const timeout = setTimeout(() => controller.abort(), __classPrivateFieldGet(this, _ProviderHttpClient_timeoutMs, "f"));
|
|
51
|
+
try {
|
|
52
|
+
const response = await __classPrivateFieldGet(this, _ProviderHttpClient_fetch, "f").call(this, url, {
|
|
53
|
+
...init,
|
|
54
|
+
redirect: "error",
|
|
55
|
+
signal: controller.signal
|
|
56
|
+
});
|
|
57
|
+
if (notFoundIsEmpty && response.status === 404) {
|
|
58
|
+
return undefined;
|
|
59
|
+
}
|
|
60
|
+
if (!response.ok) {
|
|
61
|
+
throw new errors_1.ProviderError("Payment provider returned an HTTP error.", {
|
|
62
|
+
context: {
|
|
63
|
+
provider: __classPrivateFieldGet(this, _ProviderHttpClient_provider, "f"),
|
|
64
|
+
operation,
|
|
65
|
+
status: response.status
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
try {
|
|
70
|
+
return await response.json();
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
throw new errors_1.ProviderError("Payment provider returned invalid JSON.", {
|
|
74
|
+
context: { provider: __classPrivateFieldGet(this, _ProviderHttpClient_provider, "f"), operation }
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
catch (error) {
|
|
79
|
+
if (error instanceof errors_1.ProviderError) {
|
|
80
|
+
throw error;
|
|
81
|
+
}
|
|
82
|
+
throw new errors_1.ProviderError(controller.signal.aborted
|
|
83
|
+
? "Payment provider request timed out."
|
|
84
|
+
: "Payment provider request failed.", {
|
|
85
|
+
context: { provider: __classPrivateFieldGet(this, _ProviderHttpClient_provider, "f"), operation }
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
finally {
|
|
89
|
+
clearTimeout(timeout);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
exports.ProviderHttpClient = ProviderHttpClient;
|
|
94
|
+
_ProviderHttpClient_provider = new WeakMap(), _ProviderHttpClient_fetch = new WeakMap(), _ProviderHttpClient_timeoutMs = new WeakMap();
|
|
95
|
+
function toMinorUnits(amount, currency) {
|
|
96
|
+
const exponent = currencyExponent(currency);
|
|
97
|
+
const multiplier = 10 ** exponent;
|
|
98
|
+
const minorUnits = Math.round(amount * multiplier);
|
|
99
|
+
if (!Number.isFinite(amount) ||
|
|
100
|
+
amount <= 0 ||
|
|
101
|
+
!Number.isSafeInteger(minorUnits) ||
|
|
102
|
+
Math.abs(amount * multiplier - minorUnits) > 1e-8) {
|
|
103
|
+
throw new errors_1.ValidationError("Payment amount cannot be represented in the currency's minor unit.");
|
|
104
|
+
}
|
|
105
|
+
return minorUnits;
|
|
106
|
+
}
|
|
107
|
+
function currencyExponent(currency) {
|
|
108
|
+
if (!/^[A-Z]{3}$/.test(currency)) {
|
|
109
|
+
throw new errors_1.ValidationError("Payment currency must be a three-letter uppercase code.");
|
|
110
|
+
}
|
|
111
|
+
return zeroDecimalCurrencies.has(currency)
|
|
112
|
+
? 0
|
|
113
|
+
: threeDecimalCurrencies.has(currency)
|
|
114
|
+
? 3
|
|
115
|
+
: 2;
|
|
116
|
+
}
|
|
117
|
+
function fromMinorUnits(amount, currency) {
|
|
118
|
+
if (typeof amount !== "number" || !Number.isSafeInteger(amount) || amount <= 0) {
|
|
119
|
+
throw new errors_1.ProviderError("Payment provider returned an invalid amount.");
|
|
120
|
+
}
|
|
121
|
+
const exponent = currencyExponent(currency);
|
|
122
|
+
return amount / (10 ** exponent);
|
|
123
|
+
}
|
|
124
|
+
function httpsRedirect(value) {
|
|
125
|
+
if (typeof value !== "string" || value.length > 2048) {
|
|
126
|
+
return undefined;
|
|
127
|
+
}
|
|
128
|
+
try {
|
|
129
|
+
const url = new URL(value);
|
|
130
|
+
return url.protocol === "https:" && url.username === "" && url.password === ""
|
|
131
|
+
? url.toString()
|
|
132
|
+
: undefined;
|
|
133
|
+
}
|
|
134
|
+
catch {
|
|
135
|
+
return undefined;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
function record(value) {
|
|
139
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
140
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { PaymentIdRequest, PaymentConfirmationRequest, PaymentProvider, PaymentProviderFactory, PaymentRefundRequest, PaymentRefundStatusRequest, PaymentRequest, PaymentVerification, ProviderCredentials, ProviderPayment, ProviderRefund } from "./payment-provider";
|
|
2
|
+
import type { CodsiWebhook, PaymentWebhookAdapter, PaymentWebhookEvent } from "./payment-webhook-adapter";
|
|
3
|
+
export interface StripePaymentProviderOptions {
|
|
4
|
+
environment?: "test" | "live";
|
|
5
|
+
timeoutMs?: number;
|
|
6
|
+
apiBaseUrl?: string;
|
|
7
|
+
}
|
|
8
|
+
export interface StripeWebhookAdapterOptions {
|
|
9
|
+
secret: string;
|
|
10
|
+
toleranceSeconds?: number;
|
|
11
|
+
}
|
|
12
|
+
export declare class StripePaymentProvider implements PaymentProvider {
|
|
13
|
+
#private;
|
|
14
|
+
readonly capabilities: Readonly<{
|
|
15
|
+
paymentCreation: true;
|
|
16
|
+
paymentLookup: true;
|
|
17
|
+
paymentVerification: true;
|
|
18
|
+
paymentConfirmation: true;
|
|
19
|
+
paymentCancellation: true;
|
|
20
|
+
refundCreation: true;
|
|
21
|
+
refundStatusLookup: true;
|
|
22
|
+
paymentIdempotency: true;
|
|
23
|
+
}>;
|
|
24
|
+
constructor(credentials: ProviderCredentials, options?: StripePaymentProviderOptions);
|
|
25
|
+
createPayment(request: PaymentRequest): Promise<ProviderPayment>;
|
|
26
|
+
findPayment(request: PaymentIdRequest): Promise<ProviderPayment | undefined>;
|
|
27
|
+
confirmPayment(request: PaymentConfirmationRequest): Promise<ProviderPayment>;
|
|
28
|
+
cancelPayment(request: PaymentIdRequest): Promise<void>;
|
|
29
|
+
verifyPayment(request: PaymentIdRequest): Promise<PaymentVerification>;
|
|
30
|
+
refundPayment(request: PaymentRefundRequest): Promise<ProviderRefund>;
|
|
31
|
+
findRefundStatus(request: PaymentRefundStatusRequest): Promise<ProviderRefund | undefined>;
|
|
32
|
+
private call;
|
|
33
|
+
}
|
|
34
|
+
export declare class StripePaymentProviderFactory implements PaymentProviderFactory {
|
|
35
|
+
private readonly options;
|
|
36
|
+
constructor(options?: StripePaymentProviderOptions);
|
|
37
|
+
create(credentials: ProviderCredentials): PaymentProvider;
|
|
38
|
+
}
|
|
39
|
+
export declare class StripeWebhookAdapter implements PaymentWebhookAdapter {
|
|
40
|
+
#private;
|
|
41
|
+
constructor(options: StripeWebhookAdapterOptions);
|
|
42
|
+
verifyAndParse(request: CodsiWebhook): Promise<PaymentWebhookEvent>;
|
|
43
|
+
}
|