@easypayment/medusa-payment-paypal 1.1.2 → 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 (68) hide show
  1. package/.medusa/server/src/admin/index.js +72 -72
  2. package/.medusa/server/src/admin/index.mjs +72 -72
  3. package/.medusa/server/src/api/middlewares.d.ts.map +1 -1
  4. package/.medusa/server/src/api/middlewares.js +16 -2
  5. package/.medusa/server/src/api/middlewares.js.map +1 -1
  6. package/.medusa/server/src/api/store/paypal/capture-order/route.d.ts.map +1 -1
  7. package/.medusa/server/src/api/store/paypal/capture-order/route.js +66 -13
  8. package/.medusa/server/src/api/store/paypal/capture-order/route.js.map +1 -1
  9. package/.medusa/server/src/api/store/paypal/create-order/route.d.ts.map +1 -1
  10. package/.medusa/server/src/api/store/paypal/create-order/route.js +11 -6
  11. package/.medusa/server/src/api/store/paypal/create-order/route.js.map +1 -1
  12. package/.medusa/server/src/api/utils/rate-limit.d.ts +13 -1
  13. package/.medusa/server/src/api/utils/rate-limit.d.ts.map +1 -1
  14. package/.medusa/server/src/api/utils/rate-limit.js +7 -5
  15. package/.medusa/server/src/api/utils/rate-limit.js.map +1 -1
  16. package/.medusa/server/src/jobs/paypal-webhook-retry.d.ts.map +1 -1
  17. package/.medusa/server/src/jobs/paypal-webhook-retry.js +4 -0
  18. package/.medusa/server/src/jobs/paypal-webhook-retry.js.map +1 -1
  19. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.d.ts +15 -0
  20. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.d.ts.map +1 -1
  21. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.js +26 -0
  22. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.js.map +1 -1
  23. package/.medusa/server/src/modules/paypal/payment-provider/card-service.d.ts.map +1 -1
  24. package/.medusa/server/src/modules/paypal/payment-provider/card-service.js +244 -169
  25. package/.medusa/server/src/modules/paypal/payment-provider/card-service.js.map +1 -1
  26. package/.medusa/server/src/modules/paypal/payment-provider/service.d.ts +0 -4
  27. package/.medusa/server/src/modules/paypal/payment-provider/service.d.ts.map +1 -1
  28. package/.medusa/server/src/modules/paypal/payment-provider/service.js +8 -25
  29. package/.medusa/server/src/modules/paypal/payment-provider/service.js.map +1 -1
  30. package/.medusa/server/src/modules/paypal/service.d.ts +2 -0
  31. package/.medusa/server/src/modules/paypal/service.d.ts.map +1 -1
  32. package/.medusa/server/src/modules/paypal/service.js +54 -13
  33. package/.medusa/server/src/modules/paypal/service.js.map +1 -1
  34. package/.medusa/server/src/modules/paypal/types/config.d.ts.map +1 -1
  35. package/.medusa/server/src/modules/paypal/types/config.js +13 -0
  36. package/.medusa/server/src/modules/paypal/types/config.js.map +1 -1
  37. package/.medusa/server/src/modules/paypal/utils/amounts.d.ts +1 -1
  38. package/.medusa/server/src/modules/paypal/utils/credential-resolver.d.ts.map +1 -1
  39. package/.medusa/server/src/modules/paypal/utils/credential-resolver.js +10 -34
  40. package/.medusa/server/src/modules/paypal/utils/credential-resolver.js.map +1 -1
  41. package/.medusa/server/src/modules/paypal/utils/metrics.d.ts +18 -0
  42. package/.medusa/server/src/modules/paypal/utils/metrics.d.ts.map +1 -0
  43. package/.medusa/server/src/modules/paypal/utils/metrics.js +45 -0
  44. package/.medusa/server/src/modules/paypal/utils/metrics.js.map +1 -0
  45. package/.medusa/server/src/modules/paypal/webhook-processor.d.ts +16 -0
  46. package/.medusa/server/src/modules/paypal/webhook-processor.d.ts.map +1 -1
  47. package/.medusa/server/src/modules/paypal/webhook-processor.js +85 -2
  48. package/.medusa/server/src/modules/paypal/webhook-processor.js.map +1 -1
  49. package/.medusa/server/src/subscribers/paypal-webhook-process.d.ts.map +1 -1
  50. package/.medusa/server/src/subscribers/paypal-webhook-process.js +4 -0
  51. package/.medusa/server/src/subscribers/paypal-webhook-process.js.map +1 -1
  52. package/CHANGELOG.md +208 -146
  53. package/README.md +175 -184
  54. package/package.json +91 -88
  55. package/src/api/middlewares.ts +16 -2
  56. package/src/api/store/paypal/capture-order/route.ts +83 -12
  57. package/src/api/store/paypal/create-order/route.ts +11 -7
  58. package/src/api/utils/rate-limit.ts +20 -5
  59. package/src/jobs/paypal-webhook-retry.ts +4 -0
  60. package/src/modules/paypal/payment-provider/base-provider.ts +31 -0
  61. package/src/modules/paypal/payment-provider/card-service.ts +84 -0
  62. package/src/modules/paypal/payment-provider/service.ts +12 -30
  63. package/src/modules/paypal/service.ts +1703 -1651
  64. package/src/modules/paypal/types/config.ts +16 -0
  65. package/src/modules/paypal/utils/credential-resolver.ts +9 -36
  66. package/src/modules/paypal/utils/metrics.ts +48 -0
  67. package/src/modules/paypal/webhook-processor.ts +101 -2
  68. 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
- async function getExistingCapture(cartId: string, orderId: string, scope: any) {
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
- if (paypalData.capture) return paypalData.capture
128
- if (paypalData.capture_id) return { id: paypalData.capture_id }
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
- const requestId = resolveIdempotencyKey(req, "capture-order", `pp-capture-${orderId}`)
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": requestId,
280
+ "PayPal-Request-Id": paypalRequestId,
210
281
  "PayPal-Partner-Attribution-Id": BN_CODE,
211
282
  },
212
283
  })
@@ -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
@@ -431,13 +430,18 @@ export async function POST(req: MedusaRequest, res: MedusaResponse) {
431
430
  const base = getPayPalApiBase(creds.environment)
432
431
  const accessToken = await paypal.getAppAccessToken()
433
432
 
434
- // Deterministic-per-cart idempotency key for the PayPal call. Kept distinct
435
- // from `requestId` (the log/response correlation id declared at the top of
436
- // POST) so the two never shadow each other.
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.
437
441
  const paypalRequestId = resolveIdempotencyKey(
438
442
  req,
439
- `create-order-${cart.id}`,
440
- `pp-create-${cart.id}`
443
+ `create-order-${cart.id}-${value}-${currency}`,
444
+ `pp-create-${cart.id}-${value}-${currency}`
441
445
  )
442
446
 
443
447
  const ppResp = await paypalFetch(`${base}/v2/checkout/orders`, {
@@ -36,8 +36,8 @@ 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.PAYPAL_RATE_LIMIT_MAX
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
@@ -62,8 +62,23 @@ function clientKey(req: MedusaRequest): string {
62
62
  return ip
63
63
  }
64
64
 
65
- export function createRateLimiter(scope: string) {
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 = {}) {
66
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"
67
82
 
68
83
  return function rateLimit(
69
84
  req: MedusaRequest,
@@ -72,11 +87,11 @@ export function createRateLimiter(scope: string) {
72
87
  ) {
73
88
  // Opt-in: with no configured max, this middleware is a pass-through so
74
89
  // existing deployments (especially behind a shared-IP proxy) are unaffected.
75
- const max = readConfiguredMax()
90
+ const max = readConfiguredMax(maxEnvVar)
76
91
  if (max === null) {
77
92
  return next()
78
93
  }
79
- const windowMs = readEnvInt("PAYPAL_RATE_LIMIT_WINDOW_MS", DEFAULT_WINDOW_MS)
94
+ const windowMs = readEnvInt(windowEnvVar, DEFAULT_WINDOW_MS)
80
95
  const now = Date.now()
81
96
  const key = `${scope}:${clientKey(req)}`
82
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()
@@ -66,11 +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 || {}),
73
76
  ...this.invalidateStaleOrder(input, currencyCode),
77
+ ...(providerId ? { provider_id: providerId } : {}),
74
78
  amount: input.amount,
75
79
  currency_code: currencyCode,
76
80
  },
@@ -114,6 +118,11 @@ class PayPalAdvancedCardProvider extends PayPalProviderBase {
114
118
  // The previous fallback created a fresh order here and immediately
115
119
  // called /authorize on it, which PayPal always rejects (no payment
116
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
+ })
117
126
  throw new MedusaError(
118
127
  MedusaError.Types.NOT_ALLOWED,
119
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."
@@ -304,6 +313,11 @@ class PayPalAdvancedCardProvider extends PayPalProviderBase {
304
313
 
305
314
  // CREATED / SAVED / PAYER_ACTION_REQUIRED etc.: the buyer never approved
306
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
+ })
307
321
  throw new MedusaError(
308
322
  MedusaError.Types.NOT_ALLOWED,
309
323
  `PayPal order ${orderId} has not been approved by the buyer (status ${orderStatus || "UNKNOWN"}). The payment cannot be authorized.`
@@ -345,6 +359,7 @@ class PayPalAdvancedCardProvider extends PayPalProviderBase {
345
359
  const requestId = this.getIdempotencyKey(_input, `capture-${orderId}-${amount}`)
346
360
  let debugId: string | null = null
347
361
 
362
+ try {
348
363
  const { accessToken, base } = await this.getPayPalAccessToken()
349
364
  const order = await this.getOrderDetails(orderId).catch(() => null)
350
365
  const existingCapture = order?.purchase_units?.[0]?.payments?.captures?.[0]
@@ -475,6 +490,16 @@ class PayPalAdvancedCardProvider extends PayPalProviderBase {
475
490
  raw: capture,
476
491
  }
477
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
+
478
503
  return {
479
504
  data: {
480
505
  ...(data || {}),
@@ -489,6 +514,22 @@ class PayPalAdvancedCardProvider extends PayPalProviderBase {
489
514
  captured_at: new Date().toISOString(),
490
515
  },
491
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
+ }
492
533
  }
493
534
 
494
535
  async cancelPayment(_input: CancelPaymentInput): Promise<CancelPaymentOutput> {
@@ -500,6 +541,7 @@ class PayPalAdvancedCardProvider extends PayPalProviderBase {
500
541
  paypalData.authorization_id || data.authorization_id || ""
501
542
  )
502
543
 
544
+ try {
503
545
  const order = orderId ? await this.getOrderDetails(orderId) : null
504
546
  const intent = String(order?.intent || "").toUpperCase()
505
547
  const authorizationId =
@@ -532,6 +574,12 @@ class PayPalAdvancedCardProvider extends PayPalProviderBase {
532
574
  }`
533
575
  )
534
576
  }
577
+
578
+ await this.recordSuccess("void_success")
579
+ await this.recordPaymentEvent("void", {
580
+ order_id: orderId,
581
+ authorization_id: authorizationId,
582
+ })
535
583
  } else if (captureId) {
536
584
  const { accessToken, base } = await this.getPayPalAccessToken()
537
585
  const requestId = this.getIdempotencyKey(_input, `cancel-refund-${captureId}`)
@@ -561,6 +609,18 @@ class PayPalAdvancedCardProvider extends PayPalProviderBase {
561
609
  }
562
610
 
563
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
+
564
624
  const existingRefunds = Array.isArray(paypalData.refunds) ? paypalData.refunds : []
565
625
  const refundEntry = {
566
626
  id: refund?.id,
@@ -569,6 +629,8 @@ class PayPalAdvancedCardProvider extends PayPalProviderBase {
569
629
  raw: refund,
570
630
  }
571
631
 
632
+ await this.recordSuccess("cancel_refund_success")
633
+
572
634
  return {
573
635
  data: {
574
636
  ...(data || {}),
@@ -598,6 +660,14 @@ class PayPalAdvancedCardProvider extends PayPalProviderBase {
598
660
  canceled_at: new Date().toISOString(),
599
661
  },
600
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
+ }
601
671
  }
602
672
 
603
673
  async refundPayment(_input: RefundPaymentInput): Promise<RefundPaymentOutput> {
@@ -684,6 +754,15 @@ class PayPalAdvancedCardProvider extends PayPalProviderBase {
684
754
  raw: refund,
685
755
  }
686
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
+
687
766
  return {
688
767
  data: {
689
768
  ...(data || {}),
@@ -698,6 +777,11 @@ class PayPalAdvancedCardProvider extends PayPalProviderBase {
698
777
  },
699
778
  }
700
779
  } catch (error: any) {
780
+ await this.recordFailure("refund_failed", {
781
+ capture_id: captureId,
782
+ request_id: requestId,
783
+ message: error?.message,
784
+ })
701
785
  // Surface the real reason: Medusa masks any non-MedusaError as a generic
702
786
  // "An unknown error occurred." in production, hiding the PayPal failure.
703
787
  throw error instanceof MedusaError
@@ -37,36 +37,6 @@ class PayPalPaymentProvider extends PayPalProviderBase {
37
37
  protected readonly sessionPrefix = "pp"
38
38
  protected readonly idempotencyPrefix = "pp"
39
39
 
40
- private serializeError(error: unknown) {
41
- if (error instanceof Error) {
42
- const errorWithCause = error as Error & { cause?: unknown }
43
- const cause = errorWithCause.cause
44
- return {
45
- name: error.name,
46
- message: error.message,
47
- stack: error.stack,
48
- cause:
49
- cause instanceof Error
50
- ? { name: cause.name, message: cause.message, stack: cause.stack }
51
- : cause,
52
- }
53
- }
54
- return { message: String(error) }
55
- }
56
-
57
- private async recordFailure(eventType: string, metadata?: Record<string, unknown>) {
58
- await this.paypal.recordAuditEvent(eventType, metadata)
59
- await this.paypal.recordMetric(eventType, metadata)
60
- }
61
-
62
- private async recordSuccess(metricName: string) {
63
- await this.paypal.recordMetric(metricName)
64
- }
65
-
66
- private async recordPaymentEvent(eventType: string, metadata?: Record<string, unknown>) {
67
- await this.paypal.recordAuditEvent(eventType, metadata)
68
- }
69
-
70
40
  async initiatePayment(input: InitiatePaymentInput): Promise<InitiatePaymentOutput> {
71
41
  const providerId = (input.data as Record<string, any> | undefined)?.provider_id
72
42
  try {
@@ -798,6 +768,18 @@ class PayPalPaymentProvider extends PayPalProviderBase {
798
768
  }
799
769
 
800
770
  const refund = await resp.json().catch(() => ({}))
771
+
772
+ // As with refundPayment: a 2xx response does not guarantee the refund
773
+ // stuck — FAILED / CANCELLED / DENIED refunds also return 2xx. Booking
774
+ // `canceled_at` for a refund that never went through would record a
775
+ // cancellation while the merchant keeps the funds.
776
+ const cancelRefundStatus = String(refund?.status || "").toUpperCase()
777
+ if (isRefundFailureStatus(cancelRefundStatus)) {
778
+ throw new Error(
779
+ `PayPal cancel-refund did not succeed (status=${cancelRefundStatus}). The payment was not canceled.`
780
+ )
781
+ }
782
+
801
783
  const existingRefunds = Array.isArray(paypalData.refunds) ? paypalData.refunds : []
802
784
  const refundEntry = {
803
785
  id: refund?.id,