@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.
Files changed (65) hide show
  1. package/.medusa/server/src/admin/index.js +73 -73
  2. package/.medusa/server/src/admin/index.mjs +73 -73
  3. package/.medusa/server/src/api/hooks/paypal/onboard-return/route.d.ts +16 -0
  4. package/.medusa/server/src/api/hooks/paypal/onboard-return/route.d.ts.map +1 -0
  5. package/.medusa/server/src/api/hooks/paypal/onboard-return/route.js +20 -0
  6. package/.medusa/server/src/api/hooks/paypal/onboard-return/route.js.map +1 -0
  7. package/.medusa/server/src/api/hooks/paypal/webhook/route.d.ts +18 -0
  8. package/.medusa/server/src/api/hooks/paypal/webhook/route.d.ts.map +1 -0
  9. package/.medusa/server/src/api/hooks/paypal/webhook/route.js +22 -0
  10. package/.medusa/server/src/api/hooks/paypal/webhook/route.js.map +1 -0
  11. package/.medusa/server/src/api/middlewares.d.ts.map +1 -1
  12. package/.medusa/server/src/api/middlewares.js +9 -0
  13. package/.medusa/server/src/api/middlewares.js.map +1 -1
  14. package/.medusa/server/src/api/store/paypal/config/route.d.ts.map +1 -1
  15. package/.medusa/server/src/api/store/paypal/config/route.js +8 -0
  16. package/.medusa/server/src/api/store/paypal/config/route.js.map +1 -1
  17. package/.medusa/server/src/api/store/paypal/create-order/route.d.ts.map +1 -1
  18. package/.medusa/server/src/api/store/paypal/create-order/route.js +53 -4
  19. package/.medusa/server/src/api/store/paypal/create-order/route.js.map +1 -1
  20. package/.medusa/server/src/api/store/paypal-complete/route.js +1 -1
  21. package/.medusa/server/src/api/store/paypal-complete/route.js.map +1 -1
  22. package/.medusa/server/src/api/utils/rate-limit.d.ts.map +1 -1
  23. package/.medusa/server/src/api/utils/rate-limit.js +11 -2
  24. package/.medusa/server/src/api/utils/rate-limit.js.map +1 -1
  25. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.d.ts +32 -3
  26. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.d.ts.map +1 -1
  27. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.js +47 -0
  28. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.js.map +1 -1
  29. package/.medusa/server/src/modules/paypal/payment-provider/card-service.d.ts.map +1 -1
  30. package/.medusa/server/src/modules/paypal/payment-provider/card-service.js +172 -117
  31. package/.medusa/server/src/modules/paypal/payment-provider/card-service.js.map +1 -1
  32. package/.medusa/server/src/modules/paypal/payment-provider/service.d.ts.map +1 -1
  33. package/.medusa/server/src/modules/paypal/payment-provider/service.js +132 -126
  34. package/.medusa/server/src/modules/paypal/payment-provider/service.js.map +1 -1
  35. package/.medusa/server/src/modules/paypal/service.d.ts +5 -0
  36. package/.medusa/server/src/modules/paypal/service.d.ts.map +1 -1
  37. package/.medusa/server/src/modules/paypal/service.js +82 -1
  38. package/.medusa/server/src/modules/paypal/service.js.map +1 -1
  39. package/.medusa/server/src/modules/paypal/utils/credential-resolver.d.ts +10 -0
  40. package/.medusa/server/src/modules/paypal/utils/credential-resolver.d.ts.map +1 -1
  41. package/.medusa/server/src/modules/paypal/utils/credential-resolver.js +39 -0
  42. package/.medusa/server/src/modules/paypal/utils/credential-resolver.js.map +1 -1
  43. package/.medusa/server/src/modules/paypal/utils/paypal-fetch.d.ts.map +1 -1
  44. package/.medusa/server/src/modules/paypal/utils/paypal-fetch.js +45 -28
  45. package/.medusa/server/src/modules/paypal/utils/paypal-fetch.js.map +1 -1
  46. package/.medusa/server/src/modules/paypal/webhook-processor.d.ts +11 -0
  47. package/.medusa/server/src/modules/paypal/webhook-processor.d.ts.map +1 -1
  48. package/.medusa/server/src/modules/paypal/webhook-processor.js +85 -7
  49. package/.medusa/server/src/modules/paypal/webhook-processor.js.map +1 -1
  50. package/CHANGELOG.md +73 -0
  51. package/package.json +4 -5
  52. package/src/api/hooks/paypal/onboard-return/route.ts +15 -0
  53. package/src/api/hooks/paypal/webhook/route.ts +17 -0
  54. package/src/api/middlewares.ts +9 -0
  55. package/src/api/store/paypal/config/route.ts +8 -0
  56. package/src/api/store/paypal/create-order/route.ts +64 -4
  57. package/src/api/store/paypal-complete/route.ts +1 -1
  58. package/src/api/utils/rate-limit.ts +11 -2
  59. package/src/modules/paypal/payment-provider/base-provider.ts +52 -0
  60. package/src/modules/paypal/payment-provider/card-service.ts +193 -136
  61. package/src/modules/paypal/payment-provider/service.ts +137 -156
  62. package/src/modules/paypal/service.ts +98 -1
  63. package/src/modules/paypal/utils/credential-resolver.ts +36 -0
  64. package/src/modules/paypal/utils/paypal-fetch.ts +58 -29
  65. 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, amount, currencyCode } = await this.normalizePaymentData(input)
126
+ const { data } = await this.normalizePaymentData(input)
126
127
  const existingPayPal = (data.paypal || {}) as Record<string, any>
127
128
 
128
- const { additionalSettings } = await this.resolveSettings()
129
- const paymentActionRaw =
130
- typeof additionalSettings.paymentAction === "string"
131
- ? additionalSettings.paymentAction
132
- : "capture"
133
- const returnStatus = paymentActionRaw === "authorize" ? "authorized" : "captured"
134
- const timestampKey = paymentActionRaw === "authorize" ? "authorized_at" : "captured_at"
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: returnStatus,
138
+ status: "captured",
145
139
  data: {
146
140
  ...(input.data || {}),
147
- [timestampKey]: (data as any)[timestampKey] || new Date().toISOString(),
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
- if (capture?.id || authorization?.id) {
161
- console.info("[PayPal] authorizePayment: order already processed by PayPal, returning", returnStatus)
162
- return {
163
- status: returnStatus,
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 || existingPayPal.capture_id,
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
- [timestampKey]: new Date().toISOString(),
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 (["APPROVED", "CREATED", "SAVED"].includes(String(order?.status || "").toUpperCase())) {
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
- const requestId = this.getIdempotencyKey(input, "authorize")
199
- let debugId: string | null = null
200
- const orderIntent = paymentActionRaw === "authorize" ? "AUTHORIZE" : "CAPTURE"
201
-
202
- try {
203
- const { accessToken, base } = await this.getPayPalAccessToken()
204
- const value = formatAmountForPayPal(amount, currencyCode || "EUR")
205
-
206
- const orderPayload = {
207
- intent: orderIntent,
208
- purchase_units: [
209
- {
210
- reference_id: data.cart_id || data.payment_collection_id || undefined,
211
- custom_id:
212
- data.session_id || data.cart_id || data.payment_collection_id || undefined,
213
- amount: {
214
- currency_code: currencyCode || "EUR",
215
- value,
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
- const return_url = `${String(onboarding.backend_url || "").replace(/\/$/, "")}/store/paypal/onboard-return?env=${env}`
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
- let cbState: CBState = "closed"
22
- let cbFailures: number[] = []
23
- let cbOpenedAt = 0
24
- let cbHalfOpenProbeInFlight = false
25
-
26
- function cbRecordSuccess() {
27
- cbState = "closed"
28
- cbFailures = []
29
- cbHalfOpenProbeInFlight = false
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
- function cbRecordFailure() {
33
- cbHalfOpenProbeInFlight = false
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
- cbFailures = cbFailures.filter((t) => now - t < CB_WINDOW_MS)
36
- cbFailures.push(now)
37
- if (cbFailures.length >= CB_FAILURE_THRESHOLD) {
38
- cbState = "open"
39
- cbOpenedAt = now
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
- if (cbState === "closed") return true
48
- if (cbState === "open") {
49
- if (Date.now() - cbOpenedAt >= CB_HALF_OPEN_MS) {
50
- cbState = "half-open"
51
- cbHalfOpenProbeInFlight = true
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 (cbHalfOpenProbeInFlight) return false
58
- cbHalfOpenProbeInFlight = true
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
- if (!cbAllowRequest()) {
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
  )