@easypayment/medusa-payment-paypal 1.2.8 → 1.3.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 (95) 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/admin/payment-collections/[id]/payment-sessions/route.d.ts.map +1 -1
  4. package/.medusa/server/src/api/admin/payment-collections/[id]/payment-sessions/route.js +2 -4
  5. package/.medusa/server/src/api/admin/payment-collections/[id]/payment-sessions/route.js.map +1 -1
  6. package/.medusa/server/src/api/middlewares.d.ts.map +1 -1
  7. package/.medusa/server/src/api/middlewares.js +8 -0
  8. package/.medusa/server/src/api/middlewares.js.map +1 -1
  9. package/.medusa/server/src/api/store/paypal/capture-order/route.d.ts.map +1 -1
  10. package/.medusa/server/src/api/store/paypal/capture-order/route.js +39 -2
  11. package/.medusa/server/src/api/store/paypal/capture-order/route.js.map +1 -1
  12. package/.medusa/server/src/api/store/paypal/create-order/route.d.ts.map +1 -1
  13. package/.medusa/server/src/api/store/paypal/create-order/route.js +67 -0
  14. package/.medusa/server/src/api/store/paypal/create-order/route.js.map +1 -1
  15. package/.medusa/server/src/api/store/paypal/webhook/route.js +1 -1
  16. package/.medusa/server/src/api/store/paypal/webhook/route.js.map +1 -1
  17. package/.medusa/server/src/jobs/paypal-webhook-retry.d.ts.map +1 -1
  18. package/.medusa/server/src/jobs/paypal-webhook-retry.js +17 -1
  19. package/.medusa/server/src/jobs/paypal-webhook-retry.js.map +1 -1
  20. package/.medusa/server/src/modules/paypal/models/paypal_webhook_event.d.ts.map +1 -1
  21. package/.medusa/server/src/modules/paypal/models/paypal_webhook_event.js +24 -2
  22. package/.medusa/server/src/modules/paypal/models/paypal_webhook_event.js.map +1 -1
  23. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.d.ts +13 -1
  24. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.d.ts.map +1 -1
  25. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.js +21 -2
  26. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.js.map +1 -1
  27. package/.medusa/server/src/modules/paypal/payment-provider/card-service.d.ts.map +1 -1
  28. package/.medusa/server/src/modules/paypal/payment-provider/card-service.js +25 -16
  29. package/.medusa/server/src/modules/paypal/payment-provider/card-service.js.map +1 -1
  30. package/.medusa/server/src/modules/paypal/payment-provider/service.d.ts.map +1 -1
  31. package/.medusa/server/src/modules/paypal/payment-provider/service.js +15 -16
  32. package/.medusa/server/src/modules/paypal/payment-provider/service.js.map +1 -1
  33. package/.medusa/server/src/modules/paypal/payment-provider/webhook-utils.d.ts.map +1 -1
  34. package/.medusa/server/src/modules/paypal/payment-provider/webhook-utils.js +0 -7
  35. package/.medusa/server/src/modules/paypal/payment-provider/webhook-utils.js.map +1 -1
  36. package/.medusa/server/src/modules/paypal/service.d.ts +10 -1
  37. package/.medusa/server/src/modules/paypal/service.d.ts.map +1 -1
  38. package/.medusa/server/src/modules/paypal/service.js +53 -6
  39. package/.medusa/server/src/modules/paypal/service.js.map +1 -1
  40. package/.medusa/server/src/modules/paypal/types/config.d.ts.map +1 -1
  41. package/.medusa/server/src/modules/paypal/types/config.js +2 -1
  42. package/.medusa/server/src/modules/paypal/types/config.js.map +1 -1
  43. package/.medusa/server/src/modules/paypal/utils/credential-resolver.d.ts.map +1 -1
  44. package/.medusa/server/src/modules/paypal/utils/credential-resolver.js +7 -1
  45. package/.medusa/server/src/modules/paypal/utils/credential-resolver.js.map +1 -1
  46. package/.medusa/server/src/modules/paypal/utils/decline-codes.d.ts +30 -0
  47. package/.medusa/server/src/modules/paypal/utils/decline-codes.d.ts.map +1 -0
  48. package/.medusa/server/src/modules/paypal/utils/decline-codes.js +138 -0
  49. package/.medusa/server/src/modules/paypal/utils/decline-codes.js.map +1 -0
  50. package/.medusa/server/src/modules/paypal/utils/partner.d.ts +1 -1
  51. package/.medusa/server/src/modules/paypal/utils/partner.d.ts.map +1 -1
  52. package/.medusa/server/src/modules/paypal/utils/partner.js +4 -1
  53. package/.medusa/server/src/modules/paypal/utils/partner.js.map +1 -1
  54. package/.medusa/server/src/modules/paypal/utils/payment-session.d.ts.map +1 -1
  55. package/.medusa/server/src/modules/paypal/utils/payment-session.js +8 -1
  56. package/.medusa/server/src/modules/paypal/utils/payment-session.js.map +1 -1
  57. package/.medusa/server/src/modules/paypal/utils/paypal-fetch.d.ts +3 -0
  58. package/.medusa/server/src/modules/paypal/utils/paypal-fetch.d.ts.map +1 -1
  59. package/.medusa/server/src/modules/paypal/utils/paypal-fetch.js +27 -2
  60. package/.medusa/server/src/modules/paypal/utils/paypal-fetch.js.map +1 -1
  61. package/.medusa/server/src/modules/paypal/utils/settings-cache.d.ts +21 -0
  62. package/.medusa/server/src/modules/paypal/utils/settings-cache.d.ts.map +1 -0
  63. package/.medusa/server/src/modules/paypal/utils/settings-cache.js +48 -0
  64. package/.medusa/server/src/modules/paypal/utils/settings-cache.js.map +1 -0
  65. package/.medusa/server/src/modules/paypal/webhook-processor.d.ts.map +1 -1
  66. package/.medusa/server/src/modules/paypal/webhook-processor.js +17 -4
  67. package/.medusa/server/src/modules/paypal/webhook-processor.js.map +1 -1
  68. package/.medusa/server/src/subscribers/paypal-webhook-process.d.ts.map +1 -1
  69. package/.medusa/server/src/subscribers/paypal-webhook-process.js +10 -0
  70. package/.medusa/server/src/subscribers/paypal-webhook-process.js.map +1 -1
  71. package/CHANGELOG.md +79 -0
  72. package/README.md +8 -2
  73. package/package.json +6 -3
  74. package/src/api/admin/payment-collections/[id]/payment-sessions/route.ts +2 -4
  75. package/src/api/middlewares.ts +8 -0
  76. package/src/api/store/paypal/capture-order/route.ts +44 -3
  77. package/src/api/store/paypal/create-order/route.ts +72 -0
  78. package/src/api/store/paypal/webhook/route.ts +1 -1
  79. package/src/jobs/paypal-webhook-retry.ts +17 -1
  80. package/src/modules/paypal/models/paypal_webhook_event.ts +37 -15
  81. package/src/modules/paypal/payment-provider/README.md +35 -22
  82. package/src/modules/paypal/payment-provider/base-provider.ts +30 -4
  83. package/src/modules/paypal/payment-provider/card-service.ts +31 -19
  84. package/src/modules/paypal/payment-provider/service.ts +17 -19
  85. package/src/modules/paypal/payment-provider/webhook-utils.ts +0 -9
  86. package/src/modules/paypal/service.ts +69 -6
  87. package/src/modules/paypal/types/config.ts +2 -1
  88. package/src/modules/paypal/utils/credential-resolver.ts +6 -1
  89. package/src/modules/paypal/utils/decline-codes.ts +172 -0
  90. package/src/modules/paypal/utils/partner.ts +4 -1
  91. package/src/modules/paypal/utils/payment-session.ts +9 -1
  92. package/src/modules/paypal/utils/paypal-fetch.ts +26 -2
  93. package/src/modules/paypal/utils/settings-cache.ts +45 -0
  94. package/src/modules/paypal/webhook-processor.ts +20 -4
  95. package/src/subscribers/paypal-webhook-process.ts +11 -0
@@ -92,7 +92,7 @@ function cbAllowRequest(host: string): boolean {
92
92
  return true
93
93
  }
94
94
 
95
- class CircuitOpenError extends Error {
95
+ export class CircuitOpenError extends Error {
96
96
  constructor() {
97
97
  super(
98
98
  "PayPal circuit breaker is open — API calls are temporarily blocked after repeated failures. Will retry automatically."
@@ -156,9 +156,26 @@ function jitteredDelay(attempt: number): number {
156
156
  }
157
157
 
158
158
  function isRetryable(err: unknown): boolean {
159
- if (err instanceof CircuitOpenError) return true
159
+ // An open breaker stays open for CB_HALF_OPEN_MS (60s); all retry attempts
160
+ // finish within a few seconds, so retrying it is pure wasted latency.
161
+ if (err instanceof CircuitOpenError) return false
160
162
  if (err instanceof Error) {
161
163
  if (err.name === "TimeoutError" || err.name === "AbortError") return true
164
+ // Node's fetch surfaces network failures (DNS, ECONNRESET, socket hangup)
165
+ // as `TypeError: fetch failed` — exactly the transient class retries are
166
+ // for. The request never reached PayPal (or died mid-flight), and the
167
+ // PayPal-Request-Id makes the replay safe.
168
+ if (err instanceof TypeError) return true
169
+ const code = (err as NodeJS.ErrnoException).code
170
+ if (
171
+ code === "ECONNRESET" ||
172
+ code === "ECONNREFUSED" ||
173
+ code === "ETIMEDOUT" ||
174
+ code === "EAI_AGAIN" ||
175
+ code === "UND_ERR_SOCKET"
176
+ ) {
177
+ return true
178
+ }
162
179
  }
163
180
  return false
164
181
  }
@@ -181,6 +198,13 @@ export async function paypalFetchWithRetry(
181
198
  try {
182
199
  const res = await paypalFetch(input, init)
183
200
  if (isRetryableStatus(res.status) && attempt < MAX_RETRIES) {
201
+ // Drain the discarded body so the underlying socket is released back
202
+ // to the pool instead of leaking while we retry.
203
+ try {
204
+ await res.body?.cancel()
205
+ } catch {
206
+ // best-effort cleanup only
207
+ }
184
208
  const delay = jitteredDelay(attempt)
185
209
  await new Promise((r) => setTimeout(r, delay))
186
210
  continue
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Short-TTL in-process cache for the plugin-settings singleton.
3
+ *
4
+ * Settings are read on virtually every payment operation (create-order reads
5
+ * them several times) but change only on an explicit admin save. A short TTL
6
+ * removes the per-request DB round-trips while keeping multi-instance
7
+ * deployments acceptably fresh: another instance picks a change up within the
8
+ * TTL, and the instance that wrote it invalidates immediately.
9
+ *
10
+ * `PAYPAL_SETTINGS_CACHE_MS` overrides the TTL; `0` disables caching.
11
+ */
12
+
13
+ export const SETTINGS_CACHE_TTL_MS = (() => {
14
+ const v = Number(process.env.PAYPAL_SETTINGS_CACHE_MS)
15
+ return Number.isFinite(v) && v >= 0 ? v : 15_000
16
+ })()
17
+
18
+ type Slot = { value: unknown; at: number }
19
+
20
+ const slots = new Map<string, Slot>()
21
+
22
+ export function getCachedSettings<T>(key: string): T | null {
23
+ if (SETTINGS_CACHE_TTL_MS <= 0) return null
24
+ const slot = slots.get(key)
25
+ if (!slot) return null
26
+ if (Date.now() - slot.at >= SETTINGS_CACHE_TTL_MS) {
27
+ slots.delete(key)
28
+ return null
29
+ }
30
+ return slot.value as T
31
+ }
32
+
33
+ export function setCachedSettings(key: string, value: unknown): void {
34
+ if (SETTINGS_CACHE_TTL_MS <= 0) return
35
+ slots.set(key, { value, at: Date.now() })
36
+ }
37
+
38
+ /**
39
+ * Drop every cached settings view (module service AND credential resolver —
40
+ * they cache different shapes of the same row). Called after a settings write
41
+ * so reads in this process are immediately fresh.
42
+ */
43
+ export function invalidateSettingsCache(): void {
44
+ slots.clear()
45
+ }
@@ -236,7 +236,8 @@ async function findPayPalSession(
236
236
  )
237
237
  } catch (e: any) {
238
238
  throw new Error(
239
- `payment collection not found for cart ${cartId}: ${e?.message}`
239
+ `payment collection not found for cart ${cartId}: ${e?.message}`,
240
+ { cause: e }
240
241
  )
241
242
  }
242
243
 
@@ -441,7 +442,9 @@ async function completeCartIfPending(
441
442
  return false
442
443
  }
443
444
  const msg = e instanceof Error ? e.message : String(e)
444
- throw new Error(`webhook cart completion failed for ${cartId}: ${msg}`)
445
+ throw new Error(`webhook cart completion failed for ${cartId}: ${msg}`, {
446
+ cause: e,
447
+ })
445
448
  }
446
449
  }
447
450
 
@@ -533,11 +536,19 @@ export async function processPayPalWebhookEvent(
533
536
  }
534
537
 
535
538
  if (!matchedSession && totalScanned >= MAX_PAGES * PAGE_SIZE) {
539
+ // The matching session may exist beyond the scan window. Throwing a
540
+ // retryable error keeps the event in the retry queue (and eventually
541
+ // the dead-letter queue, which is observable) instead of silently
542
+ // dropping a money-state change.
536
543
  console.warn(
537
- `[PayPal] webhook: cartId fallback scan hit limit (${totalScanned} sessions). ` +
538
- `Event ${input.eventType} may be lost. Ensure custom_id is set on PayPal orders.`,
544
+ `[PayPal] webhook: cartId fallback scan hit limit (${totalScanned} sessions) ` +
545
+ `for ${input.eventType}; scheduling retry. Ensure custom_id is set on PayPal orders.`,
539
546
  { orderId, captureId }
540
547
  )
548
+ throw new Error(
549
+ `cartId fallback scan limit reached (${totalScanned} sessions) without a match for ` +
550
+ `order_id=${orderId ?? ""} capture_id=${captureId ?? ""} — will retry`
551
+ )
541
552
  }
542
553
 
543
554
  if (matchedSession?.payment_collection_id) {
@@ -548,10 +559,15 @@ export async function processPayPalWebhookEvent(
548
559
  cartId = String(colls?.[0]?.cart_id || "").trim() || null
549
560
  }
550
561
  } catch (e: unknown) {
562
+ // Lookup infrastructure failures (module resolution, DB) and the
563
+ // scan-limit case above are transient — rethrow so the event is retried
564
+ // instead of being processed without a cart and dead-lettered as
565
+ // "cart not found".
551
566
  console.warn(
552
567
  `[PayPal] webhook: cartId fallback lookup failed for ${input.eventType}:`,
553
568
  e instanceof Error ? e.message : e
554
569
  )
570
+ throw e
555
571
  }
556
572
  }
557
573
 
@@ -133,6 +133,17 @@ export default async function paypalWebhookProcessHandler({
133
133
 
134
134
  await paypal.recordMetric("webhook_failed").catch(() => {})
135
135
 
136
+ if (!retryable) {
137
+ // Straight to dead-letter with no retry coming — alert immediately.
138
+ await paypal
139
+ .sendAlert({
140
+ type: "webhook_dead_letter",
141
+ message: `PayPal webhook ${eventType} dead-lettered (non-retryable): ${e?.message || e}`,
142
+ metadata: { id: recordId, event_id: record.event_id },
143
+ })
144
+ .catch(() => {})
145
+ }
146
+
136
147
  console.error("[PayPal] webhook: processing failed (async)", {
137
148
  id: recordId,
138
149
  event_type: eventType,