@easypayment/medusa-payment-paypal 1.1.0 → 1.1.2
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 +73 -73
- package/.medusa/server/src/admin/index.mjs +73 -73
- 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 +9 -0
- package/.medusa/server/src/api/middlewares.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 +53 -4
- 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.map +1 -1
- package/.medusa/server/src/api/utils/rate-limit.js +11 -2
- package/.medusa/server/src/api/utils/rate-limit.js.map +1 -1
- package/.medusa/server/src/modules/paypal/payment-provider/base-provider.d.ts +32 -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 +47 -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 +172 -117
- 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.map +1 -1
- package/.medusa/server/src/modules/paypal/payment-provider/service.js +132 -126
- package/.medusa/server/src/modules/paypal/payment-provider/service.js.map +1 -1
- package/.medusa/server/src/modules/paypal/service.d.ts +5 -0
- package/.medusa/server/src/modules/paypal/service.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/service.js +82 -1
- package/.medusa/server/src/modules/paypal/service.js.map +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 +39 -0
- package/.medusa/server/src/modules/paypal/utils/credential-resolver.js.map +1 -1
- 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 +11 -0
- package/.medusa/server/src/modules/paypal/webhook-processor.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/webhook-processor.js +85 -7
- package/.medusa/server/src/modules/paypal/webhook-processor.js.map +1 -1
- package/CHANGELOG.md +73 -0
- package/package.json +4 -5
- 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 +9 -0
- package/src/api/store/paypal/config/route.ts +8 -0
- package/src/api/store/paypal/create-order/route.ts +64 -4
- package/src/api/store/paypal-complete/route.ts +1 -1
- package/src/api/utils/rate-limit.ts +11 -2
- package/src/modules/paypal/payment-provider/base-provider.ts +52 -0
- package/src/modules/paypal/payment-provider/card-service.ts +193 -136
- package/src/modules/paypal/payment-provider/service.ts +137 -156
- package/src/modules/paypal/service.ts +98 -1
- package/src/modules/paypal/utils/credential-resolver.ts +36 -0
- package/src/modules/paypal/utils/paypal-fetch.ts +58 -29
- package/src/modules/paypal/webhook-processor.ts +94 -8
|
@@ -112,6 +112,7 @@ class PayPalPaymentProvider extends PayPalProviderBase {
|
|
|
112
112
|
return {
|
|
113
113
|
data: {
|
|
114
114
|
...(input.data || {}),
|
|
115
|
+
...this.invalidateStaleOrder(input, currencyCode),
|
|
115
116
|
...(providerId ? { provider_id: providerId } : {}),
|
|
116
117
|
amount: input.amount,
|
|
117
118
|
currency_code: currencyCode,
|
|
@@ -122,29 +123,22 @@ class PayPalPaymentProvider extends PayPalProviderBase {
|
|
|
122
123
|
async authorizePayment(
|
|
123
124
|
input: AuthorizePaymentInput
|
|
124
125
|
): Promise<AuthorizePaymentOutput> {
|
|
125
|
-
const { data
|
|
126
|
+
const { data } = await this.normalizePaymentData(input)
|
|
126
127
|
const existingPayPal = (data.paypal || {}) as Record<string, any>
|
|
127
128
|
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
const
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
if (
|
|
137
|
-
existingPayPal.capture_id ||
|
|
138
|
-
existingPayPal.authorization_id ||
|
|
139
|
-
(data as any).authorized_at ||
|
|
140
|
-
(data as any).captured_at
|
|
141
|
-
) {
|
|
142
|
-
console.info("[PayPal] authorizePayment: session already processed, returning", returnStatus)
|
|
129
|
+
// Session already carries a settled capture: trust it without a network
|
|
130
|
+
// round-trip. The stored capture object is only written after a COMPLETED
|
|
131
|
+
// gate (capture-order route / capturePayment), but re-verify its status
|
|
132
|
+
// here so a PENDING/DECLINED capture patched in by a webhook is never
|
|
133
|
+
// booked as captured money.
|
|
134
|
+
const storedCaptureStatus = extractCaptureStatus(existingPayPal.capture)
|
|
135
|
+
if (storedCaptureStatus === "COMPLETED") {
|
|
136
|
+
console.info("[PayPal] authorizePayment: session already captured (COMPLETED)")
|
|
143
137
|
return {
|
|
144
|
-
status:
|
|
138
|
+
status: "captured",
|
|
145
139
|
data: {
|
|
146
140
|
...(input.data || {}),
|
|
147
|
-
|
|
141
|
+
captured_at: (data as any).captured_at || new Date().toISOString(),
|
|
148
142
|
},
|
|
149
143
|
}
|
|
150
144
|
}
|
|
@@ -157,25 +151,92 @@ class PayPalPaymentProvider extends PayPalProviderBase {
|
|
|
157
151
|
const capture = order?.purchase_units?.[0]?.payments?.captures?.[0]
|
|
158
152
|
const authorization = order?.purchase_units?.[0]?.payments?.authorizations?.[0]
|
|
159
153
|
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
154
|
+
// Derive the returned status from what actually happened at PayPal —
|
|
155
|
+
// NOT from the mere presence of a capture/authorization id and NOT
|
|
156
|
+
// from the merchant's configured paymentAction. A PENDING capture
|
|
157
|
+
// (eCheck / pending review) must not be booked as captured, and a
|
|
158
|
+
// DENIED/DECLINED one must fail the authorization outright.
|
|
159
|
+
if (capture?.id) {
|
|
160
|
+
const captureStatus = this.mapCaptureStatus(capture?.status)
|
|
161
|
+
if (captureStatus === "captured") {
|
|
162
|
+
return {
|
|
163
|
+
status: "captured",
|
|
164
|
+
data: {
|
|
165
|
+
...(input.data || {}),
|
|
166
|
+
paypal: {
|
|
167
|
+
...existingPayPal,
|
|
168
|
+
order_id: orderId,
|
|
169
|
+
order,
|
|
170
|
+
authorization_id: authorization?.id || existingPayPal.authorization_id,
|
|
171
|
+
capture_id: capture.id,
|
|
172
|
+
capture,
|
|
173
|
+
},
|
|
174
|
+
captured_at: new Date().toISOString(),
|
|
172
175
|
},
|
|
173
|
-
|
|
174
|
-
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
if (captureStatus === "pending") {
|
|
179
|
+
// Funds are in flight (eCheck etc.): place the order as authorized
|
|
180
|
+
// so checkout completes, but never mark it captured — the
|
|
181
|
+
// CAPTURE.COMPLETED webhook settles it later.
|
|
182
|
+
return {
|
|
183
|
+
status: "authorized",
|
|
184
|
+
data: {
|
|
185
|
+
...(input.data || {}),
|
|
186
|
+
paypal: {
|
|
187
|
+
...existingPayPal,
|
|
188
|
+
order_id: orderId,
|
|
189
|
+
order,
|
|
190
|
+
capture_id: capture.id,
|
|
191
|
+
},
|
|
192
|
+
authorized_at: new Date().toISOString(),
|
|
193
|
+
},
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
if (captureStatus === "error" || captureStatus === "canceled") {
|
|
197
|
+
return {
|
|
198
|
+
status: "error",
|
|
199
|
+
data: {
|
|
200
|
+
...(input.data || {}),
|
|
201
|
+
paypal: { ...existingPayPal, order_id: orderId, order },
|
|
202
|
+
},
|
|
203
|
+
}
|
|
175
204
|
}
|
|
176
205
|
}
|
|
177
206
|
|
|
178
|
-
if (
|
|
207
|
+
if (authorization?.id) {
|
|
208
|
+
const authStatus = this.mapAuthorizationStatus(authorization?.status)
|
|
209
|
+
if (authStatus === "authorized") {
|
|
210
|
+
return {
|
|
211
|
+
status: "authorized",
|
|
212
|
+
data: {
|
|
213
|
+
...(input.data || {}),
|
|
214
|
+
paypal: {
|
|
215
|
+
...existingPayPal,
|
|
216
|
+
order_id: orderId,
|
|
217
|
+
order,
|
|
218
|
+
authorization_id: authorization.id,
|
|
219
|
+
},
|
|
220
|
+
authorized_at: new Date().toISOString(),
|
|
221
|
+
},
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
if (authStatus === "error" || authStatus === "canceled") {
|
|
225
|
+
return {
|
|
226
|
+
status: "error",
|
|
227
|
+
data: {
|
|
228
|
+
...(input.data || {}),
|
|
229
|
+
paypal: { ...existingPayPal, order_id: orderId, order },
|
|
230
|
+
},
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// Only a buyer-APPROVED order counts as authorized. CREATED/SAVED
|
|
236
|
+
// means the buyer never approved the payment — treating those as
|
|
237
|
+
// authorized would let a cart complete with no funds authorized at
|
|
238
|
+
// PayPal at all.
|
|
239
|
+
if (String(order?.status || "").toUpperCase() === "APPROVED") {
|
|
179
240
|
console.info("[PayPal] authorizePayment: order approved, marking authorized")
|
|
180
241
|
return {
|
|
181
242
|
status: "authorized",
|
|
@@ -192,133 +253,49 @@ class PayPalPaymentProvider extends PayPalProviderBase {
|
|
|
192
253
|
}
|
|
193
254
|
} catch (e: any) {
|
|
194
255
|
console.warn("[PayPal] authorizePayment: order lookup failed:", e?.message)
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
},
|
|
218
|
-
],
|
|
219
|
-
custom_id:
|
|
220
|
-
data.session_id || data.cart_id || data.payment_collection_id || undefined,
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
const ppResp = await paypalFetch(`${base}/v2/checkout/orders`, {
|
|
224
|
-
method: "POST",
|
|
225
|
-
headers: {
|
|
226
|
-
Authorization: `Bearer ${accessToken}`,
|
|
227
|
-
"Content-Type": "application/json",
|
|
228
|
-
"PayPal-Request-Id": requestId,
|
|
229
|
-
"PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
|
|
230
|
-
},
|
|
231
|
-
body: JSON.stringify(orderPayload),
|
|
232
|
-
})
|
|
233
|
-
|
|
234
|
-
const ppText = await ppResp.text()
|
|
235
|
-
debugId = ppResp.headers.get("paypal-debug-id")
|
|
236
|
-
if (!ppResp.ok) {
|
|
237
|
-
throw new Error(
|
|
238
|
-
`PayPal create order error (${ppResp.status}): ${ppText}${
|
|
239
|
-
debugId ? ` debug_id=${debugId}` : ""
|
|
240
|
-
}`
|
|
241
|
-
)
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
const order = JSON.parse(ppText) as Record<string, any>
|
|
245
|
-
const newOrderId = String(order.id || "")
|
|
246
|
-
|
|
247
|
-
if (!order || !newOrderId) {
|
|
248
|
-
throw new Error("Unable to resolve PayPal order details for authorization.")
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
const existingAuthorization =
|
|
252
|
-
order?.purchase_units?.[0]?.payments?.authorizations?.[0] || null
|
|
253
|
-
|
|
254
|
-
let authorization: any = null
|
|
255
|
-
if (existingAuthorization) {
|
|
256
|
-
authorization = order
|
|
257
|
-
} else {
|
|
258
|
-
const authorizeResp = await paypalFetch(
|
|
259
|
-
`${base}/v2/checkout/orders/${encodeURIComponent(newOrderId)}/authorize`,
|
|
260
|
-
{
|
|
261
|
-
method: "POST",
|
|
262
|
-
headers: {
|
|
263
|
-
Authorization: `Bearer ${accessToken}`,
|
|
264
|
-
"Content-Type": "application/json",
|
|
265
|
-
"PayPal-Request-Id": `${requestId}-auth`,
|
|
266
|
-
"PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
|
|
256
|
+
// Fall back to the session's own record when PayPal is unreachable so a
|
|
257
|
+
// transient lookup error doesn't fail a checkout that already has a
|
|
258
|
+
// real authorization/capture behind it. `captured_at` is only ever
|
|
259
|
+
// stamped after a COMPLETED gate; a bare capture_id (e.g. patched in by
|
|
260
|
+
// a webhook) or authorization id maps to "authorized" — the order is
|
|
261
|
+
// placed without claiming settled funds.
|
|
262
|
+
if ((data as any).captured_at) {
|
|
263
|
+
return {
|
|
264
|
+
status: "captured",
|
|
265
|
+
data: { ...(input.data || {}), captured_at: (data as any).captured_at },
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
if (
|
|
269
|
+
existingPayPal.capture_id ||
|
|
270
|
+
existingPayPal.authorization_id ||
|
|
271
|
+
(data as any).authorized_at
|
|
272
|
+
) {
|
|
273
|
+
return {
|
|
274
|
+
status: "authorized",
|
|
275
|
+
data: {
|
|
276
|
+
...(input.data || {}),
|
|
277
|
+
authorized_at: (data as any).authorized_at || new Date().toISOString(),
|
|
267
278
|
},
|
|
268
279
|
}
|
|
269
|
-
)
|
|
270
|
-
|
|
271
|
-
const authorizeText = await authorizeResp.text()
|
|
272
|
-
const authorizeDebugId = authorizeResp.headers.get("paypal-debug-id")
|
|
273
|
-
if (!authorizeResp.ok) {
|
|
274
|
-
throw new Error(
|
|
275
|
-
`PayPal authorize order error (${authorizeResp.status}): ${authorizeText}${
|
|
276
|
-
authorizeDebugId ? ` debug_id=${authorizeDebugId}` : ""
|
|
277
|
-
}`
|
|
278
|
-
)
|
|
279
280
|
}
|
|
280
|
-
|
|
281
|
-
authorization = JSON.parse(authorizeText)
|
|
282
281
|
}
|
|
283
|
-
|
|
284
|
-
const authorizationId =
|
|
285
|
-
authorization?.purchase_units?.[0]?.payments?.authorizations?.[0]?.id ||
|
|
286
|
-
existingAuthorization?.id
|
|
287
|
-
|
|
288
|
-
await this.recordSuccess("authorize_success")
|
|
289
|
-
await this.recordPaymentEvent("authorize", {
|
|
290
|
-
order_id: newOrderId,
|
|
291
|
-
authorization_id: authorizationId,
|
|
292
|
-
amount,
|
|
293
|
-
currency_code: currencyCode,
|
|
294
|
-
request_id: requestId,
|
|
295
|
-
})
|
|
296
|
-
|
|
297
|
-
return {
|
|
298
|
-
status: "authorized",
|
|
299
|
-
data: {
|
|
300
|
-
...(input.data || {}),
|
|
301
|
-
paypal: {
|
|
302
|
-
...((input.data || {}).paypal as Record<string, unknown>),
|
|
303
|
-
order_id: newOrderId,
|
|
304
|
-
order: order || authorization,
|
|
305
|
-
authorization_id: authorizationId,
|
|
306
|
-
authorizations:
|
|
307
|
-
authorization?.purchase_units?.[0]?.payments?.authorizations || [],
|
|
308
|
-
},
|
|
309
|
-
authorized_at: new Date().toISOString(),
|
|
310
|
-
},
|
|
311
|
-
}
|
|
312
|
-
} catch (error: any) {
|
|
313
|
-
await this.recordFailure("authorize_failed", {
|
|
314
|
-
request_id: requestId,
|
|
315
|
-
cart_id: data.cart_id,
|
|
316
|
-
payment_collection_id: data.payment_collection_id,
|
|
317
|
-
debug_id: debugId,
|
|
318
|
-
message: error?.message,
|
|
319
|
-
})
|
|
320
|
-
throw error
|
|
321
282
|
}
|
|
283
|
+
|
|
284
|
+
// No usable PayPal order on the session: nothing can be authorized. The
|
|
285
|
+
// previous fallback created a brand-new PayPal order here and immediately
|
|
286
|
+
// called /v2/checkout/orders/{id}/authorize on it — but an order no buyer
|
|
287
|
+
// has approved can never be authorized (PayPal rejects it with
|
|
288
|
+
// ORDER_NOT_APPROVED), so that path only produced confusing 422s and
|
|
289
|
+
// orphaned PayPal orders. Fail with a clear, actionable error instead.
|
|
290
|
+
await this.recordFailure("authorize_failed", {
|
|
291
|
+
cart_id: data.cart_id,
|
|
292
|
+
payment_collection_id: data.payment_collection_id,
|
|
293
|
+
message: "no approved PayPal order on session",
|
|
294
|
+
})
|
|
295
|
+
throw new MedusaError(
|
|
296
|
+
MedusaError.Types.NOT_ALLOWED,
|
|
297
|
+
"No approved PayPal payment was found for this session. The buyer must approve the payment with PayPal before the cart can be completed."
|
|
298
|
+
)
|
|
322
299
|
}
|
|
323
300
|
|
|
324
301
|
async retrievePayment(input: RetrievePaymentInput): Promise<RetrievePaymentOutput> {
|
|
@@ -411,7 +388,11 @@ class PayPalPaymentProvider extends PayPalProviderBase {
|
|
|
411
388
|
}
|
|
412
389
|
}
|
|
413
390
|
|
|
414
|
-
const { amount, currencyCode } = await this.normalizePaymentData(input)
|
|
391
|
+
const { amount: sessionAmount, currencyCode } = await this.normalizePaymentData(input)
|
|
392
|
+
// The requested (possibly partial) capture amount lives on the Medusa
|
|
393
|
+
// capture row, not in the provider input — resolve it so partial captures
|
|
394
|
+
// don't charge the full session total.
|
|
395
|
+
const amount = await this.resolveRequestedCaptureAmount(input, sessionAmount)
|
|
415
396
|
// Include the amount in the idempotency suffix: PayPal deduplicates by
|
|
416
397
|
// PayPal-Request-Id, so two sequential partial captures of the same order
|
|
417
398
|
// that share an upstream idempotency_key would otherwise collide and the
|
|
@@ -511,7 +511,10 @@ class PayPalModuleService extends MedusaService({
|
|
|
511
511
|
// result to the opener, and closes the popup. We pin the environment in the
|
|
512
512
|
// URL so the bridge saves credentials under the correct env even though
|
|
513
513
|
// PayPal's redirect carries no auth/session.
|
|
514
|
-
|
|
514
|
+
// Use the /hooks namespace: Medusa's publishable-key middleware rejects
|
|
515
|
+
// unauthenticated top-level navigations to /store/* routes, so the popup
|
|
516
|
+
// would land on a NOT_ALLOWED error page instead of the bridge.
|
|
517
|
+
const return_url = `${String(onboarding.backend_url || "").replace(/\/$/, "")}/hooks/paypal/onboard-return?env=${env}`
|
|
515
518
|
const partner_merchant_id = await this.getPartnerMerchantId(env)
|
|
516
519
|
|
|
517
520
|
const email = (input?.email || "").trim()
|
|
@@ -949,6 +952,17 @@ class PayPalModuleService extends MedusaService({
|
|
|
949
952
|
if (!base) {
|
|
950
953
|
throw new Error("PayPal backend URL is not configured.")
|
|
951
954
|
}
|
|
955
|
+
// The /hooks namespace has no publishable-key guard. PayPal cannot send
|
|
956
|
+
// Medusa's x-publishable-api-key header, so a webhook registered at the
|
|
957
|
+
// old /store/paypal/webhook path is rejected before the handler runs.
|
|
958
|
+
return `${base}/hooks/paypal/webhook`
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
/** Legacy webhook path (blocked by Medusa's store publishable-key guard). */
|
|
962
|
+
private async resolveLegacyWebhookUrl() {
|
|
963
|
+
const { onboarding } = await this.ensureSettingsDefaults()
|
|
964
|
+
const base = String(onboarding.backend_url || "").replace(/\/$/, "")
|
|
965
|
+
if (!base) return ""
|
|
952
966
|
return `${base}/store/paypal/webhook`
|
|
953
967
|
}
|
|
954
968
|
|
|
@@ -961,12 +975,82 @@ class PayPalModuleService extends MedusaService({
|
|
|
961
975
|
}
|
|
962
976
|
}
|
|
963
977
|
|
|
978
|
+
// Only probe PayPal for a stale legacy webhook URL once per process per
|
|
979
|
+
// environment — this runs on admin status reads and must stay cheap.
|
|
980
|
+
private webhookUrlMigrationChecked: Record<string, boolean> = {}
|
|
981
|
+
private webhookHealScheduled: Record<string, boolean> = {}
|
|
982
|
+
|
|
983
|
+
private async migrateLegacyWebhookUrl(env: string, webhookId: string) {
|
|
984
|
+
if (this.webhookUrlMigrationChecked[env]) return
|
|
985
|
+
this.webhookUrlMigrationChecked[env] = true
|
|
986
|
+
|
|
987
|
+
const newUrl = await this.resolveWebhookUrl().catch(() => "")
|
|
988
|
+
const legacyUrl = await this.resolveLegacyWebhookUrl()
|
|
989
|
+
if (!newUrl || !legacyUrl || this.isLocalWebhookUrl(newUrl)) return
|
|
990
|
+
|
|
991
|
+
const accessToken = await this.getAppAccessToken()
|
|
992
|
+
const baseUrl =
|
|
993
|
+
env === "live" ? "https://api-m.paypal.com" : "https://api-m.sandbox.paypal.com"
|
|
994
|
+
|
|
995
|
+
const getResp = await paypalFetch(
|
|
996
|
+
`${baseUrl}/v1/notifications/webhooks/${encodeURIComponent(webhookId)}`,
|
|
997
|
+
{
|
|
998
|
+
headers: {
|
|
999
|
+
Authorization: `Bearer ${accessToken}`,
|
|
1000
|
+
"Content-Type": "application/json",
|
|
1001
|
+
"PayPal-Partner-Attribution-Id": this.bnCode,
|
|
1002
|
+
},
|
|
1003
|
+
}
|
|
1004
|
+
)
|
|
1005
|
+
const getJson = await getResp.json().catch(() => ({}))
|
|
1006
|
+
if (!getResp.ok) return
|
|
1007
|
+
|
|
1008
|
+
const currentUrl = String(getJson?.url || "")
|
|
1009
|
+
if (currentUrl !== legacyUrl) return
|
|
1010
|
+
|
|
1011
|
+
const patchResp = await paypalFetch(
|
|
1012
|
+
`${baseUrl}/v1/notifications/webhooks/${encodeURIComponent(webhookId)}`,
|
|
1013
|
+
{
|
|
1014
|
+
method: "PATCH",
|
|
1015
|
+
headers: {
|
|
1016
|
+
Authorization: `Bearer ${accessToken}`,
|
|
1017
|
+
"Content-Type": "application/json",
|
|
1018
|
+
"PayPal-Partner-Attribution-Id": this.bnCode,
|
|
1019
|
+
},
|
|
1020
|
+
body: JSON.stringify([
|
|
1021
|
+
{ op: "replace", path: "/url", value: newUrl },
|
|
1022
|
+
]),
|
|
1023
|
+
}
|
|
1024
|
+
)
|
|
1025
|
+
if (patchResp.ok) {
|
|
1026
|
+
await this.recordAuditEvent("webhook_url_migrated", {
|
|
1027
|
+
environment: env,
|
|
1028
|
+
webhook_id: webhookId,
|
|
1029
|
+
from: legacyUrl,
|
|
1030
|
+
to: newUrl,
|
|
1031
|
+
})
|
|
1032
|
+
console.info(
|
|
1033
|
+
`[PayPal] migrated webhook ${webhookId} URL from ${legacyUrl} to ${newUrl}`
|
|
1034
|
+
)
|
|
1035
|
+
}
|
|
1036
|
+
}
|
|
1037
|
+
|
|
964
1038
|
private async ensureWebhookRegistration() {
|
|
965
1039
|
const env = await this.getCurrentEnvironment()
|
|
966
1040
|
const { apiDetails } = await this.ensureSettingsDefaults()
|
|
967
1041
|
const webhookIds = { ...(apiDetails.webhook_ids || {}) } as Record<string, string>
|
|
968
1042
|
|
|
969
1043
|
if (webhookIds[env]) {
|
|
1044
|
+
// Existing installs registered the webhook at /store/paypal/webhook,
|
|
1045
|
+
// which Medusa's publishable-key middleware blocks for external callers.
|
|
1046
|
+
// Migrate the registered URL to /hooks/paypal/webhook in place
|
|
1047
|
+
// (best-effort — a failure keeps the stored id and current behavior).
|
|
1048
|
+
await this.migrateLegacyWebhookUrl(env, webhookIds[env]).catch((e: any) => {
|
|
1049
|
+
console.warn(
|
|
1050
|
+
"[PayPal] webhook URL migration check failed:",
|
|
1051
|
+
e?.message || e
|
|
1052
|
+
)
|
|
1053
|
+
})
|
|
970
1054
|
return webhookIds[env]
|
|
971
1055
|
}
|
|
972
1056
|
|
|
@@ -1094,6 +1178,19 @@ class PayPalModuleService extends MedusaService({
|
|
|
1094
1178
|
let sellerEmail: string | null = c.sellerEmail || row.seller_email || null
|
|
1095
1179
|
let sellerMerchantId: string | null = c.sellerMerchantId || row.seller_merchant_id || null
|
|
1096
1180
|
|
|
1181
|
+
// Self-heal the webhook registration for already-connected merchants:
|
|
1182
|
+
// installs that registered the webhook at the old (blocked)
|
|
1183
|
+
// /store/paypal/webhook path get migrated to /hooks/paypal/webhook the
|
|
1184
|
+
// first time an admin views the status page after upgrading. Fire and
|
|
1185
|
+
// forget — status reads must never block on PayPal, and the migration is
|
|
1186
|
+
// throttled to once per process per environment internally.
|
|
1187
|
+
if (hasCreds && !this.webhookHealScheduled[env]) {
|
|
1188
|
+
this.webhookHealScheduled[env] = true
|
|
1189
|
+
void this.ensureWebhookRegistration().catch((e: any) => {
|
|
1190
|
+
console.warn("[PayPal] webhook self-heal failed:", e?.message || e)
|
|
1191
|
+
})
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1097
1194
|
if (!sellerEmail && hasCreds && opts.hydrateMissingProfile) {
|
|
1098
1195
|
try {
|
|
1099
1196
|
const hydrated = await this.fetchSellerProfileFromDirectCredentials(env)
|
|
@@ -44,14 +44,49 @@ export class PayPalCredentialResolver {
|
|
|
44
44
|
}
|
|
45
45
|
|
|
46
46
|
private async getConnectionRow(): Promise<any | null> {
|
|
47
|
+
// Match the module service's soft-delete semantics: this raw knex read
|
|
48
|
+
// bypasses MikroORM's automatic deleted_at filter, so apply it explicitly
|
|
49
|
+
// or a soft-deleted connection's credentials would keep being used.
|
|
47
50
|
const rows = await this.db("paypal_connection")
|
|
48
51
|
.select("*")
|
|
52
|
+
.whereNull("deleted_at")
|
|
49
53
|
.orderBy("created_at", "desc")
|
|
50
54
|
.limit(1)
|
|
51
55
|
|
|
52
56
|
return rows?.[0] ?? null
|
|
53
57
|
}
|
|
54
58
|
|
|
59
|
+
/**
|
|
60
|
+
* Resolve the amount an admin actually requested for a capture.
|
|
61
|
+
*
|
|
62
|
+
* Medusa does NOT pass the requested capture amount to the provider — only
|
|
63
|
+
* `context.idempotency_key`, which is the Medusa `capture` row id. Without
|
|
64
|
+
* this lookup the provider can only capture the full session amount, which
|
|
65
|
+
* over-charges the buyer on partial captures. Returns null when the id
|
|
66
|
+
* doesn't resolve (caller falls back to the session amount).
|
|
67
|
+
*/
|
|
68
|
+
async getRequestedCaptureAmount(captureRowId: string): Promise<number | null> {
|
|
69
|
+
try {
|
|
70
|
+
if (!captureRowId || typeof captureRowId !== "string") return null
|
|
71
|
+
const rows = await this.db("capture")
|
|
72
|
+
.select("amount", "raw_amount")
|
|
73
|
+
.where("id", captureRowId)
|
|
74
|
+
.whereNull("deleted_at")
|
|
75
|
+
.limit(1)
|
|
76
|
+
const row = rows?.[0]
|
|
77
|
+
if (!row) return null
|
|
78
|
+
const raw = row.raw_amount
|
|
79
|
+
if (raw && typeof raw === "object" && raw.value !== undefined) {
|
|
80
|
+
const v = Number(raw.value)
|
|
81
|
+
if (Number.isFinite(v) && v > 0) return v
|
|
82
|
+
}
|
|
83
|
+
const v = Number(row.amount)
|
|
84
|
+
return Number.isFinite(v) && v > 0 ? v : null
|
|
85
|
+
} catch {
|
|
86
|
+
return null
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
55
90
|
private getEnvCreds(
|
|
56
91
|
row: any,
|
|
57
92
|
env: Environment
|
|
@@ -181,6 +216,7 @@ export class PayPalCredentialResolver {
|
|
|
181
216
|
try {
|
|
182
217
|
const rows = await this.db("paypal_settings")
|
|
183
218
|
.select("data")
|
|
219
|
+
.whereNull("deleted_at")
|
|
184
220
|
.limit(1)
|
|
185
221
|
|
|
186
222
|
const data = (rows?.[0]?.data || {}) as Record<string, any>
|
|
@@ -18,44 +18,72 @@ const CB_HALF_OPEN_MS = 60_000
|
|
|
18
18
|
|
|
19
19
|
type CBState = "closed" | "open" | "half-open"
|
|
20
20
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
21
|
+
// One breaker per target host: `paypalFetch` is also used for non-PayPal hosts
|
|
22
|
+
// (onboarding service, alert webhooks). A shared breaker would let five
|
|
23
|
+
// failures of a side-channel host block live captures/refunds against a
|
|
24
|
+
// perfectly healthy PayPal API.
|
|
25
|
+
type Breaker = {
|
|
26
|
+
state: CBState
|
|
27
|
+
failures: number[]
|
|
28
|
+
openedAt: number
|
|
29
|
+
halfOpenProbeInFlight: boolean
|
|
30
30
|
}
|
|
31
31
|
|
|
32
|
-
|
|
33
|
-
|
|
32
|
+
const breakers = new Map<string, Breaker>()
|
|
33
|
+
|
|
34
|
+
function cbHostKey(input: string | URL): string {
|
|
35
|
+
try {
|
|
36
|
+
return new URL(String(input)).host || "default"
|
|
37
|
+
} catch {
|
|
38
|
+
return "default"
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function getBreaker(host: string): Breaker {
|
|
43
|
+
let b = breakers.get(host)
|
|
44
|
+
if (!b) {
|
|
45
|
+
b = { state: "closed", failures: [], openedAt: 0, halfOpenProbeInFlight: false }
|
|
46
|
+
breakers.set(host, b)
|
|
47
|
+
}
|
|
48
|
+
return b
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function cbRecordSuccess(host: string) {
|
|
52
|
+
const b = getBreaker(host)
|
|
53
|
+
b.state = "closed"
|
|
54
|
+
b.failures = []
|
|
55
|
+
b.halfOpenProbeInFlight = false
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function cbRecordFailure(host: string) {
|
|
59
|
+
const b = getBreaker(host)
|
|
60
|
+
b.halfOpenProbeInFlight = false
|
|
34
61
|
const now = Date.now()
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
if (
|
|
38
|
-
|
|
39
|
-
|
|
62
|
+
b.failures = b.failures.filter((t) => now - t < CB_WINDOW_MS)
|
|
63
|
+
b.failures.push(now)
|
|
64
|
+
if (b.failures.length >= CB_FAILURE_THRESHOLD) {
|
|
65
|
+
b.state = "open"
|
|
66
|
+
b.openedAt = now
|
|
40
67
|
console.warn(
|
|
41
|
-
`[PayPal] circuit breaker OPEN after ${CB_FAILURE_THRESHOLD} failures in ${CB_WINDOW_MS / 1000}s`
|
|
68
|
+
`[PayPal] circuit breaker OPEN for ${host} after ${CB_FAILURE_THRESHOLD} failures in ${CB_WINDOW_MS / 1000}s`
|
|
42
69
|
)
|
|
43
70
|
}
|
|
44
71
|
}
|
|
45
72
|
|
|
46
|
-
function cbAllowRequest(): boolean {
|
|
47
|
-
|
|
48
|
-
if (
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
73
|
+
function cbAllowRequest(host: string): boolean {
|
|
74
|
+
const b = getBreaker(host)
|
|
75
|
+
if (b.state === "closed") return true
|
|
76
|
+
if (b.state === "open") {
|
|
77
|
+
if (Date.now() - b.openedAt >= CB_HALF_OPEN_MS) {
|
|
78
|
+
b.state = "half-open"
|
|
79
|
+
b.halfOpenProbeInFlight = true
|
|
52
80
|
return true
|
|
53
81
|
}
|
|
54
82
|
return false
|
|
55
83
|
}
|
|
56
84
|
// half-open: allow only one probe at a time
|
|
57
|
-
if (
|
|
58
|
-
|
|
85
|
+
if (b.halfOpenProbeInFlight) return false
|
|
86
|
+
b.halfOpenProbeInFlight = true
|
|
59
87
|
return true
|
|
60
88
|
}
|
|
61
89
|
|
|
@@ -76,7 +104,8 @@ export function paypalFetch(
|
|
|
76
104
|
input: string | URL,
|
|
77
105
|
init: RequestInit = {}
|
|
78
106
|
): Promise<Response> {
|
|
79
|
-
|
|
107
|
+
const host = cbHostKey(input)
|
|
108
|
+
if (!cbAllowRequest(host)) {
|
|
80
109
|
return Promise.reject(new CircuitOpenError())
|
|
81
110
|
}
|
|
82
111
|
|
|
@@ -90,14 +119,14 @@ export function paypalFetch(
|
|
|
90
119
|
return fetchPromise.then(
|
|
91
120
|
(res) => {
|
|
92
121
|
if (res.status >= 500) {
|
|
93
|
-
cbRecordFailure()
|
|
122
|
+
cbRecordFailure(host)
|
|
94
123
|
} else {
|
|
95
|
-
cbRecordSuccess()
|
|
124
|
+
cbRecordSuccess(host)
|
|
96
125
|
}
|
|
97
126
|
return res
|
|
98
127
|
},
|
|
99
128
|
(err) => {
|
|
100
|
-
cbRecordFailure()
|
|
129
|
+
cbRecordFailure(host)
|
|
101
130
|
throw err
|
|
102
131
|
}
|
|
103
132
|
)
|