@easypayment/medusa-payment-paypal 1.1.1 → 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/.medusa/server/src/admin/index.js +7 -7
- package/.medusa/server/src/admin/index.mjs +7 -7
- package/.medusa/server/src/api/hooks/paypal/onboard-return/route.d.ts +16 -0
- package/.medusa/server/src/api/hooks/paypal/onboard-return/route.d.ts.map +1 -0
- package/.medusa/server/src/api/hooks/paypal/onboard-return/route.js +20 -0
- package/.medusa/server/src/api/hooks/paypal/onboard-return/route.js.map +1 -0
- package/.medusa/server/src/api/hooks/paypal/webhook/route.d.ts +18 -0
- package/.medusa/server/src/api/hooks/paypal/webhook/route.d.ts.map +1 -0
- package/.medusa/server/src/api/hooks/paypal/webhook/route.js +22 -0
- package/.medusa/server/src/api/hooks/paypal/webhook/route.js.map +1 -0
- package/.medusa/server/src/api/middlewares.d.ts.map +1 -1
- package/.medusa/server/src/api/middlewares.js +24 -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 +66 -13
- 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 +8 -0
- package/.medusa/server/src/api/store/paypal/config/route.js.map +1 -1
- package/.medusa/server/src/api/store/paypal/create-order/route.d.ts.map +1 -1
- package/.medusa/server/src/api/store/paypal/create-order/route.js +63 -9
- package/.medusa/server/src/api/store/paypal/create-order/route.js.map +1 -1
- package/.medusa/server/src/api/store/paypal-complete/route.js +1 -1
- package/.medusa/server/src/api/store/paypal-complete/route.js.map +1 -1
- package/.medusa/server/src/api/utils/rate-limit.d.ts +13 -1
- package/.medusa/server/src/api/utils/rate-limit.d.ts.map +1 -1
- package/.medusa/server/src/api/utils/rate-limit.js +18 -7
- package/.medusa/server/src/api/utils/rate-limit.js.map +1 -1
- package/.medusa/server/src/jobs/paypal-webhook-retry.d.ts.map +1 -1
- package/.medusa/server/src/jobs/paypal-webhook-retry.js +4 -0
- package/.medusa/server/src/jobs/paypal-webhook-retry.js.map +1 -1
- package/.medusa/server/src/modules/paypal/payment-provider/base-provider.d.ts +47 -3
- package/.medusa/server/src/modules/paypal/payment-provider/base-provider.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/payment-provider/base-provider.js +73 -0
- package/.medusa/server/src/modules/paypal/payment-provider/base-provider.js.map +1 -1
- 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 +415 -285
- 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 +0 -4
- package/.medusa/server/src/modules/paypal/payment-provider/service.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/payment-provider/service.js +140 -151
- package/.medusa/server/src/modules/paypal/payment-provider/service.js.map +1 -1
- package/.medusa/server/src/modules/paypal/service.d.ts +7 -0
- package/.medusa/server/src/modules/paypal/service.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/service.js +135 -13
- package/.medusa/server/src/modules/paypal/service.js.map +1 -1
- package/.medusa/server/src/modules/paypal/types/config.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/types/config.js +13 -0
- package/.medusa/server/src/modules/paypal/types/config.js.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/amounts.d.ts +1 -1
- package/.medusa/server/src/modules/paypal/utils/credential-resolver.d.ts +10 -0
- package/.medusa/server/src/modules/paypal/utils/credential-resolver.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/credential-resolver.js +49 -34
- package/.medusa/server/src/modules/paypal/utils/credential-resolver.js.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/metrics.d.ts +18 -0
- package/.medusa/server/src/modules/paypal/utils/metrics.d.ts.map +1 -0
- package/.medusa/server/src/modules/paypal/utils/metrics.js +45 -0
- package/.medusa/server/src/modules/paypal/utils/metrics.js.map +1 -0
- package/.medusa/server/src/modules/paypal/utils/paypal-fetch.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/paypal-fetch.js +45 -28
- package/.medusa/server/src/modules/paypal/utils/paypal-fetch.js.map +1 -1
- package/.medusa/server/src/modules/paypal/webhook-processor.d.ts +27 -0
- package/.medusa/server/src/modules/paypal/webhook-processor.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/webhook-processor.js +170 -9
- package/.medusa/server/src/modules/paypal/webhook-processor.js.map +1 -1
- package/.medusa/server/src/subscribers/paypal-webhook-process.d.ts.map +1 -1
- package/.medusa/server/src/subscribers/paypal-webhook-process.js +4 -0
- package/.medusa/server/src/subscribers/paypal-webhook-process.js.map +1 -1
- package/CHANGELOG.md +208 -73
- package/README.md +175 -184
- package/package.json +91 -90
- package/src/api/hooks/paypal/onboard-return/route.ts +15 -0
- package/src/api/hooks/paypal/webhook/route.ts +17 -0
- package/src/api/middlewares.ts +24 -1
- package/src/api/store/paypal/capture-order/route.ts +83 -12
- package/src/api/store/paypal/config/route.ts +8 -0
- package/src/api/store/paypal/create-order/route.ts +73 -9
- package/src/api/store/paypal-complete/route.ts +1 -1
- package/src/api/utils/rate-limit.ts +31 -7
- package/src/jobs/paypal-webhook-retry.ts +4 -0
- package/src/modules/paypal/payment-provider/base-provider.ts +83 -0
- package/src/modules/paypal/payment-provider/card-service.ts +277 -136
- package/src/modules/paypal/payment-provider/service.ts +149 -186
- package/src/modules/paypal/service.ts +1703 -1554
- package/src/modules/paypal/types/config.ts +16 -0
- package/src/modules/paypal/utils/credential-resolver.ts +45 -36
- package/src/modules/paypal/utils/metrics.ts +48 -0
- package/src/modules/paypal/utils/paypal-fetch.ts +58 -29
- package/src/modules/paypal/webhook-processor.ts +195 -10
- package/src/subscribers/paypal-webhook-process.ts +4 -0
|
@@ -4,6 +4,7 @@ import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
|
|
|
4
4
|
import { randomUUID } from "crypto"
|
|
5
5
|
import type PayPalModuleService from "../../../../modules/paypal/service"
|
|
6
6
|
import { getPayPalApiBase } from "../../../../modules/paypal/utils/paypal-auth"
|
|
7
|
+
import { PAYPAL_PARTNER_ATTRIBUTION_ID as BN_CODE } from "../../../../modules/paypal/utils/partner"
|
|
7
8
|
import { paypalFetch } from "../../../../modules/paypal/utils/paypal-fetch"
|
|
8
9
|
import { extractCaptureStatus } from "../../../../modules/paypal/payment-provider/status-utils"
|
|
9
10
|
import {
|
|
@@ -12,8 +13,6 @@ import {
|
|
|
12
13
|
updatePayPalSessionData,
|
|
13
14
|
} from "../../../../modules/paypal/utils/payment-session"
|
|
14
15
|
|
|
15
|
-
const BN_CODE = "MBJTechnolabs_SI_SPB"
|
|
16
|
-
|
|
17
16
|
const PAYPAL_ORDER_ID_RE = /^[A-Z0-9]{10,25}$/
|
|
18
17
|
|
|
19
18
|
type Body = {
|
|
@@ -116,7 +115,29 @@ async function attachPayPalAuthorizationToSession(
|
|
|
116
115
|
}
|
|
117
116
|
}
|
|
118
117
|
|
|
119
|
-
|
|
118
|
+
/**
|
|
119
|
+
* Return the session's existing capture ONLY when it demonstrably COMPLETED.
|
|
120
|
+
*
|
|
121
|
+
* The session can carry a capture that never settled: the webhook processor
|
|
122
|
+
* patches `capture_id` onto the session for every capture event, including
|
|
123
|
+
* PAYMENT.CAPTURE.DENIED and PENDING. Blindly short-circuiting on any stored
|
|
124
|
+
* capture would report success to the storefront for a payment that was
|
|
125
|
+
* declined — the buyer would then hit "payment processed but order could not
|
|
126
|
+
* be finalized" instead of being able to retry.
|
|
127
|
+
*
|
|
128
|
+
* - stored capture object with a known status: COMPLETED → return it,
|
|
129
|
+
* anything else → null (fall through and attempt a real capture).
|
|
130
|
+
* - bare `capture_id` (or a capture object whose status can't be read):
|
|
131
|
+
* verify against the live PayPal order. If PayPal can't be reached, return
|
|
132
|
+
* the stored data — the previous fail-safe behavior — since attempting a
|
|
133
|
+
* fresh capture against an unreachable PayPal would fail anyway.
|
|
134
|
+
*/
|
|
135
|
+
async function getExistingCompletedCapture(
|
|
136
|
+
cartId: string,
|
|
137
|
+
orderId: string,
|
|
138
|
+
scope: any,
|
|
139
|
+
fetchLiveOrder: () => Promise<any>
|
|
140
|
+
) {
|
|
120
141
|
try {
|
|
121
142
|
const session = await findPayPalSessionForCart(cartId, scope)
|
|
122
143
|
if (!session) return null
|
|
@@ -124,8 +145,26 @@ async function getExistingCapture(cartId: string, orderId: string, scope: any) {
|
|
|
124
145
|
const paypalData = (session.session_data || {}).paypal || {}
|
|
125
146
|
const existingOrderId = String(paypalData.order_id || "")
|
|
126
147
|
if (existingOrderId && existingOrderId !== orderId) return null
|
|
127
|
-
|
|
128
|
-
|
|
148
|
+
|
|
149
|
+
const stored = paypalData.capture
|
|
150
|
+
if (stored) {
|
|
151
|
+
const storedStatus = extractCaptureStatus(stored)
|
|
152
|
+
if (storedStatus === "COMPLETED") return stored
|
|
153
|
+
if (storedStatus) return null
|
|
154
|
+
// no readable status on the stored object — verify live below
|
|
155
|
+
}
|
|
156
|
+
if (!stored && !paypalData.capture_id) return null
|
|
157
|
+
|
|
158
|
+
let order: any
|
|
159
|
+
try {
|
|
160
|
+
order = await fetchLiveOrder()
|
|
161
|
+
} catch {
|
|
162
|
+
return stored || { id: paypalData.capture_id }
|
|
163
|
+
}
|
|
164
|
+
const liveCapture = order?.purchase_units?.[0]?.payments?.captures?.[0]
|
|
165
|
+
if (liveCapture && extractCaptureStatus(liveCapture) === "COMPLETED") {
|
|
166
|
+
return liveCapture
|
|
167
|
+
}
|
|
129
168
|
return null
|
|
130
169
|
} catch {
|
|
131
170
|
return null
|
|
@@ -173,16 +212,39 @@ export async function POST(req: MedusaRequest, res: MedusaResponse) {
|
|
|
173
212
|
})
|
|
174
213
|
}
|
|
175
214
|
|
|
176
|
-
const existingCapture = await getExistingCapture(cartId, orderId, scope)
|
|
177
|
-
if (existingCapture) {
|
|
178
|
-
return res.json({ capture: existingCapture })
|
|
179
|
-
}
|
|
180
|
-
|
|
181
215
|
const creds = await paypal.getActiveCredentials()
|
|
182
216
|
// Cached app access token (single-flight refresh) — avoids an OAuth
|
|
183
217
|
// round-trip on every capture-order call.
|
|
184
218
|
const base = getPayPalApiBase(creds.environment)
|
|
185
219
|
const accessToken = await paypal.getAppAccessToken()
|
|
220
|
+
|
|
221
|
+
const fetchLiveOrder = async () => {
|
|
222
|
+
const resp = await paypalFetch(
|
|
223
|
+
`${base}/v2/checkout/orders/${encodeURIComponent(orderId)}`,
|
|
224
|
+
{
|
|
225
|
+
method: "GET",
|
|
226
|
+
headers: {
|
|
227
|
+
Authorization: `Bearer ${accessToken}`,
|
|
228
|
+
"Content-Type": "application/json",
|
|
229
|
+
},
|
|
230
|
+
}
|
|
231
|
+
)
|
|
232
|
+
if (!resp.ok) {
|
|
233
|
+
throw new Error(`PayPal get order error (${resp.status})`)
|
|
234
|
+
}
|
|
235
|
+
return resp.json()
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
const existingCapture = await getExistingCompletedCapture(
|
|
239
|
+
cartId,
|
|
240
|
+
orderId,
|
|
241
|
+
scope,
|
|
242
|
+
fetchLiveOrder
|
|
243
|
+
)
|
|
244
|
+
if (existingCapture) {
|
|
245
|
+
return res.json({ capture: existingCapture })
|
|
246
|
+
}
|
|
247
|
+
|
|
186
248
|
const settings = await paypal.getSettings().catch(() => ({}))
|
|
187
249
|
const data =
|
|
188
250
|
settings && typeof settings === "object" && "data" in settings
|
|
@@ -194,7 +256,16 @@ export async function POST(req: MedusaRequest, res: MedusaResponse) {
|
|
|
194
256
|
? additionalSettings.paymentAction
|
|
195
257
|
: "capture"
|
|
196
258
|
|
|
197
|
-
|
|
259
|
+
// The suffix must include the order id: PayPal deduplicates by
|
|
260
|
+
// PayPal-Request-Id, so a client reusing one Idempotency-Key header across
|
|
261
|
+
// two different orders would otherwise get order A's cached capture back
|
|
262
|
+
// for order B. Named `paypalRequestId` so it never shadows `requestId`
|
|
263
|
+
// (the log/response correlation UUID declared at the top of POST).
|
|
264
|
+
const paypalRequestId = resolveIdempotencyKey(
|
|
265
|
+
req,
|
|
266
|
+
`capture-order-${orderId}`,
|
|
267
|
+
`pp-capture-${orderId}`
|
|
268
|
+
)
|
|
198
269
|
const safeOrderId = encodeURIComponent(orderId)
|
|
199
270
|
const endpoint =
|
|
200
271
|
paymentAction === "authorize"
|
|
@@ -206,7 +277,7 @@ export async function POST(req: MedusaRequest, res: MedusaResponse) {
|
|
|
206
277
|
headers: {
|
|
207
278
|
Authorization: `Bearer ${accessToken}`,
|
|
208
279
|
"Content-Type": "application/json",
|
|
209
|
-
"PayPal-Request-Id":
|
|
280
|
+
"PayPal-Request-Id": paypalRequestId,
|
|
210
281
|
"PayPal-Partner-Attribution-Id": BN_CODE,
|
|
211
282
|
},
|
|
212
283
|
})
|
|
@@ -100,6 +100,14 @@ export async function GET(req: MedusaRequest, res: MedusaResponse) {
|
|
|
100
100
|
button_width: paypalSettings.buttonWidth || "responsive",
|
|
101
101
|
button_height: paypalSettings.buttonHeight ?? 45,
|
|
102
102
|
button_label: paypalSettings.buttonLabel || "paypal",
|
|
103
|
+
// Funding sources to disable in the PayPal JS SDK (e.g. ["card",
|
|
104
|
+
// "paylater"]). The UI package has always read this field; emit it so
|
|
105
|
+
// the setting actually takes effect.
|
|
106
|
+
disable_buttons: Array.isArray(paypalSettings.disableButtons)
|
|
107
|
+
? paypalSettings.disableButtons.map((b: unknown) => String(b))
|
|
108
|
+
: Array.isArray(paypalSettings.disable_buttons)
|
|
109
|
+
? paypalSettings.disable_buttons.map((b: unknown) => String(b))
|
|
110
|
+
: [],
|
|
103
111
|
})
|
|
104
112
|
} catch {
|
|
105
113
|
return res.status(500).json({ message: "Failed to load PayPal config" })
|
|
@@ -8,6 +8,7 @@ import {
|
|
|
8
8
|
normalizeCurrencyCode,
|
|
9
9
|
} from "../../../../modules/paypal/utils/currencies"
|
|
10
10
|
import { getPayPalApiBase } from "../../../../modules/paypal/utils/paypal-auth"
|
|
11
|
+
import { PAYPAL_PARTNER_ATTRIBUTION_ID as BN_CODE } from "../../../../modules/paypal/utils/partner"
|
|
11
12
|
import { paypalFetch } from "../../../../modules/paypal/utils/paypal-fetch"
|
|
12
13
|
import type PayPalModuleService from "../../../../modules/paypal/service"
|
|
13
14
|
import {
|
|
@@ -16,8 +17,6 @@ import {
|
|
|
16
17
|
updatePayPalSessionData,
|
|
17
18
|
} from "../../../../modules/paypal/utils/payment-session"
|
|
18
19
|
|
|
19
|
-
const BN_CODE = "MBJTechnolabs_SI_SPB"
|
|
20
|
-
|
|
21
20
|
type Body = {
|
|
22
21
|
cart_id: string
|
|
23
22
|
is_card_payment?: boolean
|
|
@@ -31,6 +30,10 @@ function resolveIdempotencyKey(req: MedusaRequest, suffix: string, fallback: str
|
|
|
31
30
|
req.headers["X-Idempotency-Key"]
|
|
32
31
|
const key = Array.isArray(header) ? header[0] : header
|
|
33
32
|
if (key && String(key).trim()) {
|
|
33
|
+
// The suffix must include the cart id (callers pass it): PayPal caches by
|
|
34
|
+
// PayPal-Request-Id, so a client reusing one idempotency-key header across
|
|
35
|
+
// two carts would otherwise get cart A's cached order (A's amount) back
|
|
36
|
+
// for cart B.
|
|
34
37
|
return `${String(key).trim()}-${suffix}`
|
|
35
38
|
}
|
|
36
39
|
return fallback || `pp-${suffix}-${randomUUID()}`
|
|
@@ -102,10 +105,11 @@ export async function POST(req: MedusaRequest, res: MedusaResponse) {
|
|
|
102
105
|
return res.status(400).json({ message: "Invalid cart_id format" })
|
|
103
106
|
}
|
|
104
107
|
|
|
108
|
+
// A stored order id is only reused after verifying it still matches the
|
|
109
|
+
// cart (amount/currency/state) — see below, once the cart is loaded. Buyers
|
|
110
|
+
// who back out of the PayPal popup and change their cart would otherwise be
|
|
111
|
+
// charged the stale total.
|
|
105
112
|
const existingOrderId = await getExistingPayPalOrderId(req, cartId)
|
|
106
|
-
if (existingOrderId) {
|
|
107
|
-
return res.json({ id: existingOrderId })
|
|
108
|
-
}
|
|
109
113
|
|
|
110
114
|
const query = req.scope.resolve("query")
|
|
111
115
|
|
|
@@ -181,6 +185,57 @@ export async function POST(req: MedusaRequest, res: MedusaResponse) {
|
|
|
181
185
|
const totalMajor = Number(cart.total || 0)
|
|
182
186
|
const value = totalMajor.toFixed(exponent)
|
|
183
187
|
|
|
188
|
+
// Reuse the stored PayPal order only when it still matches the cart: same
|
|
189
|
+
// amount, same currency, and still in a reusable (pre-terminal) state. On
|
|
190
|
+
// mismatch fall through and create a fresh order (which replaces the
|
|
191
|
+
// stored id on the session). If PayPal can't be reached for the check,
|
|
192
|
+
// reuse the stored id — matching the previous behavior rather than
|
|
193
|
+
// blocking checkout on a transient error.
|
|
194
|
+
if (existingOrderId) {
|
|
195
|
+
try {
|
|
196
|
+
const checkBase = getPayPalApiBase(creds.environment)
|
|
197
|
+
const checkToken = await paypal.getAppAccessToken()
|
|
198
|
+
const checkResp = await paypalFetch(
|
|
199
|
+
`${checkBase}/v2/checkout/orders/${encodeURIComponent(existingOrderId)}`,
|
|
200
|
+
{
|
|
201
|
+
method: "GET",
|
|
202
|
+
headers: {
|
|
203
|
+
Authorization: `Bearer ${checkToken}`,
|
|
204
|
+
"Content-Type": "application/json",
|
|
205
|
+
},
|
|
206
|
+
}
|
|
207
|
+
)
|
|
208
|
+
if (checkResp.ok) {
|
|
209
|
+
const existingOrder = await checkResp.json()
|
|
210
|
+
const existingAmount = existingOrder?.purchase_units?.[0]?.amount
|
|
211
|
+
const existingStatus = String(existingOrder?.status || "").toUpperCase()
|
|
212
|
+
const reusableStatus = ["CREATED", "APPROVED", "PAYER_ACTION_REQUIRED"].includes(
|
|
213
|
+
existingStatus
|
|
214
|
+
)
|
|
215
|
+
const amountMatches =
|
|
216
|
+
String(existingAmount?.value || "") === value &&
|
|
217
|
+
String(existingAmount?.currency_code || "").toUpperCase() === currency
|
|
218
|
+
if (reusableStatus && amountMatches) {
|
|
219
|
+
return res.json({ id: existingOrderId })
|
|
220
|
+
}
|
|
221
|
+
if (existingStatus === "COMPLETED") {
|
|
222
|
+
// Already paid — never mint a second order for this cart.
|
|
223
|
+
return res.json({ id: existingOrderId })
|
|
224
|
+
}
|
|
225
|
+
logger.info(
|
|
226
|
+
`[paypal] create-order: stored order ${existingOrderId} is stale (status=${existingStatus}, amount=${existingAmount?.value} ${existingAmount?.currency_code} vs cart ${value} ${currency}) — creating a fresh order (request_id=${requestId})`
|
|
227
|
+
)
|
|
228
|
+
} else if (checkResp.status !== 404) {
|
|
229
|
+
// Transient PayPal-side failure: reuse rather than block checkout.
|
|
230
|
+
return res.json({ id: existingOrderId })
|
|
231
|
+
}
|
|
232
|
+
// 404: the stored order no longer exists (e.g. environment switched) —
|
|
233
|
+
// fall through and create a fresh one.
|
|
234
|
+
} catch {
|
|
235
|
+
return res.json({ id: existingOrderId })
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
184
239
|
const paymentActionRaw =
|
|
185
240
|
typeof additionalSettings.paymentAction === "string"
|
|
186
241
|
? additionalSettings.paymentAction
|
|
@@ -375,10 +430,19 @@ export async function POST(req: MedusaRequest, res: MedusaResponse) {
|
|
|
375
430
|
const base = getPayPalApiBase(creds.environment)
|
|
376
431
|
const accessToken = await paypal.getAppAccessToken()
|
|
377
432
|
|
|
378
|
-
// Deterministic-per-cart idempotency key for the PayPal
|
|
379
|
-
//
|
|
380
|
-
//
|
|
381
|
-
|
|
433
|
+
// Deterministic-per-(cart, amount, currency) idempotency key for the PayPal
|
|
434
|
+
// call. The amount/currency MUST be part of the key: PayPal replays the
|
|
435
|
+
// cached response for a reused PayPal-Request-Id, so a key derived from the
|
|
436
|
+
// cart id alone would return the ORIGINAL order (at the original total)
|
|
437
|
+
// when the buyer changes the cart and a fresh order is minted — silently
|
|
438
|
+
// re-charging the stale amount and defeating the staleness check above.
|
|
439
|
+
// Kept distinct from `requestId` (the log/response correlation id declared
|
|
440
|
+
// at the top of POST) so the two never shadow each other.
|
|
441
|
+
const paypalRequestId = resolveIdempotencyKey(
|
|
442
|
+
req,
|
|
443
|
+
`create-order-${cart.id}-${value}-${currency}`,
|
|
444
|
+
`pp-create-${cart.id}-${value}-${currency}`
|
|
445
|
+
)
|
|
382
446
|
|
|
383
447
|
const ppResp = await paypalFetch(`${base}/v2/checkout/orders`, {
|
|
384
448
|
method: "POST",
|
|
@@ -8,7 +8,7 @@ import { runCoreWorkflow } from "../../../modules/paypal/utils/core-workflow"
|
|
|
8
8
|
export async function POST(req: MedusaRequest, res: MedusaResponse) {
|
|
9
9
|
const logger = req.scope.resolve<Logger>(ContainerRegistrationKeys.LOGGER)
|
|
10
10
|
const requestId = randomUUID()
|
|
11
|
-
const { cart_id } = req.body as { cart_id: string }
|
|
11
|
+
const { cart_id } = (req.body || {}) as { cart_id: string }
|
|
12
12
|
|
|
13
13
|
if (!cart_id || typeof cart_id !== "string") {
|
|
14
14
|
return res.status(400).json({ message: "cart_id is required" })
|
|
@@ -36,25 +36,49 @@ function readEnvInt(name: string, fallback: number): number {
|
|
|
36
36
|
}
|
|
37
37
|
|
|
38
38
|
/** The configured max, or null when rate limiting is disabled (opt-in). */
|
|
39
|
-
function readConfiguredMax(): number | null {
|
|
40
|
-
const raw = process.env
|
|
39
|
+
function readConfiguredMax(envVar: string): number | null {
|
|
40
|
+
const raw = process.env[envVar]
|
|
41
41
|
if (raw === undefined || raw === "") return null
|
|
42
42
|
const v = Number(raw)
|
|
43
43
|
return Number.isFinite(v) && v > 0 ? v : null
|
|
44
44
|
}
|
|
45
45
|
|
|
46
46
|
function clientKey(req: MedusaRequest): string {
|
|
47
|
+
// Use the RIGHT-most x-forwarded-for entry: proxies append the address they
|
|
48
|
+
// received the request from, so the right-most value was written by the
|
|
49
|
+
// merchant's own edge proxy and cannot be forged by the client. The
|
|
50
|
+
// left-most entry is fully client-controlled — keying on it would let an
|
|
51
|
+
// attacker rotate a header value to get a fresh bucket per request,
|
|
52
|
+
// bypassing the limiter entirely.
|
|
47
53
|
const fwd = req.headers["x-forwarded-for"]
|
|
48
|
-
const
|
|
54
|
+
const fwdRaw = Array.isArray(fwd) ? fwd[fwd.length - 1] : fwd
|
|
55
|
+
const parts = fwdRaw
|
|
56
|
+
? fwdRaw.split(",").map((s) => s.trim()).filter(Boolean)
|
|
57
|
+
: []
|
|
49
58
|
const ip =
|
|
50
|
-
|
|
59
|
+
parts[parts.length - 1] ||
|
|
51
60
|
req.socket?.remoteAddress ||
|
|
52
61
|
"unknown"
|
|
53
62
|
return ip
|
|
54
63
|
}
|
|
55
64
|
|
|
56
|
-
export
|
|
65
|
+
export type RateLimiterOptions = {
|
|
66
|
+
/**
|
|
67
|
+
* Env var holding the request cap for this limiter. Defaults to the shared
|
|
68
|
+
* PAYPAL_RATE_LIMIT_MAX. The webhook routes pass their own dedicated var:
|
|
69
|
+
* PayPal delivers from a handful of egress IPs, so a cap sized for
|
|
70
|
+
* individual buyers would throttle legitimate webhook bursts (a sale spike)
|
|
71
|
+
* into 429-driven redelivery loops.
|
|
72
|
+
*/
|
|
73
|
+
maxEnvVar?: string
|
|
74
|
+
/** Env var for the window; defaults to PAYPAL_RATE_LIMIT_WINDOW_MS. */
|
|
75
|
+
windowEnvVar?: string
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function createRateLimiter(scope: string, options: RateLimiterOptions = {}) {
|
|
57
79
|
const buckets = new Map<string, Bucket>()
|
|
80
|
+
const maxEnvVar = options.maxEnvVar || "PAYPAL_RATE_LIMIT_MAX"
|
|
81
|
+
const windowEnvVar = options.windowEnvVar || "PAYPAL_RATE_LIMIT_WINDOW_MS"
|
|
58
82
|
|
|
59
83
|
return function rateLimit(
|
|
60
84
|
req: MedusaRequest,
|
|
@@ -63,11 +87,11 @@ export function createRateLimiter(scope: string) {
|
|
|
63
87
|
) {
|
|
64
88
|
// Opt-in: with no configured max, this middleware is a pass-through so
|
|
65
89
|
// existing deployments (especially behind a shared-IP proxy) are unaffected.
|
|
66
|
-
const max = readConfiguredMax()
|
|
90
|
+
const max = readConfiguredMax(maxEnvVar)
|
|
67
91
|
if (max === null) {
|
|
68
92
|
return next()
|
|
69
93
|
}
|
|
70
|
-
const windowMs = readEnvInt(
|
|
94
|
+
const windowMs = readEnvInt(windowEnvVar, DEFAULT_WINDOW_MS)
|
|
71
95
|
const now = Date.now()
|
|
72
96
|
const key = `${scope}:${clientKey(req)}`
|
|
73
97
|
|
|
@@ -183,8 +183,12 @@ async function attemptRetry(
|
|
|
183
183
|
capture_id: processed.captureId,
|
|
184
184
|
cart_id: processed.cartId,
|
|
185
185
|
session_updated: processed.sessionUpdated,
|
|
186
|
+
cart_completed: processed.cartCompleted,
|
|
186
187
|
})
|
|
187
188
|
|
|
189
|
+
if (processed.cartCompleted) {
|
|
190
|
+
await paypal.recordMetric("webhook_cart_completed").catch(() => {})
|
|
191
|
+
}
|
|
188
192
|
await paypal.recordMetric("webhook_retry_success").catch(() => {})
|
|
189
193
|
} catch (error: any) {
|
|
190
194
|
const retryable = isRetryableError(error)
|
|
@@ -59,6 +59,37 @@ export abstract class PayPalProviderBase extends AbstractPaymentProvider<Options
|
|
|
59
59
|
)
|
|
60
60
|
}
|
|
61
61
|
|
|
62
|
+
/** Serialize an error for audit metadata without losing cause chains. */
|
|
63
|
+
protected serializeError(error: unknown) {
|
|
64
|
+
if (error instanceof Error) {
|
|
65
|
+
const errorWithCause = error as Error & { cause?: unknown }
|
|
66
|
+
const cause = errorWithCause.cause
|
|
67
|
+
return {
|
|
68
|
+
name: error.name,
|
|
69
|
+
message: error.message,
|
|
70
|
+
stack: error.stack,
|
|
71
|
+
cause:
|
|
72
|
+
cause instanceof Error
|
|
73
|
+
? { name: cause.name, message: cause.message, stack: cause.stack }
|
|
74
|
+
: cause,
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return { message: String(error) }
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
protected async recordFailure(eventType: string, metadata?: Record<string, unknown>) {
|
|
81
|
+
await this.paypal.recordAuditEvent(eventType, metadata)
|
|
82
|
+
await this.paypal.recordMetric(eventType, metadata)
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
protected async recordSuccess(metricName: string) {
|
|
86
|
+
await this.paypal.recordMetric(metricName)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
protected async recordPaymentEvent(eventType: string, metadata?: Record<string, unknown>) {
|
|
90
|
+
await this.paypal.recordAuditEvent(eventType, metadata)
|
|
91
|
+
}
|
|
92
|
+
|
|
62
93
|
protected generateSessionId(): string {
|
|
63
94
|
try {
|
|
64
95
|
return randomUUID()
|
|
@@ -135,6 +166,58 @@ export abstract class PayPalProviderBase extends AbstractPaymentProvider<Options
|
|
|
135
166
|
return formatAmountForPayPal(amount, currencyCode || "EUR")
|
|
136
167
|
}
|
|
137
168
|
|
|
169
|
+
/**
|
|
170
|
+
* Amount to send to PayPal for a capture. Medusa invokes the provider's
|
|
171
|
+
* capturePayment with only `{ data, context: { idempotency_key } }` — the
|
|
172
|
+
* admin's requested (possibly partial) capture amount is never passed in the
|
|
173
|
+
* input. The idempotency_key IS the Medusa `capture` row id, so resolve the
|
|
174
|
+
* requested amount from that row; otherwise a partial capture would silently
|
|
175
|
+
* charge the buyer the full session total. Falls back to the session amount
|
|
176
|
+
* when the row can't be resolved (preserving full-capture behavior), and
|
|
177
|
+
* never returns more than the session amount.
|
|
178
|
+
*/
|
|
179
|
+
protected async resolveRequestedCaptureAmount(
|
|
180
|
+
input: { context?: { idempotency_key?: string } },
|
|
181
|
+
sessionAmount: number
|
|
182
|
+
): Promise<number> {
|
|
183
|
+
const captureRowId = input?.context?.idempotency_key?.trim()
|
|
184
|
+
if (!captureRowId) return sessionAmount
|
|
185
|
+
const requested = await this.paypal.getRequestedCaptureAmount(captureRowId)
|
|
186
|
+
if (requested === null || !Number.isFinite(requested) || requested <= 0) {
|
|
187
|
+
return sessionAmount
|
|
188
|
+
}
|
|
189
|
+
return Math.min(requested, sessionAmount)
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* When the session amount or currency changes while a not-yet-approved PayPal
|
|
194
|
+
* order is stored on the session, drop the stored order reference so the next
|
|
195
|
+
* create-order call mints a fresh order at the correct total. Without this, a
|
|
196
|
+
* buyer who opens PayPal (order created for the old total), backs out, and
|
|
197
|
+
* changes the cart gets charged the stale amount. Returns a `{ paypal }`
|
|
198
|
+
* patch to spread into the updated session data, or `{}` when nothing needs
|
|
199
|
+
* invalidating. Sessions that already carry a capture/authorization are never
|
|
200
|
+
* touched.
|
|
201
|
+
*/
|
|
202
|
+
protected invalidateStaleOrder(
|
|
203
|
+
input: { data?: Record<string, unknown>; amount?: unknown },
|
|
204
|
+
nextCurrencyCode: string
|
|
205
|
+
): Record<string, unknown> {
|
|
206
|
+
const data = (input.data || {}) as Record<string, any>
|
|
207
|
+
const paypal = (data.paypal || {}) as Record<string, any>
|
|
208
|
+
if (!paypal.order_id) return {}
|
|
209
|
+
if (paypal.capture_id || paypal.authorization_id) return {}
|
|
210
|
+
const prevAmount = toAmountNumber(data.amount)
|
|
211
|
+
const nextAmount = toAmountNumber(input.amount)
|
|
212
|
+
const prevCurrency = String(data.currency_code || "").toUpperCase()
|
|
213
|
+
const amountChanged =
|
|
214
|
+
prevAmount > 0 && nextAmount > 0 && prevAmount !== nextAmount
|
|
215
|
+
const currencyChanged = !!prevCurrency && prevCurrency !== nextCurrencyCode
|
|
216
|
+
if (!amountChanged && !currencyChanged) return {}
|
|
217
|
+
const { order_id: _orderId, order: _order, ...rest } = paypal
|
|
218
|
+
return { paypal: rest }
|
|
219
|
+
}
|
|
220
|
+
|
|
138
221
|
protected mapCaptureStatus(status?: string) {
|
|
139
222
|
// Delegate to the shared, unit-tested mapping so the card and wallet
|
|
140
223
|
// providers agree with each other and with the webhook processor. Notably a
|