@easypayment/medusa-payment-paypal 1.0.2 → 1.1.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/.medusa/server/src/admin/index.js +7 -7
- package/.medusa/server/src/admin/index.mjs +7 -7
- package/.medusa/server/src/api/admin/paypal/onboard-complete/route.d.ts +2 -2
- package/.medusa/server/src/api/admin/paypal/onboard-complete/route.d.ts.map +1 -1
- package/.medusa/server/src/api/admin/paypal/onboard-complete/route.js +4 -0
- package/.medusa/server/src/api/admin/paypal/onboard-complete/route.js.map +1 -1
- package/.medusa/server/src/api/middlewares.d.ts.map +1 -1
- package/.medusa/server/src/api/middlewares.js +16 -1
- package/.medusa/server/src/api/middlewares.js.map +1 -1
- package/.medusa/server/src/api/store/paypal/capture-order/route.d.ts.map +1 -1
- package/.medusa/server/src/api/store/paypal/capture-order/route.js +45 -16
- package/.medusa/server/src/api/store/paypal/capture-order/route.js.map +1 -1
- package/.medusa/server/src/api/store/paypal/config/route.d.ts.map +1 -1
- package/.medusa/server/src/api/store/paypal/config/route.js +7 -1
- package/.medusa/server/src/api/store/paypal/config/route.js.map +1 -1
- package/.medusa/server/src/api/store/paypal/onboard-return/route.d.ts.map +1 -1
- package/.medusa/server/src/api/store/paypal/onboard-return/route.js +24 -2
- package/.medusa/server/src/api/store/paypal/onboard-return/route.js.map +1 -1
- package/.medusa/server/src/api/store/paypal/webhook/route.d.ts.map +1 -1
- package/.medusa/server/src/api/store/paypal/webhook/route.js +22 -48
- package/.medusa/server/src/api/store/paypal/webhook/route.js.map +1 -1
- package/.medusa/server/src/api/utils/rate-limit.d.ts +3 -0
- package/.medusa/server/src/api/utils/rate-limit.d.ts.map +1 -0
- package/.medusa/server/src/api/utils/rate-limit.js +92 -0
- package/.medusa/server/src/api/utils/rate-limit.js.map +1 -0
- package/.medusa/server/src/jobs/paypal-webhook-retry.d.ts.map +1 -1
- package/.medusa/server/src/jobs/paypal-webhook-retry.js +115 -90
- package/.medusa/server/src/jobs/paypal-webhook-retry.js.map +1 -1
- package/.medusa/server/src/modules/paypal/payment-provider/base-provider.d.ts +48 -0
- package/.medusa/server/src/modules/paypal/payment-provider/base-provider.d.ts.map +1 -0
- package/.medusa/server/src/modules/paypal/payment-provider/base-provider.js +159 -0
- package/.medusa/server/src/modules/paypal/payment-provider/base-provider.js.map +1 -0
- package/.medusa/server/src/modules/paypal/payment-provider/card-service.d.ts +5 -20
- package/.medusa/server/src/modules/paypal/payment-provider/card-service.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/payment-provider/card-service.js +27 -160
- package/.medusa/server/src/modules/paypal/payment-provider/card-service.js.map +1 -1
- package/.medusa/server/src/modules/paypal/payment-provider/service.d.ts +5 -20
- package/.medusa/server/src/modules/paypal/payment-provider/service.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/payment-provider/service.js +21 -138
- package/.medusa/server/src/modules/paypal/payment-provider/service.js.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/amounts.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/amounts.js +10 -0
- package/.medusa/server/src/modules/paypal/utils/amounts.js.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/credential-resolver.d.ts +1 -1
- package/.medusa/server/src/modules/paypal/utils/credential-resolver.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/credential-resolver.js +27 -26
- package/.medusa/server/src/modules/paypal/utils/credential-resolver.js.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/partner.d.ts +9 -0
- package/.medusa/server/src/modules/paypal/utils/partner.d.ts.map +1 -0
- package/.medusa/server/src/modules/paypal/utils/partner.js +12 -0
- package/.medusa/server/src/modules/paypal/utils/partner.js.map +1 -0
- package/.medusa/server/src/modules/paypal/utils/payment-session.d.ts +0 -5
- package/.medusa/server/src/modules/paypal/utils/payment-session.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/payment-session.js +37 -18
- package/.medusa/server/src/modules/paypal/utils/payment-session.js.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/secret-crypto.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/secret-crypto.js +30 -1
- package/.medusa/server/src/modules/paypal/utils/secret-crypto.js.map +1 -1
- package/.medusa/server/src/subscribers/paypal-webhook-process.d.ts +19 -0
- package/.medusa/server/src/subscribers/paypal-webhook-process.d.ts.map +1 -0
- package/.medusa/server/src/subscribers/paypal-webhook-process.js +107 -0
- package/.medusa/server/src/subscribers/paypal-webhook-process.js.map +1 -0
- package/CHANGELOG.md +73 -0
- package/package.json +2 -1
- package/src/api/admin/paypal/onboard-complete/route.ts +10 -2
- package/src/api/middlewares.ts +16 -1
- package/src/api/store/paypal/capture-order/route.ts +60 -22
- package/src/api/store/paypal/config/route.ts +8 -1
- package/src/api/store/paypal/onboard-return/route.ts +31 -6
- package/src/api/store/paypal/webhook/route.ts +24 -60
- package/src/api/utils/rate-limit.ts +105 -0
- package/src/jobs/paypal-webhook-retry.ts +132 -94
- package/src/modules/paypal/payment-provider/base-provider.ts +192 -0
- package/src/modules/paypal/payment-provider/card-service.ts +28 -196
- package/src/modules/paypal/payment-provider/service.ts +23 -164
- package/src/modules/paypal/utils/amounts.ts +10 -0
- package/src/modules/paypal/utils/credential-resolver.ts +32 -27
- package/src/modules/paypal/utils/partner.ts +8 -0
- package/src/modules/paypal/utils/payment-session.ts +44 -19
- package/src/modules/paypal/utils/secret-crypto.ts +36 -1
- package/src/subscribers/paypal-webhook-process.ts +127 -0
- package/.medusa/server/src/modules/paypal/clients/paypal-seller.client.d.ts +0 -15
- package/.medusa/server/src/modules/paypal/clients/paypal-seller.client.d.ts.map +0 -1
- package/.medusa/server/src/modules/paypal/clients/paypal-seller.client.js +0 -68
- package/.medusa/server/src/modules/paypal/clients/paypal-seller.client.js.map +0 -1
- package/src/modules/paypal/clients/paypal-seller.client.ts +0 -64
|
@@ -58,27 +58,46 @@ function getStoredPayPalOrderId(sessionData) {
|
|
|
58
58
|
* Shallow-merge `extraData` into a payment session's `data`, preserving the
|
|
59
59
|
* session's amount/currency. Callers that update the nested `paypal` object are
|
|
60
60
|
* responsible for spreading its existing keys (see `getStoredPayPalOrderId`).
|
|
61
|
+
*
|
|
62
|
+
* The write is retried a few times before giving up: when this runs right after
|
|
63
|
+
* a successful PayPal capture, a transient DB blip that loses the write means
|
|
64
|
+
* the money is captured but Medusa never records it. A bounded retry closes the
|
|
65
|
+
* common transient-failure window; if every attempt fails the error is
|
|
66
|
+
* re-thrown (with a CRITICAL log for capture/order data) so the caller can react
|
|
67
|
+
* — the webhook and paypal-complete's live re-derivation remain the backstop.
|
|
61
68
|
*/
|
|
69
|
+
const SESSION_UPDATE_MAX_ATTEMPTS = 3;
|
|
70
|
+
const SESSION_UPDATE_BASE_DELAY_MS = 200;
|
|
62
71
|
async function updatePayPalSessionData(sessionId, extraData, scope) {
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
72
|
+
const paymentModule = scope.resolve(utils_1.Modules.PAYMENT);
|
|
73
|
+
let lastError;
|
|
74
|
+
for (let attempt = 1; attempt <= SESSION_UPDATE_MAX_ATTEMPTS; attempt++) {
|
|
75
|
+
try {
|
|
76
|
+
const [existing] = await paymentModule.listPaymentSessions({ id: [sessionId] }, { take: 1 });
|
|
77
|
+
const mergedData = { ...(existing?.data || {}), ...extraData };
|
|
78
|
+
await paymentModule.updatePaymentSession({
|
|
79
|
+
id: sessionId,
|
|
80
|
+
data: mergedData,
|
|
81
|
+
amount: existing?.amount,
|
|
82
|
+
currency_code: existing?.currency_code,
|
|
83
|
+
});
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
catch (e) {
|
|
87
|
+
lastError = e;
|
|
88
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
89
|
+
console.warn(`[PayPal] updatePayPalSessionData attempt ${attempt}/${SESSION_UPDATE_MAX_ATTEMPTS} failed:`, msg);
|
|
90
|
+
if (attempt < SESSION_UPDATE_MAX_ATTEMPTS) {
|
|
91
|
+
await new Promise((r) => setTimeout(r, SESSION_UPDATE_BASE_DELAY_MS * attempt));
|
|
92
|
+
}
|
|
80
93
|
}
|
|
81
|
-
throw e;
|
|
82
94
|
}
|
|
95
|
+
const msg = lastError instanceof Error ? lastError.message : String(lastError);
|
|
96
|
+
console.error("[PayPal] updatePayPalSessionData failed after retries:", msg);
|
|
97
|
+
const hasCaptureData = "capture_id" in extraData || "order_id" in extraData;
|
|
98
|
+
if (hasCaptureData) {
|
|
99
|
+
console.error("[PayPal] CRITICAL: Payment data (capture/order) was NOT persisted to session.", { sessionId, keys: Object.keys(extraData) });
|
|
100
|
+
}
|
|
101
|
+
throw lastError;
|
|
83
102
|
}
|
|
84
103
|
//# sourceMappingURL=payment-session.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"payment-session.js","sourceRoot":"","sources":["../../../../../../src/modules/paypal/utils/payment-session.ts"],"names":[],"mappings":";;AA2BA,4DAsCC;AAOD,wDAMC;
|
|
1
|
+
{"version":3,"file":"payment-session.js","sourceRoot":"","sources":["../../../../../../src/modules/paypal/utils/payment-session.ts"],"names":[],"mappings":";;AA2BA,4DAsCC;AAOD,wDAMC;AAiBD,0DA0CC;AAxID,qDAAmD;AACnD,iDAAmD;AAmBnD;;;;;GAKG;AACI,KAAK,UAAU,wBAAwB,CAC5C,MAAc,EACd,KAAU;IAEV,IAAI,CAAC;QACH,MAAM,KAAK,GAAG,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,CAAA;QACpC,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,MAAM,KAAK,CAAC,KAAK,CAAC;YACxC,MAAM,EAAE,MAAM;YACd,MAAM,EAAE;gBACN,IAAI;gBAC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EAAE,CAAC;gBAC1C,MAAM,IAAI,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,UAAU,CAAC,CAAC,EAAE,4BAA4B,GAAG,OAAO,CAAC,CAAC,CAAA;YACjF,CAAC;QACH,CAAC;IACH,CAAC;IAED,MAAM,GAAG,GAAG,SAAS,YAAY,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,SAAS,CAAC,CAAA;IAC9E,OAAO,CAAC,KAAK,CAAC,wDAAwD,EAAE,GAAG,CAAC,CAAA;IAC5E,MAAM,cAAc,GAAG,YAAY,IAAI,SAAS,IAAI,UAAU,IAAI,SAAS,CAAA;IAC3E,IAAI,cAAc,EAAE,CAAC;QACnB,OAAO,CAAC,KAAK,CACX,+EAA+E,EAC/E,EAAE,SAAS,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,CAC5C,CAAA;IACH,CAAC;IACD,MAAM,SAAS,CAAA;AACjB,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"secret-crypto.d.ts","sourceRoot":"","sources":["../../../../../../src/modules/paypal/utils/secret-crypto.ts"],"names":[],"mappings":"AA4FA,wBAAgB,yBAAyB,IAAI,OAAO,CAEnD;AAED,wBAAgB,WAAW,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAKnD;
|
|
1
|
+
{"version":3,"file":"secret-crypto.d.ts","sourceRoot":"","sources":["../../../../../../src/modules/paypal/utils/secret-crypto.ts"],"names":[],"mappings":"AA4FA,wBAAgB,yBAAyB,IAAI,OAAO,CAEnD;AAED,wBAAgB,WAAW,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAKnD;AA+BD;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,CAAC,SAAS,MAAM,GAAG,IAAI,GAAG,SAAS,EAAE,KAAK,EAAE,CAAC,GAAG,CAAC,GAAG,MAAM,CAqBvF;AAED;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,CAAC,SAAS,MAAM,GAAG,IAAI,GAAG,SAAS,EAAE,KAAK,EAAE,CAAC,GAAG,CAAC,GAAG,MAAM,CA+BvF"}
|
|
@@ -96,6 +96,29 @@ function isEncrypted(value) {
|
|
|
96
96
|
return (typeof value === "string" &&
|
|
97
97
|
(value.startsWith(PREFIX_V2) || value.startsWith(PREFIX_V1)));
|
|
98
98
|
}
|
|
99
|
+
let warnedNoKey = false;
|
|
100
|
+
/**
|
|
101
|
+
* Surface (once) that secrets are being stored without encryption-at-rest. In a
|
|
102
|
+
* production environment this is a real exposure — client_secret / access_token
|
|
103
|
+
* land in the database as plaintext — so it is worth a loud warning. Set
|
|
104
|
+
* PAYPAL_ENCRYPTION_STRICT=true to make it a hard error instead (recommended for
|
|
105
|
+
* production once a key is provisioned), which fails the write rather than
|
|
106
|
+
* persisting a plaintext secret.
|
|
107
|
+
*/
|
|
108
|
+
function assertOrWarnNoEncryptionKey() {
|
|
109
|
+
const strict = String(process.env.PAYPAL_ENCRYPTION_STRICT || "").toLowerCase();
|
|
110
|
+
if (strict === "true" || strict === "1") {
|
|
111
|
+
throw new Error("PAYPAL_ENCRYPTION_STRICT is enabled but PAYPAL_ENCRYPTION_KEY is not set. " +
|
|
112
|
+
"Set PAYPAL_ENCRYPTION_KEY to encrypt PayPal secrets at rest, or disable strict mode.");
|
|
113
|
+
}
|
|
114
|
+
if (!warnedNoKey) {
|
|
115
|
+
warnedNoKey = true;
|
|
116
|
+
const inProd = process.env.NODE_ENV === "production";
|
|
117
|
+
console.warn(`[PayPal]${inProd ? " WARNING (production):" : ""} PAYPAL_ENCRYPTION_KEY is not set — ` +
|
|
118
|
+
"PayPal secrets (client_secret, access_token) are stored UNENCRYPTED. " +
|
|
119
|
+
"Set PAYPAL_ENCRYPTION_KEY to enable AES-256-GCM encryption at rest.");
|
|
120
|
+
}
|
|
121
|
+
}
|
|
99
122
|
/**
|
|
100
123
|
* Encrypt a secret for storage. Returns the input unchanged when no key is
|
|
101
124
|
* configured or when the value is empty/already encrypted. Always writes the
|
|
@@ -106,7 +129,13 @@ function encryptSecret(value) {
|
|
|
106
129
|
return value;
|
|
107
130
|
}
|
|
108
131
|
const raw = getRawKey();
|
|
109
|
-
if (!raw
|
|
132
|
+
if (!raw) {
|
|
133
|
+
if (!isEncrypted(value)) {
|
|
134
|
+
assertOrWarnNoEncryptionKey();
|
|
135
|
+
}
|
|
136
|
+
return value;
|
|
137
|
+
}
|
|
138
|
+
if (isEncrypted(value)) {
|
|
110
139
|
return value;
|
|
111
140
|
}
|
|
112
141
|
const salt = (0, crypto_1.randomBytes)(SALT_LEN);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"secret-crypto.js","sourceRoot":"","sources":["../../../../../../src/modules/paypal/utils/secret-crypto.ts"],"names":[],"mappings":";;AA4FA,8DAEC;AAED,kCAKC;
|
|
1
|
+
{"version":3,"file":"secret-crypto.js","sourceRoot":"","sources":["../../../../../../src/modules/paypal/utils/secret-crypto.ts"],"names":[],"mappings":";;AA4FA,8DAEC;AAED,kCAKC;AAoCD,sCAqBC;AAOD,sCA+BC;AApMD,mCAA8F;AAE9F;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,SAAS,GAAG,SAAS,CAAA;AAC3B,MAAM,SAAS,GAAG,SAAS,CAAA;AAE3B,6EAA6E;AAC7E,4EAA4E;AAC5E,8EAA8E;AAC9E,6DAA6D;AAC7D,MAAM,QAAQ,GAAG,KAAK,CAAA;AACtB,MAAM,QAAQ,GAAG,CAAC,CAAA;AAClB,MAAM,QAAQ,GAAG,CAAC,CAAA;AAClB,MAAM,OAAO,GAAG,EAAE,CAAA;AAClB,MAAM,QAAQ,GAAG,EAAE,CAAA;AAEnB,IAAI,SAA6B,CAAA;AACjC,IAAI,YAAY,GAAkB,IAAI,CAAA;AACtC,IAAI,WAAW,GAAkB,IAAI,CAAA;AACrC,MAAM,gBAAgB,GAAG,GAAG,CAAA;AAC5B,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AAG,EAAE,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC,CAAA;QAC5D,OAAO,UAAU,CAAC,GAAG,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,CAAC,CAAA;IAC9C,CAAC;IAED,oCAAoC;IACpC,MAAM,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,SAAS,CAAC,MAAM,CAAC,CAAA;IAClD,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;IAC9C,IAAI,CAAC,KAAK,IAAI,CAAC,MAAM,IAAI,CAAC,KAAK,EAAE,CAAC;QAChC,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAA;IAC3D,CAAC;IACD,IAAI,CAAC,WAAW,EAAE,CAAC;QACjB,MAAM,IAAI,KAAK,CAAC,kEAAkE,CAAC,CAAA;IACrF,CAAC;IACD,OAAO,UAAU,CAAC,WAAW,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,CAAC,CAAA;AACtD,CAAC"}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { SubscriberArgs, SubscriberConfig } from "@medusajs/framework";
|
|
2
|
+
export declare const PAYPAL_WEBHOOK_RECEIVED_EVENT = "paypal.webhook.received";
|
|
3
|
+
/**
|
|
4
|
+
* Asynchronous PayPal webhook processing.
|
|
5
|
+
*
|
|
6
|
+
* The webhook route verifies the signature, persists the event (status
|
|
7
|
+
* "processing"), emits `paypal.webhook.received`, and returns 200 immediately —
|
|
8
|
+
* so PayPal's ~15s delivery timeout can't be tripped by slow downstream work and
|
|
9
|
+
* the event is never lost. This subscriber does the actual processing off the
|
|
10
|
+
* request path, using its own framework-managed container (no request-scope
|
|
11
|
+
* disposal risk). If the event bus ever drops the message, the webhook retry
|
|
12
|
+
* cron recovers events left in "processing" past a staleness threshold, so
|
|
13
|
+
* delivery is guaranteed either way.
|
|
14
|
+
*/
|
|
15
|
+
export default function paypalWebhookProcessHandler({ event, container, }: SubscriberArgs<{
|
|
16
|
+
id: string;
|
|
17
|
+
}>): Promise<void>;
|
|
18
|
+
export declare const config: SubscriberConfig;
|
|
19
|
+
//# sourceMappingURL=paypal-webhook-process.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"paypal-webhook-process.d.ts","sourceRoot":"","sources":["../../../../src/subscribers/paypal-webhook-process.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAA;AAS3E,eAAO,MAAM,6BAA6B,4BAA4B,CAAA;AAEtE;;;;;;;;;;;GAWG;AACH,wBAA8B,2BAA2B,CAAC,EACxD,KAAK,EACL,SAAS,GACV,EAAE,cAAc,CAAC;IAAE,EAAE,EAAE,MAAM,CAAA;CAAE,CAAC,iBAgGhC;AAED,eAAO,MAAM,MAAM,EAAE,gBAEpB,CAAA"}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.config = exports.PAYPAL_WEBHOOK_RECEIVED_EVENT = void 0;
|
|
4
|
+
exports.default = paypalWebhookProcessHandler;
|
|
5
|
+
const webhook_processor_1 = require("../modules/paypal/webhook-processor");
|
|
6
|
+
exports.PAYPAL_WEBHOOK_RECEIVED_EVENT = "paypal.webhook.received";
|
|
7
|
+
/**
|
|
8
|
+
* Asynchronous PayPal webhook processing.
|
|
9
|
+
*
|
|
10
|
+
* The webhook route verifies the signature, persists the event (status
|
|
11
|
+
* "processing"), emits `paypal.webhook.received`, and returns 200 immediately —
|
|
12
|
+
* so PayPal's ~15s delivery timeout can't be tripped by slow downstream work and
|
|
13
|
+
* the event is never lost. This subscriber does the actual processing off the
|
|
14
|
+
* request path, using its own framework-managed container (no request-scope
|
|
15
|
+
* disposal risk). If the event bus ever drops the message, the webhook retry
|
|
16
|
+
* cron recovers events left in "processing" past a staleness threshold, so
|
|
17
|
+
* delivery is guaranteed either way.
|
|
18
|
+
*/
|
|
19
|
+
async function paypalWebhookProcessHandler({ event, container, }) {
|
|
20
|
+
const recordId = event?.data?.id;
|
|
21
|
+
if (!recordId)
|
|
22
|
+
return;
|
|
23
|
+
const paypal = container.resolve("paypal_onboarding");
|
|
24
|
+
let record;
|
|
25
|
+
try {
|
|
26
|
+
const rows = await paypal.listPayPalWebhookEvents({ id: [recordId] }, { take: 1 });
|
|
27
|
+
record = rows?.[0];
|
|
28
|
+
}
|
|
29
|
+
catch (e) {
|
|
30
|
+
console.error("[PayPal] webhook subscriber: failed to load event", {
|
|
31
|
+
id: recordId,
|
|
32
|
+
error: e?.message,
|
|
33
|
+
});
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
if (!record) {
|
|
37
|
+
console.warn("[PayPal] webhook subscriber: event not found", { id: recordId });
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
// Only process events still queued for the first attempt. Anything already
|
|
41
|
+
// processed/failed/ignored/dead-lettered is owned by the retry cron; skipping
|
|
42
|
+
// here keeps the subscriber idempotent if the bus delivers more than once.
|
|
43
|
+
if (String(record.status) !== "processing") {
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
const eventType = String(record.event_type || "");
|
|
47
|
+
if (!(0, webhook_processor_1.isAllowedEventType)(eventType)) {
|
|
48
|
+
await paypal
|
|
49
|
+
.updateWebhookEventRecord({ id: recordId, status: "ignored", processed_at: new Date() })
|
|
50
|
+
.catch(() => { });
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
try {
|
|
54
|
+
const payload = (record.payload || {});
|
|
55
|
+
const processed = await (0, webhook_processor_1.processPayPalWebhookEvent)(container, { eventType, payload });
|
|
56
|
+
await paypal
|
|
57
|
+
.updateWebhookEventRecord({
|
|
58
|
+
id: recordId,
|
|
59
|
+
status: "processed",
|
|
60
|
+
processed_at: new Date(),
|
|
61
|
+
resource_id: processed.refundId || processed.captureId || processed.orderId || null,
|
|
62
|
+
})
|
|
63
|
+
.catch(() => { });
|
|
64
|
+
console.info("[PayPal] webhook: processed (async)", {
|
|
65
|
+
id: recordId,
|
|
66
|
+
event_type: eventType,
|
|
67
|
+
order_id: processed.orderId,
|
|
68
|
+
capture_id: processed.captureId,
|
|
69
|
+
refund_id: processed.refundId,
|
|
70
|
+
cart_id: processed.cartId,
|
|
71
|
+
session_updated: processed.sessionUpdated,
|
|
72
|
+
});
|
|
73
|
+
await paypal.recordMetric("webhook_success").catch(() => { });
|
|
74
|
+
}
|
|
75
|
+
catch (e) {
|
|
76
|
+
const retryable = (0, webhook_processor_1.isRetryableError)(e);
|
|
77
|
+
const nextStatus = retryable ? "failed" : "dead_letter";
|
|
78
|
+
await paypal
|
|
79
|
+
.updateWebhookEventRecord({
|
|
80
|
+
id: recordId,
|
|
81
|
+
status: nextStatus,
|
|
82
|
+
attempt_count: 1,
|
|
83
|
+
next_retry_at: retryable ? (0, webhook_processor_1.computeNextRetryAt)(1) : null,
|
|
84
|
+
last_error: e?.message || String(e),
|
|
85
|
+
})
|
|
86
|
+
.catch(() => { });
|
|
87
|
+
await paypal
|
|
88
|
+
.recordAuditEvent("webhook_processing_failed", {
|
|
89
|
+
event_id: record.event_id,
|
|
90
|
+
event_type: eventType,
|
|
91
|
+
retryable,
|
|
92
|
+
message: e?.message || String(e),
|
|
93
|
+
})
|
|
94
|
+
.catch(() => { });
|
|
95
|
+
await paypal.recordMetric("webhook_failed").catch(() => { });
|
|
96
|
+
console.error("[PayPal] webhook: processing failed (async)", {
|
|
97
|
+
id: recordId,
|
|
98
|
+
event_type: eventType,
|
|
99
|
+
retryable,
|
|
100
|
+
error: e?.message,
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
exports.config = {
|
|
105
|
+
event: exports.PAYPAL_WEBHOOK_RECEIVED_EVENT,
|
|
106
|
+
};
|
|
107
|
+
//# sourceMappingURL=paypal-webhook-process.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"paypal-webhook-process.js","sourceRoot":"","sources":["../../../../src/subscribers/paypal-webhook-process.ts"],"names":[],"mappings":";;;AAuBA,8CAmGC;AAxHD,2EAK4C;AAE/B,QAAA,6BAA6B,GAAG,yBAAyB,CAAA;AAEtE;;;;;;;;;;;GAWG;AACY,KAAK,UAAU,2BAA2B,CAAC,EACxD,KAAK,EACL,SAAS,GACsB;IAC/B,MAAM,QAAQ,GAAG,KAAK,EAAE,IAAI,EAAE,EAAE,CAAA;IAChC,IAAI,CAAC,QAAQ;QAAE,OAAM;IAErB,MAAM,MAAM,GAAG,SAAS,CAAC,OAAO,CAAsB,mBAAmB,CAAC,CAAA;IAE1E,IAAI,MAAW,CAAA;IACf,IAAI,CAAC;QACH,MAAM,IAAI,GAAG,MAAM,MAAM,CAAC,uBAAuB,CAAC,EAAE,EAAE,EAAE,CAAC,QAAQ,CAAC,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC,EAAE,CAAC,CAAA;QAClF,MAAM,GAAG,IAAI,EAAE,CAAC,CAAC,CAAC,CAAA;IACpB,CAAC;IAAC,OAAO,CAAM,EAAE,CAAC;QAChB,OAAO,CAAC,KAAK,CAAC,mDAAmD,EAAE;YACjE,EAAE,EAAE,QAAQ;YACZ,KAAK,EAAE,CAAC,EAAE,OAAO;SAClB,CAAC,CAAA;QACF,OAAM;IACR,CAAC;IAED,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,OAAO,CAAC,IAAI,CAAC,8CAA8C,EAAE,EAAE,EAAE,EAAE,QAAQ,EAAE,CAAC,CAAA;QAC9E,OAAM;IACR,CAAC;IAED,2EAA2E;IAC3E,8EAA8E;IAC9E,2EAA2E;IAC3E,IAAI,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,YAAY,EAAE,CAAC;QAC3C,OAAM;IACR,CAAC;IAED,MAAM,SAAS,GAAG,MAAM,CAAC,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al` are documented here.
|
|
4
|
+
|
|
5
|
+
## 1.1.0
|
|
6
|
+
|
|
7
|
+
### Fixed
|
|
8
|
+
- **Transient capture/refund failures now retry.** The `paypalFetchWithRetry`
|
|
9
|
+
wrapper (jittered backoff on 5xx/429/timeout) was implemented but never wired
|
|
10
|
+
in — capture and refund used the non-retrying path. They now retry safely: the
|
|
11
|
+
`PayPal-Request-Id` idempotency key means a retry re-uses the same
|
|
12
|
+
capture/refund instead of double-charging.
|
|
13
|
+
- **Provider `recordMetric` is now atomic.** The credential-resolver metric path
|
|
14
|
+
used by the payment providers (capture/refund/authorize success & failure
|
|
15
|
+
counters) now uses a single `INSERT … ON CONFLICT … count = count + 1` upsert
|
|
16
|
+
instead of a read-modify-write, so concurrent captures/refunds no longer lose
|
|
17
|
+
increments. (The module-service metric path remains best-effort and unchanged.)
|
|
18
|
+
- **Capture persisted-but-lost gap is now observable.** After a successful PayPal
|
|
19
|
+
capture, session persistence is retried, and if it still fails the route logs
|
|
20
|
+
CRITICAL and records a `capture_order_persist_failed` metric instead of
|
|
21
|
+
silently swallowing the error (the webhook and `paypal-complete`'s live
|
|
22
|
+
re-derivation remain the reconciliation backstop).
|
|
23
|
+
- **Card provider partial-capture idempotency key** now includes the amount, so
|
|
24
|
+
two sequential partial captures of the same order are no longer deduplicated by
|
|
25
|
+
PayPal into one (matching the wallet provider).
|
|
26
|
+
|
|
27
|
+
### Added
|
|
28
|
+
- **Asynchronous webhook processing.** The webhook route now verifies, persists,
|
|
29
|
+
and acknowledges (200) immediately, then processes off the request path via a
|
|
30
|
+
subscriber — so PayPal's ~15s delivery timeout is never tripped by slow
|
|
31
|
+
downstream work. The retry cron additionally recovers events left in
|
|
32
|
+
`processing` past a staleness threshold, so an event is never lost even if the
|
|
33
|
+
event bus drops a message.
|
|
34
|
+
- **Opt-in rate limiting** on the public store payment routes (`create-order`,
|
|
35
|
+
`capture-order`, `paypal-complete`). Disabled by default (a pass-through) so
|
|
36
|
+
existing deployments are unaffected; enable by setting `PAYPAL_RATE_LIMIT_MAX`
|
|
37
|
+
(and optionally `PAYPAL_RATE_LIMIT_WINDOW_MS`) once you've confirmed the real
|
|
38
|
+
client IP reaches the app (e.g. behind a proxy that forwards `x-forwarded-for`).
|
|
39
|
+
- **Encryption-key guardrail.** When `PAYPAL_ENCRYPTION_KEY` is unset, secrets
|
|
40
|
+
now emit a loud (production-flagged) warning; set `PAYPAL_ENCRYPTION_STRICT=true`
|
|
41
|
+
to fail closed instead of persisting plaintext secrets.
|
|
42
|
+
- Additional unit tests: retry/circuit-breaker behavior, the rate limiter, the
|
|
43
|
+
atomic metric upsert, and session-persistence retry.
|
|
44
|
+
|
|
45
|
+
### Changed
|
|
46
|
+
- **`client_token` is only issued when advanced card fields are enabled** — the
|
|
47
|
+
PayPal-buttons flow uses just `client_id`, so an unauthenticated config fetch no
|
|
48
|
+
longer hands out a card-fields token it won't use.
|
|
49
|
+
- **`postMessage` target origin** for the onboarding return popup is now
|
|
50
|
+
configurable (`PAYPAL_ADMIN_ORIGIN`, falling back to the first `ADMIN_CORS`
|
|
51
|
+
entry) instead of the `"*"` wildcard.
|
|
52
|
+
- **Shared provider base class.** The wallet and advanced-card providers now
|
|
53
|
+
extend a common `PayPalProviderBase` for the identical credential/token
|
|
54
|
+
handling, order lookups, idempotency keys, amount normalization, and status
|
|
55
|
+
mapping — removing a large block of duplicated code. Behavior is unchanged.
|
|
56
|
+
- Centralized the PayPal partner-attribution (BN) code into a single constant and
|
|
57
|
+
removed the unused `PayPalSellerClient` dead code.
|
|
58
|
+
|
|
59
|
+
## 1.0.2
|
|
60
|
+
|
|
61
|
+
### Fixed
|
|
62
|
+
- `toAmountNumber` no longer silently coerces a blank string (`""` / `" "`) or a
|
|
63
|
+
blank serialized `BigNumber` value to `0`. `Number("")` is `0`, so a blank amount
|
|
64
|
+
could previously turn a partial refund/capture into a full one — it now throws
|
|
65
|
+
instead, consistent with the function's existing guards against `NaN`/unparseable
|
|
66
|
+
input.
|
|
67
|
+
|
|
68
|
+
### Added
|
|
69
|
+
- Unit test suite (vitest) covering the money-critical, IO-free logic:
|
|
70
|
+
amount coercion & currency formatting, currency support checks, capture/refund
|
|
71
|
+
status mapping, secret encryption/decryption (AES-256-GCM round-trip, tamper &
|
|
72
|
+
missing-key handling), webhook signature request composition, the webhook state
|
|
73
|
+
machine, retry scheduling, identifier extraction, and provider-id detection.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@easypayment/medusa-payment-paypal",
|
|
3
|
-
"version": "1.0
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"description": "PayPal integration for Medusa v2",
|
|
5
5
|
"author": "EasyPayment Plugins",
|
|
6
6
|
"license": "MIT",
|
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
"scripts",
|
|
13
13
|
"package.json",
|
|
14
14
|
"README.md",
|
|
15
|
+
"CHANGELOG.md",
|
|
15
16
|
"LICENSE",
|
|
16
17
|
"tsconfig.json"
|
|
17
18
|
],
|
|
@@ -1,4 +1,8 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type {
|
|
2
|
+
AuthenticatedMedusaRequest,
|
|
3
|
+
MedusaRequest,
|
|
4
|
+
MedusaResponse,
|
|
5
|
+
} from "@medusajs/framework/http"
|
|
2
6
|
import type PayPalModuleService from "../../../../modules/paypal/service"
|
|
3
7
|
|
|
4
8
|
/**
|
|
@@ -15,7 +19,11 @@ export async function GET(_req: MedusaRequest, res: MedusaResponse) {
|
|
|
15
19
|
})
|
|
16
20
|
}
|
|
17
21
|
|
|
18
|
-
|
|
22
|
+
// Typed as AuthenticatedMedusaRequest: every /admin/* route is gated by
|
|
23
|
+
// Medusa's built-in admin authentication, so this credential-exchange endpoint
|
|
24
|
+
// only runs for an authenticated admin. The typed request makes that contract
|
|
25
|
+
// explicit (and gives access to the authenticated actor if ever needed).
|
|
26
|
+
export async function POST(req: AuthenticatedMedusaRequest, res: MedusaResponse) {
|
|
19
27
|
const paypal = req.scope.resolve<PayPalModuleService>("paypal_onboarding")
|
|
20
28
|
const body = req.body as { authCode?: string; sharedId?: string; env?: "sandbox" | "live" }
|
|
21
29
|
|
package/src/api/middlewares.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { defineMiddlewares } from "@medusajs/framework/http"
|
|
2
|
+
import { createRateLimiter } from "./utils/rate-limit"
|
|
2
3
|
|
|
3
4
|
export default defineMiddlewares({
|
|
4
5
|
routes: [
|
|
@@ -11,9 +12,23 @@ export default defineMiddlewares({
|
|
|
11
12
|
bodyParser: { preserveRawBody: true },
|
|
12
13
|
middlewares: [],
|
|
13
14
|
},
|
|
15
|
+
{
|
|
16
|
+
// Rate-limit the order-creating route: unauthenticated by necessity, so
|
|
17
|
+
// cap how fast one client can spin up PayPal orders on the merchant
|
|
18
|
+
// account. Each createRateLimiter() call builds its own counter at boot.
|
|
19
|
+
matcher: "/store/paypal/create-order",
|
|
20
|
+
method: ["POST"],
|
|
21
|
+
middlewares: [createRateLimiter("create-order")],
|
|
22
|
+
},
|
|
23
|
+
{
|
|
24
|
+
matcher: "/store/paypal/capture-order",
|
|
25
|
+
method: ["POST"],
|
|
26
|
+
middlewares: [createRateLimiter("capture-order")],
|
|
27
|
+
},
|
|
14
28
|
{
|
|
15
29
|
matcher: "/store/paypal-complete",
|
|
16
|
-
|
|
30
|
+
method: ["POST"],
|
|
31
|
+
middlewares: [createRateLimiter("paypal-complete")],
|
|
17
32
|
},
|
|
18
33
|
{
|
|
19
34
|
matcher: "/store/paypal/:path*",
|
|
@@ -34,21 +34,29 @@ function resolveIdempotencyKey(req: MedusaRequest, suffix: string, fallback: str
|
|
|
34
34
|
return fallback || `pp-${suffix}-${randomUUID()}`
|
|
35
35
|
}
|
|
36
36
|
|
|
37
|
+
/**
|
|
38
|
+
* Persist the capture onto the cart's PayPal session. Returns `true` when the
|
|
39
|
+
* data was written (or there was nothing to write because no session exists),
|
|
40
|
+
* and `false` when the write ultimately failed after retries. The caller must
|
|
41
|
+
* NOT silently treat a `false` here as success: the funds were captured at
|
|
42
|
+
* PayPal, so a persistence failure has to be recorded/alerted (the webhook and
|
|
43
|
+
* paypal-complete's live re-derivation are the reconciliation backstop).
|
|
44
|
+
*/
|
|
37
45
|
async function attachPayPalCaptureToSession(
|
|
38
46
|
cartId: string,
|
|
39
47
|
orderId: string,
|
|
40
48
|
capture: any,
|
|
41
49
|
scope: any
|
|
42
|
-
) {
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
}
|
|
50
|
+
): Promise<boolean> {
|
|
51
|
+
const session = await findPayPalSessionForCart(cartId, scope)
|
|
52
|
+
if (!session) {
|
|
53
|
+
console.warn("[PayPal] attachPayPalCaptureToSession: no session found for cart", cartId)
|
|
54
|
+
return true
|
|
55
|
+
}
|
|
49
56
|
|
|
50
|
-
|
|
57
|
+
const captureId = capture?.purchase_units?.[0]?.payments?.captures?.[0]?.id || capture?.id
|
|
51
58
|
|
|
59
|
+
try {
|
|
52
60
|
await updatePayPalSessionData(
|
|
53
61
|
session.session_id,
|
|
54
62
|
{
|
|
@@ -61,9 +69,13 @@ async function attachPayPalCaptureToSession(
|
|
|
61
69
|
},
|
|
62
70
|
scope
|
|
63
71
|
)
|
|
64
|
-
|
|
72
|
+
return true
|
|
65
73
|
} catch (e: unknown) {
|
|
66
|
-
console.
|
|
74
|
+
console.error(
|
|
75
|
+
"[PayPal] attachPayPalCaptureToSession failed:",
|
|
76
|
+
e instanceof Error ? e.message : e
|
|
77
|
+
)
|
|
78
|
+
return false
|
|
67
79
|
}
|
|
68
80
|
}
|
|
69
81
|
|
|
@@ -72,16 +84,16 @@ async function attachPayPalAuthorizationToSession(
|
|
|
72
84
|
orderId: string,
|
|
73
85
|
authorization: any,
|
|
74
86
|
scope: any
|
|
75
|
-
) {
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
}
|
|
87
|
+
): Promise<boolean> {
|
|
88
|
+
const session = await findPayPalSessionForCart(cartId, scope)
|
|
89
|
+
if (!session) {
|
|
90
|
+
console.warn("[PayPal] attachPayPalAuthorizationToSession: no session found for cart", cartId)
|
|
91
|
+
return true
|
|
92
|
+
}
|
|
82
93
|
|
|
83
|
-
|
|
94
|
+
const authorizationId = authorization?.purchase_units?.[0]?.payments?.authorizations?.[0]?.id
|
|
84
95
|
|
|
96
|
+
try {
|
|
85
97
|
await updatePayPalSessionData(
|
|
86
98
|
session.session_id,
|
|
87
99
|
{
|
|
@@ -94,9 +106,13 @@ async function attachPayPalAuthorizationToSession(
|
|
|
94
106
|
},
|
|
95
107
|
scope
|
|
96
108
|
)
|
|
97
|
-
|
|
109
|
+
return true
|
|
98
110
|
} catch (e: unknown) {
|
|
99
|
-
console.
|
|
111
|
+
console.error(
|
|
112
|
+
"[PayPal] attachPayPalAuthorizationToSession failed:",
|
|
113
|
+
e instanceof Error ? e.message : e
|
|
114
|
+
)
|
|
115
|
+
return false
|
|
100
116
|
}
|
|
101
117
|
}
|
|
102
118
|
|
|
@@ -204,8 +220,9 @@ export async function POST(req: MedusaRequest, res: MedusaResponse) {
|
|
|
204
220
|
}
|
|
205
221
|
|
|
206
222
|
const payload = JSON.parse(ppText)
|
|
223
|
+
let persisted = true
|
|
207
224
|
if (paymentAction === "authorize") {
|
|
208
|
-
await attachPayPalAuthorizationToSession(cartId, orderId, payload, req.scope)
|
|
225
|
+
persisted = await attachPayPalAuthorizationToSession(cartId, orderId, payload, req.scope)
|
|
209
226
|
} else {
|
|
210
227
|
// A 2xx capture response does NOT guarantee the funds settled: PayPal
|
|
211
228
|
// returns 201 for PENDING (pending review / eCheck), DECLINED and FAILED
|
|
@@ -221,9 +238,30 @@ export async function POST(req: MedusaRequest, res: MedusaResponse) {
|
|
|
221
238
|
}`
|
|
222
239
|
)
|
|
223
240
|
}
|
|
224
|
-
await attachPayPalCaptureToSession(cartId, orderId, payload, req.scope)
|
|
241
|
+
persisted = await attachPayPalCaptureToSession(cartId, orderId, payload, req.scope)
|
|
225
242
|
}
|
|
226
243
|
|
|
244
|
+
// The PayPal operation itself succeeded. If we could not persist it onto the
|
|
245
|
+
// Medusa session, the money is (authorized/)captured but Medusa doesn't yet
|
|
246
|
+
// record it — record a metric and log CRITICAL so it's observable/alertable.
|
|
247
|
+
// We still return success to the storefront: re-capturing would hit
|
|
248
|
+
// ORDER_ALREADY_CAPTURED, and both the webhook and paypal-complete's live
|
|
249
|
+
// PayPal re-derivation reconcile the session afterward.
|
|
250
|
+
if (!persisted) {
|
|
251
|
+
logger.error(
|
|
252
|
+
`[paypal] CRITICAL: ${
|
|
253
|
+
paymentAction === "authorize" ? "authorization" : "capture"
|
|
254
|
+
} succeeded at PayPal but could not be persisted to the session (request_id=${requestId}, cart_id=${cartId}, order_id=${orderId})`
|
|
255
|
+
)
|
|
256
|
+
try {
|
|
257
|
+
await paypal.recordMetric(
|
|
258
|
+
paymentAction === "authorize"
|
|
259
|
+
? "authorize_order_persist_failed"
|
|
260
|
+
: "capture_order_persist_failed"
|
|
261
|
+
)
|
|
262
|
+
} catch {
|
|
263
|
+
}
|
|
264
|
+
}
|
|
227
265
|
|
|
228
266
|
try {
|
|
229
267
|
await paypal.recordMetric(
|
|
@@ -11,7 +11,6 @@ export async function GET(req: MedusaRequest, res: MedusaResponse) {
|
|
|
11
11
|
try {
|
|
12
12
|
const creds = await paypal.getActiveCredentials()
|
|
13
13
|
const apiDetails = await paypal.getApiDetails().catch(() => null)
|
|
14
|
-
const client_token = await paypal.generateClientToken({ locale: "en_US" }).catch(() => "")
|
|
15
14
|
const cartId = (req.query?.cart_id as string) || ""
|
|
16
15
|
const query = req.scope.resolve("query")
|
|
17
16
|
let currency = normalizeCurrencyCode(
|
|
@@ -74,6 +73,14 @@ export async function GET(req: MedusaRequest, res: MedusaResponse) {
|
|
|
74
73
|
? advancedCardSettings.threeDS
|
|
75
74
|
: "when_required"
|
|
76
75
|
|
|
76
|
+
// The client_token grants the browser SDK API access and is only needed to
|
|
77
|
+
// render the Advanced (hosted) Card Fields. Generate/expose it only when
|
|
78
|
+
// card payments are enabled — the PayPal buttons flow uses just client_id —
|
|
79
|
+
// so an unauthenticated config fetch doesn't hand out a token it won't use.
|
|
80
|
+
const client_token = cardEnabled
|
|
81
|
+
? await paypal.generateClientToken({ locale: "en_US" }).catch(() => "")
|
|
82
|
+
: ""
|
|
83
|
+
|
|
77
84
|
return res.json({
|
|
78
85
|
environment: creds.environment,
|
|
79
86
|
client_id: creds.client_id,
|