@easypayment/medusa-payment-paypal 1.2.7 → 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 (99) 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/provider-ids.d.ts +2 -1
  62. package/.medusa/server/src/modules/paypal/utils/provider-ids.d.ts.map +1 -1
  63. package/.medusa/server/src/modules/paypal/utils/provider-ids.js.map +1 -1
  64. package/.medusa/server/src/modules/paypal/utils/settings-cache.d.ts +21 -0
  65. package/.medusa/server/src/modules/paypal/utils/settings-cache.d.ts.map +1 -0
  66. package/.medusa/server/src/modules/paypal/utils/settings-cache.js +48 -0
  67. package/.medusa/server/src/modules/paypal/utils/settings-cache.js.map +1 -0
  68. package/.medusa/server/src/modules/paypal/webhook-processor.d.ts.map +1 -1
  69. package/.medusa/server/src/modules/paypal/webhook-processor.js +17 -4
  70. package/.medusa/server/src/modules/paypal/webhook-processor.js.map +1 -1
  71. package/.medusa/server/src/subscribers/paypal-webhook-process.d.ts.map +1 -1
  72. package/.medusa/server/src/subscribers/paypal-webhook-process.js +10 -0
  73. package/.medusa/server/src/subscribers/paypal-webhook-process.js.map +1 -1
  74. package/CHANGELOG.md +79 -0
  75. package/README.md +8 -2
  76. package/package.json +6 -3
  77. package/src/api/admin/payment-collections/[id]/payment-sessions/route.ts +2 -4
  78. package/src/api/middlewares.ts +8 -0
  79. package/src/api/store/paypal/capture-order/route.ts +44 -3
  80. package/src/api/store/paypal/create-order/route.ts +72 -0
  81. package/src/api/store/paypal/webhook/route.ts +1 -1
  82. package/src/jobs/paypal-webhook-retry.ts +17 -1
  83. package/src/modules/paypal/models/paypal_webhook_event.ts +37 -15
  84. package/src/modules/paypal/payment-provider/README.md +35 -22
  85. package/src/modules/paypal/payment-provider/base-provider.ts +30 -4
  86. package/src/modules/paypal/payment-provider/card-service.ts +31 -19
  87. package/src/modules/paypal/payment-provider/service.ts +17 -19
  88. package/src/modules/paypal/payment-provider/webhook-utils.ts +0 -9
  89. package/src/modules/paypal/service.ts +69 -6
  90. package/src/modules/paypal/types/config.ts +2 -1
  91. package/src/modules/paypal/utils/credential-resolver.ts +6 -1
  92. package/src/modules/paypal/utils/decline-codes.ts +172 -0
  93. package/src/modules/paypal/utils/partner.ts +4 -1
  94. package/src/modules/paypal/utils/payment-session.ts +9 -1
  95. package/src/modules/paypal/utils/paypal-fetch.ts +26 -2
  96. package/src/modules/paypal/utils/provider-ids.ts +6 -4
  97. package/src/modules/paypal/utils/settings-cache.ts +45 -0
  98. package/src/modules/paypal/webhook-processor.ts +20 -4
  99. package/src/subscribers/paypal-webhook-process.ts +11 -0
@@ -15,13 +15,13 @@ import type {
15
15
  UpdatePaymentInput,
16
16
  UpdatePaymentOutput,
17
17
  } from "@medusajs/framework/types"
18
- import { formatAmountForPayPal, toAmountNumber } from "../utils/amounts"
18
+ import { formatAmountForPayPal } from "../utils/amounts"
19
19
  import {
20
20
  assertPayPalCurrencySupported,
21
21
  normalizeCurrencyCode,
22
22
  } from "../utils/currencies"
23
23
  import { PAYPAL_PARTNER_ATTRIBUTION_ID } from "../utils/partner"
24
- import { paypalFetch, paypalFetchWithRetry } from "../utils/paypal-fetch"
24
+ import { paypalFetchWithRetry } from "../utils/paypal-fetch"
25
25
  import { extractCaptureStatus, isRefundFailureStatus } from "./status-utils"
26
26
  import { PayPalProviderBase } from "./base-provider"
27
27
 
@@ -138,7 +138,7 @@ class PayPalAdvancedCardProvider extends PayPalProviderBase {
138
138
  )
139
139
  }
140
140
 
141
- let order: Record<string, any> | null = null
141
+ let order: Record<string, any> | null
142
142
  try {
143
143
  order = (await this.getOrderDetails(orderId)) as Record<
144
144
  string,
@@ -272,7 +272,7 @@ class PayPalAdvancedCardProvider extends PayPalProviderBase {
272
272
  if (orderIntent === "AUTHORIZE") {
273
273
  // Approved AUTHORIZE-intent order with no authorization yet: create it.
274
274
  const { accessToken, base } = await this.getPayPalAccessToken()
275
- const authorizeResp = await paypalFetch(
275
+ const authorizeResp = await paypalFetchWithRetry(
276
276
  `${base}/v2/checkout/orders/${encodeURIComponent(orderId)}/authorize`,
277
277
  {
278
278
  method: "POST",
@@ -369,7 +369,7 @@ class PayPalAdvancedCardProvider extends PayPalProviderBase {
369
369
  `void-${authorizationId}`
370
370
  )
371
371
 
372
- const resp = await paypalFetch(
372
+ const resp = await paypalFetchWithRetry(
373
373
  `${base}/v2/payments/authorizations/${encodeURIComponent(authorizationId)}/void`,
374
374
  {
375
375
  method: "POST",
@@ -404,7 +404,7 @@ class PayPalAdvancedCardProvider extends PayPalProviderBase {
404
404
  `cancel-refund-${captureId}`
405
405
  )
406
406
 
407
- const resp = await paypalFetch(
407
+ const resp = await paypalFetchWithRetry(
408
408
  `${base}/v2/payments/captures/${encodeURIComponent(captureId)}/refund`,
409
409
  {
410
410
  method: "POST",
@@ -503,12 +503,16 @@ class PayPalAdvancedCardProvider extends PayPalProviderBase {
503
503
  )
504
504
  }
505
505
 
506
+ const refundReason = String(
507
+ paypalData.refund_reason || data.refund_reason || data.reason || ""
508
+ ).trim()
509
+
506
510
  // Use the refund amount Medusa passes (top-level input), not the session
507
511
  // amount in `data` — otherwise a partial refund would refund the full order.
508
- // Medusa passes it as a BigNumberInput, so coerce it to a number; a naive
509
- // Number() of the object form yields NaN and silently refunds the full
510
- // capture.
511
- const amount = toAmountNumber(input.amount)
512
+ // resolveRefundAmount coerces the BigNumberInput and validates it: a
513
+ // missing/zero/NaN amount throws instead of falling through to an empty
514
+ // PayPal payload, which would refund the FULL capture.
515
+ const amount = this.resolveRefundAmount(input)
512
516
  const requestId = this.getIdempotencyKey(
513
517
  input,
514
518
  `refund-${captureId}-${amount}`
@@ -520,15 +524,20 @@ class PayPalAdvancedCardProvider extends PayPalProviderBase {
520
524
 
521
525
  try {
522
526
  const { accessToken, base } = await this.getPayPalAccessToken()
523
- const refundPayload: Record<string, any> =
524
- amount > 0
525
- ? {
526
- amount: {
527
- currency_code: currencyCode,
528
- value: formatAmountForPayPal(amount, currencyCode),
529
- },
530
- }
531
- : {}
527
+ // Always send an explicit amount — an empty body means "refund
528
+ // everything remaining" to PayPal and must never be reachable.
529
+ const refundPayload: Record<string, any> = {
530
+ amount: {
531
+ currency_code: currencyCode,
532
+ value: formatAmountForPayPal(amount, currencyCode),
533
+ },
534
+ }
535
+
536
+ if (refundReason) {
537
+ // PayPal rejects a note_to_payer longer than 255 characters with a 422
538
+ // (which would otherwise fail the whole refund); truncate defensively.
539
+ refundPayload.note_to_payer = refundReason.slice(0, 255)
540
+ }
532
541
 
533
542
  // Retry transient 5xx/429/timeout: the PayPal-Request-Id (which includes
534
543
  // the refund amount) makes the refund idempotent, so a retry after a
@@ -584,6 +593,7 @@ class PayPalAdvancedCardProvider extends PayPalProviderBase {
584
593
  id: refund?.id,
585
594
  status: refund?.status,
586
595
  amount: refund?.amount,
596
+ reason: refundReason || refund?.note_to_payer,
587
597
  raw: refund,
588
598
  }
589
599
 
@@ -594,6 +604,7 @@ class PayPalAdvancedCardProvider extends PayPalProviderBase {
594
604
  amount,
595
605
  currency_code: currencyCode,
596
606
  request_id: requestId,
607
+ reason: refundReason,
597
608
  })
598
609
 
599
610
  return {
@@ -603,6 +614,7 @@ class PayPalAdvancedCardProvider extends PayPalProviderBase {
603
614
  ...paypalData,
604
615
  refund_id: refund?.id,
605
616
  refund_status: refund?.status,
617
+ refund_reason: refundReason || refund?.note_to_payer,
606
618
  refunds: [...existingRefunds, refundEntry],
607
619
  refund,
608
620
  },
@@ -15,13 +15,13 @@ import type {
15
15
  UpdatePaymentInput,
16
16
  UpdatePaymentOutput,
17
17
  } from "@medusajs/framework/types"
18
- import { formatAmountForPayPal, toAmountNumber } from "../utils/amounts"
18
+ import { formatAmountForPayPal } from "../utils/amounts"
19
19
  import {
20
20
  assertPayPalCurrencySupported,
21
21
  normalizeCurrencyCode,
22
22
  } from "../utils/currencies"
23
23
  import { PAYPAL_PARTNER_ATTRIBUTION_ID } from "../utils/partner"
24
- import { paypalFetch, paypalFetchWithRetry } from "../utils/paypal-fetch"
24
+ import { paypalFetchWithRetry } from "../utils/paypal-fetch"
25
25
  import { extractCaptureStatus, isRefundFailureStatus } from "./status-utils"
26
26
  import { PayPalProviderBase } from "./base-provider"
27
27
 
@@ -382,9 +382,10 @@ class PayPalPaymentProvider extends PayPalProviderBase {
382
382
  }
383
383
 
384
384
  // Medusa passes the refund amount as a BigNumberInput (BigNumber instance or
385
- // serialized { value, precision }); coerce it to a number so partial refunds
386
- // send the correct value instead of silently refunding the full capture.
387
- const refundAmount = toAmountNumber(input.amount)
385
+ // serialized { value, precision }). resolveRefundAmount coerces and
386
+ // validates it: a missing/zero/NaN amount throws instead of falling
387
+ // through to an empty PayPal payload, which would refund the FULL capture.
388
+ const refundAmount = this.resolveRefundAmount(input)
388
389
 
389
390
  // Include the amount in the idempotency suffix so two sequential partial
390
391
  // refunds of the same capture are not deduplicated by PayPal into one.
@@ -398,23 +399,20 @@ class PayPalPaymentProvider extends PayPalProviderBase {
398
399
  data.currency_code || currencyOverride || "EUR"
399
400
  )
400
401
 
401
- const refundValue =
402
- refundAmount > 0
403
- ? formatAmountForPayPal(refundAmount, currencyCode)
404
- : null
402
+ const refundValue = formatAmountForPayPal(refundAmount, currencyCode)
405
403
 
406
404
  let debugId: string | null = null
407
405
 
408
406
  try {
409
407
  const { accessToken, base } = await this.getPayPalAccessToken()
410
- const refundPayload: Record<string, any> = refundValue
411
- ? {
412
- amount: {
413
- currency_code: currencyCode || "EUR",
414
- value: refundValue,
415
- },
416
- }
417
- : {}
408
+ // Always send an explicit amount — an empty body means "refund
409
+ // everything remaining" to PayPal and must never be reachable.
410
+ const refundPayload: Record<string, any> = {
411
+ amount: {
412
+ currency_code: currencyCode || "EUR",
413
+ value: refundValue,
414
+ },
415
+ }
418
416
 
419
417
  if (refundReason) {
420
418
  // PayPal rejects a note_to_payer longer than 255 characters with a 422
@@ -544,7 +542,7 @@ class PayPalPaymentProvider extends PayPalProviderBase {
544
542
  `void-${authorizationId}`
545
543
  )
546
544
 
547
- const resp = await paypalFetch(
545
+ const resp = await paypalFetchWithRetry(
548
546
  `${base}/v2/payments/authorizations/${encodeURIComponent(authorizationId)}/void`,
549
547
  {
550
548
  method: "POST",
@@ -579,7 +577,7 @@ class PayPalPaymentProvider extends PayPalProviderBase {
579
577
  `cancel-refund-${captureId}`
580
578
  )
581
579
 
582
- const resp = await paypalFetch(
580
+ const resp = await paypalFetchWithRetry(
583
581
  `${base}/v2/payments/captures/${encodeURIComponent(captureId)}/refund`,
584
582
  {
585
583
  method: "POST",
@@ -52,15 +52,6 @@ function resolveAmount(resource: any): number | undefined {
52
52
  return Number.isFinite(parsed) ? parsed : undefined
53
53
  }
54
54
 
55
- function resolveCurrencyCode(resource: any): string | undefined {
56
- const amount =
57
- resource?.amount ||
58
- resource?.purchase_units?.[0]?.amount ||
59
- resource?.purchase_units?.[0]?.payments?.captures?.[0]?.amount ||
60
- resource?.purchase_units?.[0]?.payments?.authorizations?.[0]?.amount
61
- return amount?.currency_code || undefined
62
- }
63
-
64
55
  function resolveEventType(payload: ProviderWebhookPayload["payload"]) {
65
56
  const raw = payload as { event_type?: string; eventType?: string }
66
57
  return raw?.event_type || raw?.eventType
@@ -9,6 +9,12 @@ import PayPalWebhookEvent from "./models/paypal_webhook_event"
9
9
  import { getPayPalConfig } from "./types/config"
10
10
  import { getPayPalApiBase } from "./utils/paypal-auth"
11
11
  import { normalizeCurrencyCode } from "./utils/currencies"
12
+ import { PAYPAL_PARTNER_ATTRIBUTION_ID } from "./utils/partner"
13
+ import {
14
+ getCachedSettings,
15
+ invalidateSettingsCache,
16
+ setCachedSettings,
17
+ } from "./utils/settings-cache"
12
18
 
13
19
  type Environment = "sandbox" | "live"
14
20
 
@@ -84,7 +90,7 @@ class PayPalModuleService extends MedusaService({
84
90
  }
85
91
 
86
92
  private get bnCode(): string {
87
- return this.cfg.bnCode || "MBJTechnolabs_SI_SPB"
93
+ return this.cfg.bnCode || PAYPAL_PARTNER_ATTRIBUTION_ID
88
94
  }
89
95
 
90
96
  private async getSettingsData() {
@@ -390,7 +396,7 @@ class PayPalModuleService extends MedusaService({
390
396
  const partnerMerchantId = await this.getPartnerMerchantId(env)
391
397
  let tokenPayload: Record<string, any> | null = null
392
398
 
393
- let accessToken = ""
399
+ let accessToken: string
394
400
  if (credentials) {
395
401
  const tokenResp = await this.getAppAccessTokenForCredentials(env, {
396
402
  clientId: credentials.clientId,
@@ -494,7 +500,7 @@ class PayPalModuleService extends MedusaService({
494
500
  metadataCandidates?: any[]
495
501
  }
496
502
  ): Promise<{ sellerMerchantId: string | null; sellerEmail: string | null }> {
497
- let sellerMerchantId = (input.sellerMerchantId || "").trim() || null
503
+ const sellerMerchantId = (input.sellerMerchantId || "").trim() || null
498
504
  let sellerEmail = (input.sellerEmail || "").trim() || null
499
505
 
500
506
  if (!sellerEmail && input.metadataCandidates?.length) {
@@ -544,6 +550,8 @@ class PayPalModuleService extends MedusaService({
544
550
  * app token.
545
551
  */
546
552
  async setEnvironment(env: Environment) {
553
+ // Tokens are minted per environment/credentials — drop them on any switch.
554
+ PayPalModuleService.clientTokenCache.clear()
547
555
  const nextEnv: Environment = env === "sandbox" ? "sandbox" : "live"
548
556
  const row = await this.getCurrentRow()
549
557
  const previousEnv = (row?.environment as Environment) || "live"
@@ -999,6 +1007,8 @@ class PayPalModuleService extends MedusaService({
999
1007
  sellerEmail?: string | null
1000
1008
  environment?: Environment
1001
1009
  }) {
1010
+ // New credentials invalidate any client token minted for the old account.
1011
+ PayPalModuleService.clientTokenCache.clear()
1002
1012
  const row = await this.getCurrentRow()
1003
1013
  const currentEnv = await this.getCurrentEnvironment()
1004
1014
  const env = (input.environment || currentEnv) as Environment
@@ -1437,6 +1447,7 @@ class PayPalModuleService extends MedusaService({
1437
1447
  * a usable credential set.
1438
1448
  */
1439
1449
  async disconnect() {
1450
+ PayPalModuleService.clientTokenCache.clear()
1440
1451
  const row = await this.getCurrentRow()
1441
1452
  if (!row) return
1442
1453
  const env = await this.getCurrentEnvironment()
@@ -1560,9 +1571,47 @@ class PayPalModuleService extends MedusaService({
1560
1571
  return accessToken
1561
1572
  }
1562
1573
 
1563
- /** Mint a browser `client_token` (required by the hosted card fields SDK). */
1574
+ /**
1575
+ * Mint a browser `client_token` (required by the hosted card fields SDK),
1576
+ * cached until shortly before PayPal's stated expiry with single-flight
1577
+ * refresh. The unauthenticated store config route calls this on every
1578
+ * request — without the cache each anonymous hit costs an outbound PayPal
1579
+ * call, which is both slow and an amplification vector.
1580
+ */
1564
1581
  async generateClientToken(opts?: { locale?: string }): Promise<string> {
1565
1582
  const env = await this.getCurrentEnvironment()
1583
+ const cacheKey = `${env}::${opts?.locale || ""}`
1584
+
1585
+ const cached = PayPalModuleService.clientTokenCache.get(cacheKey)
1586
+ if (cached && Date.now() < cached.expiresAt) {
1587
+ return cached.token
1588
+ }
1589
+
1590
+ const inflight = PayPalModuleService.clientTokenInflight.get(cacheKey)
1591
+ if (inflight) return inflight
1592
+
1593
+ const p = this.mintClientToken(env, opts)
1594
+ .then((minted) => {
1595
+ PayPalModuleService.clientTokenCache.set(cacheKey, minted)
1596
+ return minted.token
1597
+ })
1598
+ .finally(() => {
1599
+ PayPalModuleService.clientTokenInflight.delete(cacheKey)
1600
+ })
1601
+ PayPalModuleService.clientTokenInflight.set(cacheKey, p)
1602
+ return p
1603
+ }
1604
+
1605
+ private static clientTokenCache = new Map<
1606
+ string,
1607
+ { token: string; expiresAt: number }
1608
+ >()
1609
+ private static clientTokenInflight = new Map<string, Promise<string>>()
1610
+
1611
+ private async mintClientToken(
1612
+ env: string,
1613
+ opts?: { locale?: string }
1614
+ ): Promise<{ token: string; expiresAt: number }> {
1566
1615
  const baseUrl = getPayPalApiBase(env)
1567
1616
 
1568
1617
  const accessToken = await this.getAppAccessToken()
@@ -1592,11 +1641,20 @@ class PayPalModuleService extends MedusaService({
1592
1641
  )
1593
1642
  }
1594
1643
 
1595
- return token
1644
+ // Refresh 5 minutes before PayPal's stated expiry (default 1h) so a token
1645
+ // handed to a buyer mid-checkout doesn't die under them.
1646
+ const expiresIn = Number((json as any)?.expires_in || 3600)
1647
+ const expiresAt = Date.now() + Math.max(60, expiresIn - 300) * 1000
1648
+
1649
+ return { token, expiresAt }
1596
1650
  }
1597
1651
 
1598
1652
  /** The plugin settings singleton (`{ data }`), never null. */
1599
1653
  async getSettings() {
1654
+ const cached = getCachedSettings<{ data: Record<string, any> }>(
1655
+ "module-settings"
1656
+ )
1657
+ if (cached) return cached
1600
1658
  // Deterministic singleton read: always the OLDEST row. If a first-boot race
1601
1659
  // ever created a duplicate settings row, every reader (here and the
1602
1660
  // credential resolver's raw read) must agree on the same winner — ordering
@@ -1606,7 +1664,9 @@ class PayPalModuleService extends MedusaService({
1606
1664
  { take: 1, order: { created_at: "ASC" } }
1607
1665
  )
1608
1666
  const row = rows?.[0]
1609
- return { data: (row?.data || {}) as Record<string, any> }
1667
+ const result = { data: (row?.data || {}) as Record<string, any> }
1668
+ setCachedSettings("module-settings", result)
1669
+ return result
1610
1670
  }
1611
1671
 
1612
1672
  private deepMerge(
@@ -1662,12 +1722,15 @@ class PayPalModuleService extends MedusaService({
1662
1722
  patch
1663
1723
  )
1664
1724
  await this.updatePayPalSettings({ id: canonical.id, data: merged })
1725
+ invalidateSettingsCache()
1665
1726
  return { data: merged }
1666
1727
  }
1728
+ invalidateSettingsCache()
1667
1729
  return { data: (created.data || {}) as Record<string, any> }
1668
1730
  }
1669
1731
 
1670
1732
  await this.updatePayPalSettings({ id: row.id, data: next })
1733
+ invalidateSettingsCache()
1671
1734
  return { data: next }
1672
1735
  }
1673
1736
 
@@ -1,4 +1,5 @@
1
1
  import { randomBytes } from "crypto"
2
+ import { PAYPAL_PARTNER_ATTRIBUTION_ID } from "../utils/partner"
2
3
 
3
4
  /** Partner-level configuration, resolved from env vars with built-in defaults. */
4
5
  export type PayPalModuleConfig = {
@@ -19,7 +20,7 @@ const STATIC_CFG: PayPalModuleConfig = {
19
20
  "https://www.paypal.com/webapps/merchantboarding/js/lib/lightbox/partner.js",
20
21
  backendUrl: "http://localhost:9000",
21
22
  sellerNonce: "",
22
- bnCode: "MBJTechnolabs_SI_SPB",
23
+ bnCode: PAYPAL_PARTNER_ATTRIBUTION_ID,
23
24
  partnerMerchantIdSandbox: "K6QLN2LPGQRHL",
24
25
  partnerMerchantIdLive: "GT5R877JNBPLL",
25
26
  alertWebhookUrls: [],
@@ -1,4 +1,5 @@
1
1
  import { recordMetricAtomic } from "./metrics"
2
+ import { getCachedSettings, setCachedSettings } from "./settings-cache"
2
3
  import { PAYPAL_PARTNER_ATTRIBUTION_ID as BN_CODE } from "./partner"
3
4
  import { paypalFetch } from "./paypal-fetch"
4
5
  import { decryptSecret, encryptSecret } from "./secret-crypto"
@@ -258,6 +259,8 @@ export class PayPalCredentialResolver {
258
259
  }
259
260
 
260
261
  async getSettings(): Promise<ResolvedSettings> {
262
+ const cached = getCachedSettings<ResolvedSettings>("resolver-settings")
263
+ if (cached) return cached
261
264
  try {
262
265
  // Deterministic singleton read (oldest row wins) — must match the module
263
266
  // service's getSettings ordering so both containers agree on the same
@@ -269,7 +272,7 @@ export class PayPalCredentialResolver {
269
272
  .limit(1)
270
273
 
271
274
  const data = (rows?.[0]?.data || {}) as Record<string, any>
272
- return {
275
+ const resolved: ResolvedSettings = {
273
276
  additionalSettings: (data.additional_settings || {}) as Record<
274
277
  string,
275
278
  unknown
@@ -280,6 +283,8 @@ export class PayPalCredentialResolver {
280
283
  >,
281
284
  apiDetails: (data.api_details || {}) as Record<string, unknown>,
282
285
  }
286
+ setCachedSettings("resolver-settings", resolved)
287
+ return resolved
283
288
  } catch {
284
289
  return {
285
290
  additionalSettings: {},
@@ -0,0 +1,172 @@
1
+ /**
2
+ * Structured card/wallet decline information extracted from PayPal responses.
3
+ *
4
+ * A declined capture used to surface as a generic "Failed to capture PayPal
5
+ * order" 500. This maps PayPal's processor response codes and issue names to
6
+ * a buyer-friendly message plus a `retryable` flag, so storefronts can say
7
+ * "insufficient funds — try another card" and decide whether to offer a retry.
8
+ */
9
+
10
+ export type PayPalDeclineInfo = {
11
+ /** Processor `response_code` (e.g. "5120") or PayPal issue name. */
12
+ code: string
13
+ /** Buyer-friendly message, safe to show in the storefront. */
14
+ message: string
15
+ /**
16
+ * Whether another attempt could plausibly succeed (usually with a different
17
+ * card or funding source). `false` marks hard declines — fraud, restricted
18
+ * accounts — where inviting a retry only frustrates the buyer.
19
+ */
20
+ retryable: boolean
21
+ avs_code?: string
22
+ cvv_code?: string
23
+ }
24
+
25
+ const PROCESSOR_CODES: Record<string, { message: string; retryable: boolean }> =
26
+ {
27
+ "0500": {
28
+ message:
29
+ "The card was declined by the issuing bank. Please try a different card or contact your bank.",
30
+ retryable: true,
31
+ },
32
+ "1330": {
33
+ message: "The card account is not valid. Please use a different card.",
34
+ retryable: true,
35
+ },
36
+ "5100": {
37
+ message: "The card was declined. Please try a different payment method.",
38
+ retryable: true,
39
+ },
40
+ "5110": {
41
+ message:
42
+ "The card's security code (CVV) did not match. Please check the code and try again.",
43
+ retryable: true,
44
+ },
45
+ "5120": {
46
+ message:
47
+ "The card was declined due to insufficient funds. Please use a different payment method.",
48
+ retryable: true,
49
+ },
50
+ "5400": {
51
+ message: "The card has expired. Please use a different card.",
52
+ retryable: true,
53
+ },
54
+ "5180": {
55
+ message:
56
+ "This card cannot be used for this purchase. Please use a different card.",
57
+ retryable: true,
58
+ },
59
+ "9500": {
60
+ message:
61
+ "This transaction was declined. Please contact your bank or use a different payment method.",
62
+ retryable: false,
63
+ },
64
+ "9520": {
65
+ message:
66
+ "This card has been reported lost or stolen and cannot be used. Please use a different card.",
67
+ retryable: false,
68
+ },
69
+ "00N7": {
70
+ message:
71
+ "The card's security code (CVV) was incorrect. Please check the code and try again.",
72
+ retryable: true,
73
+ },
74
+ }
75
+
76
+ const ISSUE_NAMES: Record<string, { message: string; retryable: boolean }> = {
77
+ INSTRUMENT_DECLINED: {
78
+ message:
79
+ "Your payment method was declined. Please try a different card or payment method.",
80
+ retryable: true,
81
+ },
82
+ TRANSACTION_REFUSED: {
83
+ message:
84
+ "The payment was refused. Please try again or use a different payment method.",
85
+ retryable: true,
86
+ },
87
+ PAYER_CANNOT_PAY: {
88
+ message:
89
+ "This PayPal account cannot complete the payment. Please use a different payment method.",
90
+ retryable: false,
91
+ },
92
+ PAYER_ACCOUNT_RESTRICTED: {
93
+ message:
94
+ "The PayPal account is restricted and cannot complete this payment.",
95
+ retryable: false,
96
+ },
97
+ PAYER_ACCOUNT_LOCKED_OR_CLOSED: {
98
+ message:
99
+ "The PayPal account is locked or closed. Please use a different payment method.",
100
+ retryable: false,
101
+ },
102
+ INSUFFICIENT_FUNDS: {
103
+ message:
104
+ "The payment was declined due to insufficient funds. Please use a different payment method.",
105
+ retryable: true,
106
+ },
107
+ CARD_EXPIRED: {
108
+ message: "The card has expired. Please use a different card.",
109
+ retryable: true,
110
+ },
111
+ COMPLIANCE_VIOLATION: {
112
+ message: "This transaction cannot be processed.",
113
+ retryable: false,
114
+ },
115
+ }
116
+
117
+ const GENERIC_DECLINE: { message: string; retryable: boolean } = {
118
+ message:
119
+ "The payment was declined. Please try again or use a different payment method.",
120
+ retryable: true,
121
+ }
122
+
123
+ /**
124
+ * Extract decline info from a PayPal response body — either a 4xx error body
125
+ * (`{ name, details: [{ issue }] }`) or a 2xx capture/authorize payload whose
126
+ * capture came back DECLINED/FAILED (carrying `processor_response`).
127
+ * Returns null when the payload holds no recognizable decline.
128
+ */
129
+ export function extractPayPalDecline(
130
+ payload: unknown
131
+ ): PayPalDeclineInfo | null {
132
+ if (!payload || typeof payload !== "object") return null
133
+ const body = payload as Record<string, any>
134
+
135
+ // 4xx error body with issue details (e.g. 422 UNPROCESSABLE_ENTITY).
136
+ const details = Array.isArray(body.details) ? body.details : []
137
+ for (const detail of details) {
138
+ const issue = String(detail?.issue || "").toUpperCase()
139
+ if (issue && ISSUE_NAMES[issue]) {
140
+ return { code: issue, ...ISSUE_NAMES[issue] }
141
+ }
142
+ if (issue === "INSTRUMENT_DECLINED" || issue.includes("DECLINED")) {
143
+ return { code: issue, ...GENERIC_DECLINE }
144
+ }
145
+ }
146
+
147
+ // 2xx payload with a non-completed capture carrying processor_response.
148
+ const captures: Record<string, any>[] = []
149
+ const direct = body.purchase_units?.[0]?.payments?.captures
150
+ if (Array.isArray(direct)) captures.push(...direct)
151
+ if (body.processor_response) captures.push(body)
152
+
153
+ for (const capture of captures) {
154
+ const status = String(capture?.status || "").toUpperCase()
155
+ const processor = capture?.processor_response as
156
+ | Record<string, any>
157
+ | undefined
158
+ if (!processor) continue
159
+ if (status && status !== "DECLINED" && status !== "FAILED") continue
160
+
161
+ const responseCode = String(processor.response_code || "").toUpperCase()
162
+ const mapped = PROCESSOR_CODES[responseCode] ?? GENERIC_DECLINE
163
+ return {
164
+ code: responseCode || "DECLINED",
165
+ ...mapped,
166
+ avs_code: processor.avs_code ? String(processor.avs_code) : undefined,
167
+ cvv_code: processor.cvv_code ? String(processor.cvv_code) : undefined,
168
+ }
169
+ }
170
+
171
+ return null
172
+ }
@@ -5,4 +5,7 @@
5
5
  * re-declared across the providers, credential resolver, and store routes.
6
6
  * Sent as the `PayPal-Partner-Attribution-Id` header on outbound PayPal calls.
7
7
  */
8
- export const PAYPAL_PARTNER_ATTRIBUTION_ID = "MBJTechnolabs_SI_SPB"
8
+ // "MBJ_Medusa_SI" is the Medusa-platform BN code PayPal assigned on 2026-10-06
9
+ // (replacing "MBJTechnolabs_SI_SPB"); PayPal verifies it on sandbox
10
+ // transactions, so changing it requires re-verification with the partner team.
11
+ export const PAYPAL_PARTNER_ATTRIBUTION_ID = "MBJ_Medusa_SI"
@@ -133,7 +133,15 @@ export async function updatePayPalSessionData(
133
133
 
134
134
  const msg = lastError instanceof Error ? lastError.message : String(lastError)
135
135
  console.error("[PayPal] updatePayPalSessionData failed after retries:", msg)
136
- const hasCaptureData = "capture_id" in extraData || "order_id" in extraData
136
+ // Callers nest the payment data under `paypal` ({ paypal: { capture_id } }),
137
+ // so the money-relevance check must look inside that envelope too — a
138
+ // top-level-only check never fired for real capture persist failures.
139
+ const paypalData = (extraData.paypal || {}) as Record<string, unknown>
140
+ const hasCaptureData =
141
+ "capture_id" in extraData ||
142
+ "order_id" in extraData ||
143
+ "capture_id" in paypalData ||
144
+ "order_id" in paypalData
137
145
  if (hasCaptureData) {
138
146
  console.error(
139
147
  "[PayPal] CRITICAL: Payment data (capture/order) was NOT persisted to session.",