@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.
Files changed (90) hide show
  1. package/.medusa/server/src/admin/index.js +7 -7
  2. package/.medusa/server/src/admin/index.mjs +7 -7
  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 +24 -1
  13. package/.medusa/server/src/api/middlewares.js.map +1 -1
  14. package/.medusa/server/src/api/store/paypal/capture-order/route.d.ts.map +1 -1
  15. package/.medusa/server/src/api/store/paypal/capture-order/route.js +66 -13
  16. package/.medusa/server/src/api/store/paypal/capture-order/route.js.map +1 -1
  17. package/.medusa/server/src/api/store/paypal/config/route.d.ts.map +1 -1
  18. package/.medusa/server/src/api/store/paypal/config/route.js +8 -0
  19. package/.medusa/server/src/api/store/paypal/config/route.js.map +1 -1
  20. package/.medusa/server/src/api/store/paypal/create-order/route.d.ts.map +1 -1
  21. package/.medusa/server/src/api/store/paypal/create-order/route.js +63 -9
  22. package/.medusa/server/src/api/store/paypal/create-order/route.js.map +1 -1
  23. package/.medusa/server/src/api/store/paypal-complete/route.js +1 -1
  24. package/.medusa/server/src/api/store/paypal-complete/route.js.map +1 -1
  25. package/.medusa/server/src/api/utils/rate-limit.d.ts +13 -1
  26. package/.medusa/server/src/api/utils/rate-limit.d.ts.map +1 -1
  27. package/.medusa/server/src/api/utils/rate-limit.js +18 -7
  28. package/.medusa/server/src/api/utils/rate-limit.js.map +1 -1
  29. package/.medusa/server/src/jobs/paypal-webhook-retry.d.ts.map +1 -1
  30. package/.medusa/server/src/jobs/paypal-webhook-retry.js +4 -0
  31. package/.medusa/server/src/jobs/paypal-webhook-retry.js.map +1 -1
  32. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.d.ts +47 -3
  33. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.d.ts.map +1 -1
  34. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.js +73 -0
  35. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.js.map +1 -1
  36. package/.medusa/server/src/modules/paypal/payment-provider/card-service.d.ts.map +1 -1
  37. package/.medusa/server/src/modules/paypal/payment-provider/card-service.js +415 -285
  38. package/.medusa/server/src/modules/paypal/payment-provider/card-service.js.map +1 -1
  39. package/.medusa/server/src/modules/paypal/payment-provider/service.d.ts +0 -4
  40. package/.medusa/server/src/modules/paypal/payment-provider/service.d.ts.map +1 -1
  41. package/.medusa/server/src/modules/paypal/payment-provider/service.js +140 -151
  42. package/.medusa/server/src/modules/paypal/payment-provider/service.js.map +1 -1
  43. package/.medusa/server/src/modules/paypal/service.d.ts +7 -0
  44. package/.medusa/server/src/modules/paypal/service.d.ts.map +1 -1
  45. package/.medusa/server/src/modules/paypal/service.js +135 -13
  46. package/.medusa/server/src/modules/paypal/service.js.map +1 -1
  47. package/.medusa/server/src/modules/paypal/types/config.d.ts.map +1 -1
  48. package/.medusa/server/src/modules/paypal/types/config.js +13 -0
  49. package/.medusa/server/src/modules/paypal/types/config.js.map +1 -1
  50. package/.medusa/server/src/modules/paypal/utils/amounts.d.ts +1 -1
  51. package/.medusa/server/src/modules/paypal/utils/credential-resolver.d.ts +10 -0
  52. package/.medusa/server/src/modules/paypal/utils/credential-resolver.d.ts.map +1 -1
  53. package/.medusa/server/src/modules/paypal/utils/credential-resolver.js +49 -34
  54. package/.medusa/server/src/modules/paypal/utils/credential-resolver.js.map +1 -1
  55. package/.medusa/server/src/modules/paypal/utils/metrics.d.ts +18 -0
  56. package/.medusa/server/src/modules/paypal/utils/metrics.d.ts.map +1 -0
  57. package/.medusa/server/src/modules/paypal/utils/metrics.js +45 -0
  58. package/.medusa/server/src/modules/paypal/utils/metrics.js.map +1 -0
  59. package/.medusa/server/src/modules/paypal/utils/paypal-fetch.d.ts.map +1 -1
  60. package/.medusa/server/src/modules/paypal/utils/paypal-fetch.js +45 -28
  61. package/.medusa/server/src/modules/paypal/utils/paypal-fetch.js.map +1 -1
  62. package/.medusa/server/src/modules/paypal/webhook-processor.d.ts +27 -0
  63. package/.medusa/server/src/modules/paypal/webhook-processor.d.ts.map +1 -1
  64. package/.medusa/server/src/modules/paypal/webhook-processor.js +170 -9
  65. package/.medusa/server/src/modules/paypal/webhook-processor.js.map +1 -1
  66. package/.medusa/server/src/subscribers/paypal-webhook-process.d.ts.map +1 -1
  67. package/.medusa/server/src/subscribers/paypal-webhook-process.js +4 -0
  68. package/.medusa/server/src/subscribers/paypal-webhook-process.js.map +1 -1
  69. package/CHANGELOG.md +208 -73
  70. package/README.md +175 -184
  71. package/package.json +91 -90
  72. package/src/api/hooks/paypal/onboard-return/route.ts +15 -0
  73. package/src/api/hooks/paypal/webhook/route.ts +17 -0
  74. package/src/api/middlewares.ts +24 -1
  75. package/src/api/store/paypal/capture-order/route.ts +83 -12
  76. package/src/api/store/paypal/config/route.ts +8 -0
  77. package/src/api/store/paypal/create-order/route.ts +73 -9
  78. package/src/api/store/paypal-complete/route.ts +1 -1
  79. package/src/api/utils/rate-limit.ts +31 -7
  80. package/src/jobs/paypal-webhook-retry.ts +4 -0
  81. package/src/modules/paypal/payment-provider/base-provider.ts +83 -0
  82. package/src/modules/paypal/payment-provider/card-service.ts +277 -136
  83. package/src/modules/paypal/payment-provider/service.ts +149 -186
  84. package/src/modules/paypal/service.ts +1703 -1554
  85. package/src/modules/paypal/types/config.ts +16 -0
  86. package/src/modules/paypal/utils/credential-resolver.ts +45 -36
  87. package/src/modules/paypal/utils/metrics.ts +48 -0
  88. package/src/modules/paypal/utils/paypal-fetch.ts +58 -29
  89. package/src/modules/paypal/webhook-processor.ts +195 -10
  90. package/src/subscribers/paypal-webhook-process.ts +4 -0
@@ -66,10 +66,15 @@ class PayPalAdvancedCardProvider extends PayPalProviderBase {
66
66
  currencyCode,
67
67
  paypalCurrencyOverride: currencyOverride,
68
68
  })
69
+ // Preserve the provider_id passthrough exactly like the wallet provider —
70
+ // dropping it here would make the two providers' session data diverge.
71
+ const providerId = (input.data as Record<string, any> | undefined)?.provider_id
69
72
 
70
73
  return {
71
74
  data: {
72
75
  ...(input.data || {}),
76
+ ...this.invalidateStaleOrder(input, currencyCode),
77
+ ...(providerId ? { provider_id: providerId } : {}),
73
78
  amount: input.amount,
74
79
  currency_code: currencyCode,
75
80
  },
@@ -77,27 +82,9 @@ class PayPalAdvancedCardProvider extends PayPalProviderBase {
77
82
  }
78
83
 
79
84
  async authorizePayment(_input: AuthorizePaymentInput): Promise<AuthorizePaymentOutput> {
80
- const { data, amount, currencyCode } = await this.normalizePaymentData(_input)
85
+ const { data } = await this.normalizePaymentData(_input)
81
86
  const requestId = this.getIdempotencyKey(_input, "authorize")
82
- let debugId: string | null = null
83
- const { additionalSettings, advancedCardSettings } = await this.resolveSettings()
84
- const paymentActionRaw =
85
- typeof additionalSettings.paymentAction === "string"
86
- ? additionalSettings.paymentAction
87
- : "capture"
88
- const orderIntent = paymentActionRaw === "authorize" ? "AUTHORIZE" : "CAPTURE"
89
- const returnStatus = paymentActionRaw === "authorize" ? "authorized" : "captured"
90
- const timestampKey = paymentActionRaw === "authorize" ? "authorized_at" : "captured_at"
91
- const threeDsRaw =
92
- typeof advancedCardSettings.threeDS === "string"
93
- ? advancedCardSettings.threeDS
94
- : "when_required"
95
- const threeDsMethod =
96
- threeDsRaw === "always"
97
- ? "SCA_ALWAYS"
98
- : threeDsRaw === "when_required" || threeDsRaw === "sli"
99
- ? "SCA_WHEN_REQUIRED"
100
- : null
87
+ const { advancedCardSettings } = await this.resolveSettings()
101
88
  const disabledCards = Array.isArray(advancedCardSettings.disabledCards)
102
89
  ? advancedCardSettings.disabledCards.map((card: string) => String(card).toLowerCase())
103
90
  : []
@@ -110,151 +97,231 @@ class PayPalAdvancedCardProvider extends PayPalProviderBase {
110
97
 
111
98
  const existingPayPal = (data.paypal || {}) as Record<string, any>
112
99
 
113
- if (
114
- existingPayPal.capture_id ||
115
- existingPayPal.authorization_id ||
116
- (data as any).authorized_at ||
117
- (data as any).captured_at
118
- ) {
100
+ // Session already carries a settled capture: trust it without a network
101
+ // round-trip, but only when the stored capture is actually COMPLETED — a
102
+ // PENDING/DECLINED capture must never be booked as captured money.
103
+ const storedCaptureStatus = extractCaptureStatus(existingPayPal.capture)
104
+ if (storedCaptureStatus === "COMPLETED") {
119
105
  return {
120
- status: returnStatus,
106
+ status: "captured",
121
107
  data: {
122
108
  ...(_input.data || {}),
123
- [timestampKey]: (data as any)[timestampKey] || new Date().toISOString(),
109
+ captured_at: (data as any).captured_at || new Date().toISOString(),
124
110
  },
125
111
  }
126
112
  }
127
113
 
128
- const { accessToken, base } = await this.getPayPalAccessToken()
129
- let orderId = String(existingPayPal.order_id || data.order_id || "")
130
- let order: Record<string, any> | null = null
131
- let authorization: Record<string, any> | null = null
132
-
114
+ const orderId = String(existingPayPal.order_id || data.order_id || "")
133
115
  if (!orderId) {
134
- const value = formatAmountForPayPal(amount, currencyCode || "EUR")
135
- const orderPayload = {
136
- intent: orderIntent,
137
- purchase_units: [
138
- {
139
- reference_id: data.cart_id || data.payment_collection_id || undefined,
140
- custom_id: data.session_id || data.cart_id || data.payment_collection_id || undefined,
141
- amount: {
142
- currency_code: currencyCode || "EUR",
143
- value,
144
- },
116
+ // Nothing to authorize: a PayPal order only exists after the buyer
117
+ // submitted their card via the storefront (create-order + card fields).
118
+ // The previous fallback created a fresh order here and immediately
119
+ // called /authorize on it, which PayPal always rejects (no payment
120
+ // source, and 422 UNSUPPORTED_INTENT for CAPTURE-intent orders).
121
+ await this.recordFailure("authorize_failed", {
122
+ cart_id: data.cart_id,
123
+ payment_collection_id: data.payment_collection_id,
124
+ message: "no PayPal order on card session",
125
+ })
126
+ throw new MedusaError(
127
+ MedusaError.Types.NOT_ALLOWED,
128
+ "No PayPal order was found for this payment session. The buyer must submit and approve their card payment before the cart can be completed."
129
+ )
130
+ }
131
+
132
+ let order: Record<string, any> | null = null
133
+ try {
134
+ order = (await this.getOrderDetails(orderId)) as Record<string, any> | null
135
+ } catch (e: any) {
136
+ console.warn("[PayPal] card authorizePayment: order lookup failed:", e?.message)
137
+ // Fall back to the session's own record on a transient lookup failure so
138
+ // checkout isn't blocked when a real authorization/capture exists.
139
+ if ((data as any).captured_at) {
140
+ return {
141
+ status: "captured",
142
+ data: { ...(_input.data || {}), captured_at: (data as any).captured_at },
143
+ }
144
+ }
145
+ if (
146
+ existingPayPal.capture_id ||
147
+ existingPayPal.authorization_id ||
148
+ (data as any).authorized_at
149
+ ) {
150
+ return {
151
+ status: "authorized",
152
+ data: {
153
+ ...(_input.data || {}),
154
+ authorized_at: (data as any).authorized_at || new Date().toISOString(),
145
155
  },
146
- ],
147
- custom_id: data.session_id || data.cart_id || data.payment_collection_id || undefined,
148
- ...(threeDsMethod
149
- ? {
150
- payment_source: {
151
- card: {
152
- attributes: {
153
- verification: {
154
- method: threeDsMethod,
155
- },
156
- },
157
- },
158
- },
159
- }
160
- : {}),
156
+ }
161
157
  }
158
+ throw e
159
+ }
162
160
 
163
- const ppResp = await paypalFetch(`${base}/v2/checkout/orders`, {
164
- method: "POST",
165
- headers: {
166
- Authorization: `Bearer ${accessToken}`,
167
- "Content-Type": "application/json",
168
- "PayPal-Request-Id": requestId,
169
- "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
170
- },
171
- body: JSON.stringify(orderPayload),
172
- })
161
+ if (!order) {
162
+ throw new Error("Unable to resolve PayPal order details for authorization.")
163
+ }
173
164
 
174
- const ppText = await ppResp.text()
175
- debugId = ppResp.headers.get("paypal-debug-id")
176
- if (!ppResp.ok) {
177
- throw new Error(
178
- `PayPal create order error (${ppResp.status}): ${ppText}${
179
- debugId ? ` debug_id=${debugId}` : ""
180
- }`
181
- )
182
- }
165
+ const capture = order?.purchase_units?.[0]?.payments?.captures?.[0]
166
+ const authorization = order?.purchase_units?.[0]?.payments?.authorizations?.[0]
183
167
 
184
- order = JSON.parse(ppText) as Record<string, any>
185
- orderId = String(order.id || "")
186
- } else {
187
- order = (await this.getOrderDetails(orderId)) as Record<string, any> | null
168
+ // Derive the status from what actually happened at PayPal, never from the
169
+ // mere presence of a capture/authorization or from the configured
170
+ // paymentAction: a PENDING (eCheck) capture is not settled money and a
171
+ // DENIED/DECLINED one must fail the authorization.
172
+ if (capture?.id) {
173
+ const captureStatus = this.mapCaptureStatus(capture?.status)
174
+ if (captureStatus === "captured") {
175
+ return {
176
+ status: "captured",
177
+ data: {
178
+ ...(data || {}),
179
+ paypal: {
180
+ ...existingPayPal,
181
+ order_id: orderId,
182
+ order,
183
+ capture_id: capture.id,
184
+ capture,
185
+ },
186
+ captured_at: new Date().toISOString(),
187
+ },
188
+ }
189
+ }
190
+ if (captureStatus === "pending") {
191
+ return {
192
+ status: "authorized",
193
+ data: {
194
+ ...(data || {}),
195
+ paypal: {
196
+ ...existingPayPal,
197
+ order_id: orderId,
198
+ order,
199
+ capture_id: capture.id,
200
+ },
201
+ authorized_at: new Date().toISOString(),
202
+ },
203
+ }
204
+ }
205
+ if (captureStatus === "error" || captureStatus === "canceled") {
206
+ return {
207
+ status: "error",
208
+ data: {
209
+ ...(data || {}),
210
+ paypal: { ...existingPayPal, order_id: orderId, order },
211
+ },
212
+ }
213
+ }
188
214
  }
189
215
 
190
- if (!order || !orderId) {
191
- throw new Error("Unable to resolve PayPal order details for authorization.")
216
+ if (authorization?.id) {
217
+ const authStatus = this.mapAuthorizationStatus(authorization?.status)
218
+ if (authStatus === "authorized") {
219
+ return {
220
+ status: "authorized",
221
+ data: {
222
+ ...(data || {}),
223
+ paypal: {
224
+ ...existingPayPal,
225
+ order_id: orderId,
226
+ order,
227
+ authorization_id: authorization.id,
228
+ authorizations:
229
+ order?.purchase_units?.[0]?.payments?.authorizations || [],
230
+ },
231
+ authorized_at: new Date().toISOString(),
232
+ },
233
+ }
234
+ }
235
+ if (authStatus === "error" || authStatus === "canceled") {
236
+ return {
237
+ status: "error",
238
+ data: {
239
+ ...(data || {}),
240
+ paypal: { ...existingPayPal, order_id: orderId, order },
241
+ },
242
+ }
243
+ }
192
244
  }
193
245
 
194
- const existingAuthorization =
195
- order?.purchase_units?.[0]?.payments?.authorizations?.[0] || null
196
- const existingCapture =
197
- order?.purchase_units?.[0]?.payments?.captures?.[0] || null
246
+ const orderStatus = String(order?.status || "").toUpperCase()
247
+ const orderIntent = String(order?.intent || "").toUpperCase()
198
248
 
199
- if (existingAuthorization) {
200
- authorization = order
201
- } else if (existingCapture) {
249
+ if (orderStatus === "APPROVED") {
250
+ if (orderIntent === "AUTHORIZE") {
251
+ // Approved AUTHORIZE-intent order with no authorization yet: create it.
252
+ const { accessToken, base } = await this.getPayPalAccessToken()
253
+ const authorizeResp = await paypalFetch(
254
+ `${base}/v2/checkout/orders/${encodeURIComponent(orderId)}/authorize`,
255
+ {
256
+ method: "POST",
257
+ headers: {
258
+ Authorization: `Bearer ${accessToken}`,
259
+ "Content-Type": "application/json",
260
+ "PayPal-Request-Id": `${requestId}-auth`,
261
+ "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
262
+ },
263
+ }
264
+ )
265
+ const authorizeText = await authorizeResp.text()
266
+ const authorizeDebugId = authorizeResp.headers.get("paypal-debug-id")
267
+ if (!authorizeResp.ok) {
268
+ throw new Error(
269
+ `PayPal authorize order error (${authorizeResp.status}): ${authorizeText}${
270
+ authorizeDebugId ? ` debug_id=${authorizeDebugId}` : ""
271
+ }`
272
+ )
273
+ }
274
+ const authorized = JSON.parse(authorizeText) as Record<string, any>
275
+ const authorizationId =
276
+ authorized?.purchase_units?.[0]?.payments?.authorizations?.[0]?.id
277
+ return {
278
+ status: "authorized",
279
+ data: {
280
+ ...(data || {}),
281
+ paypal: {
282
+ ...existingPayPal,
283
+ order_id: orderId,
284
+ order: authorized || order,
285
+ authorization_id: authorizationId,
286
+ authorizations:
287
+ authorized?.purchase_units?.[0]?.payments?.authorizations || [],
288
+ },
289
+ authorized_at: new Date().toISOString(),
290
+ },
291
+ }
292
+ }
293
+
294
+ // Approved CAPTURE-intent order: the buyer approved but the capture has
295
+ // not happened yet (e.g. the storefront capture call failed). Report
296
+ // "authorized" so the order can complete; capturePayment then routes the
297
+ // actual capture by intent. Calling /authorize here — as the previous
298
+ // code did for every intent — always fails with 422 UNSUPPORTED_INTENT
299
+ // and permanently stuck the checkout.
202
300
  return {
203
- status: returnStatus,
301
+ status: "authorized",
204
302
  data: {
205
303
  ...(data || {}),
206
304
  paypal: {
207
305
  ...existingPayPal,
208
306
  order_id: orderId,
209
307
  order,
210
- capture_id: existingCapture.id,
211
- capture: existingCapture,
212
308
  },
213
- [timestampKey]: new Date().toISOString(),
214
- },
215
- }
216
- } else {
217
- const authorizeResp = await paypalFetch(`${base}/v2/checkout/orders/${encodeURIComponent(orderId)}/authorize`, {
218
- method: "POST",
219
- headers: {
220
- Authorization: `Bearer ${accessToken}`,
221
- "Content-Type": "application/json",
222
- "PayPal-Request-Id": `${requestId}-auth`,
223
- "PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
309
+ authorized_at: new Date().toISOString(),
224
310
  },
225
- })
226
-
227
- const authorizeText = await authorizeResp.text()
228
- const authorizeDebugId = authorizeResp.headers.get("paypal-debug-id")
229
- if (!authorizeResp.ok) {
230
- throw new Error(
231
- `PayPal authorize order error (${authorizeResp.status}): ${authorizeText}${
232
- authorizeDebugId ? ` debug_id=${authorizeDebugId}` : ""
233
- }`
234
- )
235
311
  }
236
-
237
- authorization = JSON.parse(authorizeText)
238
312
  }
239
313
 
240
- const authorizationId =
241
- authorization?.purchase_units?.[0]?.payments?.authorizations?.[0]?.id ||
242
- existingAuthorization?.id
243
-
244
- return {
245
- status: "authorized",
246
- data: {
247
- ...(data || {}),
248
- paypal: {
249
- ...existingPayPal,
250
- order_id: orderId,
251
- order: order || authorization,
252
- authorization_id: authorizationId,
253
- authorizations: authorization?.purchase_units?.[0]?.payments?.authorizations || [],
254
- },
255
- authorized_at: new Date().toISOString(),
256
- },
257
- }
314
+ // CREATED / SAVED / PAYER_ACTION_REQUIRED etc.: the buyer never approved
315
+ // the payment — nothing is authorized at PayPal.
316
+ await this.recordFailure("authorize_failed", {
317
+ order_id: orderId,
318
+ order_status: orderStatus,
319
+ message: "PayPal order not approved by buyer",
320
+ })
321
+ throw new MedusaError(
322
+ MedusaError.Types.NOT_ALLOWED,
323
+ `PayPal order ${orderId} has not been approved by the buyer (status ${orderStatus || "UNKNOWN"}). The payment cannot be authorized.`
324
+ )
258
325
  }
259
326
 
260
327
  async capturePayment(_input: CapturePaymentInput): Promise<CapturePaymentOutput> {
@@ -280,7 +347,11 @@ class PayPalAdvancedCardProvider extends PayPalProviderBase {
280
347
  }
281
348
  }
282
349
 
283
- const { amount, currencyCode } = await this.normalizePaymentData(_input)
350
+ const { amount: sessionAmount, currencyCode } = await this.normalizePaymentData(_input)
351
+ // The requested (possibly partial) capture amount lives on the Medusa
352
+ // capture row, not in the provider input — resolve it so partial captures
353
+ // don't charge the full session total.
354
+ const amount = await this.resolveRequestedCaptureAmount(_input, sessionAmount)
284
355
  // Include the amount in the idempotency suffix: PayPal deduplicates by
285
356
  // PayPal-Request-Id, so two sequential partial captures of the same order
286
357
  // that share an upstream idempotency_key would otherwise collide and the
@@ -288,6 +359,7 @@ class PayPalAdvancedCardProvider extends PayPalProviderBase {
288
359
  const requestId = this.getIdempotencyKey(_input, `capture-${orderId}-${amount}`)
289
360
  let debugId: string | null = null
290
361
 
362
+ try {
291
363
  const { accessToken, base } = await this.getPayPalAccessToken()
292
364
  const order = await this.getOrderDetails(orderId).catch(() => null)
293
365
  const existingCapture = order?.purchase_units?.[0]?.payments?.captures?.[0]
@@ -418,6 +490,16 @@ class PayPalAdvancedCardProvider extends PayPalProviderBase {
418
490
  raw: capture,
419
491
  }
420
492
 
493
+ await this.recordSuccess("capture_success")
494
+ await this.recordPaymentEvent("capture", {
495
+ order_id: orderId,
496
+ capture_id: captureId,
497
+ authorization_id: authorizationId || undefined,
498
+ amount,
499
+ currency_code: currencyCode,
500
+ request_id: requestId,
501
+ })
502
+
421
503
  return {
422
504
  data: {
423
505
  ...(data || {}),
@@ -432,6 +514,22 @@ class PayPalAdvancedCardProvider extends PayPalProviderBase {
432
514
  captured_at: new Date().toISOString(),
433
515
  },
434
516
  }
517
+ } catch (error: any) {
518
+ await this.recordFailure("capture_failed", {
519
+ order_id: orderId,
520
+ request_id: requestId,
521
+ debug_id: debugId,
522
+ message: error?.message,
523
+ })
524
+ // Surface the real reason: Medusa masks non-MedusaErrors as a generic
525
+ // "unknown error" in production, hiding the PayPal failure.
526
+ throw error instanceof MedusaError
527
+ ? error
528
+ : new MedusaError(
529
+ MedusaError.Types.INVALID_DATA,
530
+ error?.message || "PayPal capture failed."
531
+ )
532
+ }
435
533
  }
436
534
 
437
535
  async cancelPayment(_input: CancelPaymentInput): Promise<CancelPaymentOutput> {
@@ -443,6 +541,7 @@ class PayPalAdvancedCardProvider extends PayPalProviderBase {
443
541
  paypalData.authorization_id || data.authorization_id || ""
444
542
  )
445
543
 
544
+ try {
446
545
  const order = orderId ? await this.getOrderDetails(orderId) : null
447
546
  const intent = String(order?.intent || "").toUpperCase()
448
547
  const authorizationId =
@@ -475,6 +574,12 @@ class PayPalAdvancedCardProvider extends PayPalProviderBase {
475
574
  }`
476
575
  )
477
576
  }
577
+
578
+ await this.recordSuccess("void_success")
579
+ await this.recordPaymentEvent("void", {
580
+ order_id: orderId,
581
+ authorization_id: authorizationId,
582
+ })
478
583
  } else if (captureId) {
479
584
  const { accessToken, base } = await this.getPayPalAccessToken()
480
585
  const requestId = this.getIdempotencyKey(_input, `cancel-refund-${captureId}`)
@@ -504,6 +609,18 @@ class PayPalAdvancedCardProvider extends PayPalProviderBase {
504
609
  }
505
610
 
506
611
  const refund = await resp.json().catch(() => ({}))
612
+
613
+ // As with refundPayment: a 2xx response does not guarantee the refund
614
+ // stuck — FAILED / CANCELLED / DENIED refunds also return 2xx. Booking
615
+ // `canceled_at` for a refund that never went through would record a
616
+ // cancellation while the merchant keeps the funds.
617
+ const cancelRefundStatus = String(refund?.status || "").toUpperCase()
618
+ if (isRefundFailureStatus(cancelRefundStatus)) {
619
+ throw new Error(
620
+ `PayPal cancel-refund did not succeed (status=${cancelRefundStatus}). The payment was not canceled.`
621
+ )
622
+ }
623
+
507
624
  const existingRefunds = Array.isArray(paypalData.refunds) ? paypalData.refunds : []
508
625
  const refundEntry = {
509
626
  id: refund?.id,
@@ -512,6 +629,8 @@ class PayPalAdvancedCardProvider extends PayPalProviderBase {
512
629
  raw: refund,
513
630
  }
514
631
 
632
+ await this.recordSuccess("cancel_refund_success")
633
+
515
634
  return {
516
635
  data: {
517
636
  ...(data || {}),
@@ -541,6 +660,14 @@ class PayPalAdvancedCardProvider extends PayPalProviderBase {
541
660
  canceled_at: new Date().toISOString(),
542
661
  },
543
662
  }
663
+ } catch (error: any) {
664
+ await this.recordFailure("cancel_failed", {
665
+ order_id: orderId,
666
+ capture_id: captureId,
667
+ message: error?.message,
668
+ })
669
+ throw error
670
+ }
544
671
  }
545
672
 
546
673
  async refundPayment(_input: RefundPaymentInput): Promise<RefundPaymentOutput> {
@@ -627,6 +754,15 @@ class PayPalAdvancedCardProvider extends PayPalProviderBase {
627
754
  raw: refund,
628
755
  }
629
756
 
757
+ await this.recordSuccess("refund_success")
758
+ await this.recordPaymentEvent("refund", {
759
+ capture_id: captureId,
760
+ refund_id: refund?.id,
761
+ amount,
762
+ currency_code: currencyCode,
763
+ request_id: requestId,
764
+ })
765
+
630
766
  return {
631
767
  data: {
632
768
  ...(data || {}),
@@ -641,6 +777,11 @@ class PayPalAdvancedCardProvider extends PayPalProviderBase {
641
777
  },
642
778
  }
643
779
  } catch (error: any) {
780
+ await this.recordFailure("refund_failed", {
781
+ capture_id: captureId,
782
+ request_id: requestId,
783
+ message: error?.message,
784
+ })
644
785
  // Surface the real reason: Medusa masks any non-MedusaError as a generic
645
786
  // "An unknown error occurred." in production, hiding the PayPal failure.
646
787
  throw error instanceof MedusaError