@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
package/CHANGELOG.md CHANGED
@@ -2,6 +2,85 @@
2
2
 
3
3
  All notable changes to `@easypayment/medusa-payment-paypal` are documented here.
4
4
 
5
+ ## 1.3.0 — 2026-10-06
6
+
7
+ ### Fixed
8
+ - **A missing or zero refund amount can no longer trigger a full refund.** A
9
+ PayPal refund request with an empty body refunds the FULL remaining capture;
10
+ previously a nullish/zero/NaN amount fell through to exactly that. Refunds
11
+ now require an explicit positive amount (shared validation in the base
12
+ provider) and always send it — the unbounded-refund path is unreachable.
13
+ - **Webhook events are no longer silently dropped when the session-scan
14
+ fallback hits its page limit.** Events whose session may lie beyond the scan
15
+ window (and events whose lookup failed on infrastructure errors) are now
16
+ retried on the normal backoff schedule and eventually dead-lettered —
17
+ observable instead of lost.
18
+ - The "capture persisted?" CRITICAL log check inspected only top-level keys
19
+ and never fired for the nested `{ paypal: { capture_id } }` shape every
20
+ caller uses; it now checks inside the envelope.
21
+ - Card refunds now send the merchant's refund reason as `note_to_payer` and
22
+ record it in session/audit data, matching the wallet provider (the two
23
+ implementations had drifted).
24
+
25
+ ### Added
26
+ - **Structured card-decline responses.** When PayPal declines a capture,
27
+ `/store/paypal/capture-order` now answers `402` with a buyer-friendly
28
+ `message` and a `decline` object — `{ code, message, retryable, avs_code?,
29
+ cvv_code? }` mapped from PayPal processor response codes and issue names —
30
+ instead of a generic 500, so storefronts can say "insufficient funds, try
31
+ another card" and decide whether to offer a retry.
32
+ - **Opt-in shipping address on PayPal orders** (`PAYPAL_SEND_SHIPPING_ADDRESS`
33
+ env var or the `sendShippingAddress` additional setting): sends the cart's
34
+ shipping address with `SET_PROVIDED_ADDRESS`, improving PayPal Seller
35
+ Protection eligibility. Fetched in a separate query so the totals
36
+ computation is untouched.
37
+ - **Dead-letter alerts.** Webhook events that exhaust their retries (or fail
38
+ non-retryably) now push an alert to `PAYPAL_ALERT_WEBHOOK_URLS` — the alert
39
+ mechanism existed but nothing called it.
40
+ - **Settings cache** (`PAYPAL_SETTINGS_CACHE_MS`, default 15s, `0` disables):
41
+ plugin settings were read from the DB several times per request; both the
42
+ module service and the credential resolver now share a short-TTL cache,
43
+ invalidated immediately on an admin save.
44
+ - **Client-token caching.** The unauthenticated `/store/paypal/config` route
45
+ minted a fresh browser client token (an outbound PayPal call) on every hit;
46
+ tokens are now cached until shortly before PayPal's stated expiry with
47
+ single-flight refresh, and the cache is cleared on credential/environment
48
+ changes. The config route is also covered by the opt-in rate limiter now.
49
+
50
+ ### Changed
51
+ - **PayPal partner attribution (BN) code changed to `MBJ_Medusa_SI`** — the
52
+ Medusa-platform code PayPal assigned (2026-10-06), sent on every REST call
53
+ as `PayPal-Partner-Attribution-Id` (previously `MBJTechnolabs_SI_SPB`).
54
+ - Transient-failure retries (bounded, jittered, idempotent via
55
+ `PayPal-Request-Id`) now also cover the storefront capture route, void /
56
+ cancel, authorize-on-approve, and order lookups — previously only provider
57
+ captures and refunds retried. Plain network failures (`fetch failed`,
58
+ `ECONNRESET`, DNS) are now classified retryable; an open circuit breaker is
59
+ no longer retried (the breaker stays open longer than any retry window);
60
+ and the discarded body of a retried 5xx response is drained so its socket
61
+ returns to the pool.
62
+ - The webhook-event model now declares the indexes its migrations created
63
+ (transmission-id dedup, retry sweep, event type), so `db:generate` diffs
64
+ stay clean.
65
+ - The PayPal partner attribution (BN) code is defined once and the admin
66
+ payment-sessions route reuses the central provider-id constants; removed a
67
+ dead currency helper.
68
+
69
+ ### Dev
70
+ - ESLint (typescript-eslint) added and clean; lint + format checks run in CI.
71
+ - 27 new tests (182 total): refund-amount validation on both providers,
72
+ decline-code mapping, settings cache, webhook scan-limit retry behavior,
73
+ and the new fetch retry/circuit-breaker classification.
74
+ - `package.json` `files` no longer lists a `scripts` folder that doesn't
75
+ exist inside the package.
76
+
77
+ ## 1.2.8 — 2026-09-28
78
+
79
+ ### Changed
80
+ - `isPayPalProviderId` is now a type guard and the `PayPalProviderId` type is
81
+ exported (aligned with `@easypayment/medusa-paypal-ui` 1.2.8). No runtime
82
+ behavior changes.
83
+
5
84
  ## 1.2.7 — 2026-09-23
6
85
 
7
86
  ### Changed
package/README.md CHANGED
@@ -163,9 +163,15 @@ Everything is managed in **Medusa Admin → Settings → PayPal** — changes ap
163
163
  | `PAYPAL_WEBHOOK_ID_LIVE` / `PAYPAL_WEBHOOK_ID_SANDBOX` | *(auto)* | Manual webhook-id override (normally automatic) |
164
164
  | `PAYPAL_HTTP_TIMEOUT_MS` | `30000` | Timeout for calls to PayPal |
165
165
  | `PAYPAL_CURRENCY` | `EUR` | Fallback currency if none is configured |
166
- | `PAYPAL_ALERT_WEBHOOK_URLS` | *(unset)* | Comma-separated URLs that receive operational alert notifications |
166
+ | `PAYPAL_ALERT_WEBHOOK_URLS` | *(unset)* | Comma-separated URLs that receive operational alerts (including dead-lettered webhook events) |
167
+ | `PAYPAL_SETTINGS_CACHE_MS` | `15000` | In-process cache for plugin settings reads; `0` disables |
168
+ | `PAYPAL_SEND_SHIPPING_ADDRESS` | `false` | `true` sends the cart's shipping address on PayPal orders (`SET_PROVIDED_ADDRESS`) — improves PayPal Seller Protection eligibility |
169
+ | `PAYPAL_PARTNER_SERVICE_URL` | *(built-in)* | Override the partner onboarding service used by the connect flow |
170
+ | `PAYPAL_PARTNER_MERCHANT_ID_SANDBOX` / `PAYPAL_PARTNER_MERCHANT_ID_LIVE` | *(built-in)* | Override the partner merchant ids used for onboarding |
167
171
 
168
- **Monitoring:** operational counters live in the `paypal_metric` table; every webhook is recorded in `paypal_webhook_event` with automatic retries; audit events are logged as JSON lines tagged `"log":"paypal_audit"` (secrets redacted).
172
+ **Declined cards:** when PayPal declines a capture, `/store/paypal/capture-order` responds `402` with a buyer-friendly `message` plus a structured `decline` object — `{ code, message, retryable, avs_code?, cvv_code? }` — so storefronts can show "insufficient funds, try another card" and decide whether to offer a retry.
173
+
174
+ **Monitoring:** operational counters live in the `paypal_metric` table; every webhook is recorded in `paypal_webhook_event` with automatic retries (events that exhaust retries are dead-lettered **and pushed to `PAYPAL_ALERT_WEBHOOK_URLS`**); audit events are logged as JSON lines tagged `"log":"paypal_audit"` (secrets redacted).
169
175
 
170
176
  </details>
171
177
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@easypayment/medusa-payment-paypal",
3
- "version": "1.2.7",
3
+ "version": "1.3.0",
4
4
  "description": "PayPal & credit card payments for Medusa v2 — PayPal Buttons, hosted card fields, 3D Secure, and an admin dashboard. Built by a PayPal Partner.",
5
5
  "author": "EasyPayment Plugins",
6
6
  "license": "MIT",
@@ -9,7 +9,6 @@
9
9
  "files": [
10
10
  ".medusa/server",
11
11
  "src",
12
- "scripts",
13
12
  "package.json",
14
13
  "README.md",
15
14
  "CHANGELOG.md",
@@ -40,9 +39,11 @@
40
39
  "typecheck": "tsc --noEmit",
41
40
  "format": "prettier --write .",
42
41
  "format:check": "prettier --check .",
43
- "prepublishOnly": "npm run build"
42
+ "prepublishOnly": "npm run build",
43
+ "lint": "eslint src test"
44
44
  },
45
45
  "devDependencies": {
46
+ "@eslint/js": "^10.0.1",
46
47
  "@medusajs/admin-sdk": "2.12.5",
47
48
  "@medusajs/cli": "2.12.5",
48
49
  "@medusajs/framework": "2.12.5",
@@ -52,10 +53,12 @@
52
53
  "@medusajs/ui": "^4.0.0",
53
54
  "@swc/core": "^1.5.7",
54
55
  "@types/react": "^18.3.31",
56
+ "eslint": "^10.12.0",
55
57
  "prettier": "3.6.2",
56
58
  "react": "^18.3.1",
57
59
  "ts-node": "^10.9.2",
58
60
  "typescript": "^5.6.2",
61
+ "typescript-eslint": "^8.71.1",
59
62
  "vitest": "^2.0.5"
60
63
  },
61
64
  "peerDependencies": {
@@ -1,5 +1,6 @@
1
1
  import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
2
2
  import { runCoreWorkflow } from "../../../../../modules/paypal/utils/core-workflow"
3
+ import { PAYPAL_PROVIDER_IDS } from "../../../../../modules/paypal/utils/provider-ids"
3
4
 
4
5
  type CreatePaymentSessionBody = {
5
6
  provider_id: string
@@ -8,10 +9,7 @@ type CreatePaymentSessionBody = {
8
9
  }
9
10
 
10
11
  /** Only PayPal sessions may be created through this admin-side route. */
11
- const ALLOWED_PROVIDERS = new Set([
12
- "pp_paypal_paypal",
13
- "pp_paypal_card_paypal_card",
14
- ])
12
+ const ALLOWED_PROVIDERS = new Set<string>(PAYPAL_PROVIDER_IDS)
15
13
 
16
14
  /** POST /admin/payment-collections/:id/payment-sessions — create a PayPal session. */
17
15
  export async function POST(req: MedusaRequest, res: MedusaResponse) {
@@ -53,6 +53,14 @@ export default defineMiddlewares({
53
53
  method: ["POST"],
54
54
  middlewares: [createRateLimiter("paypal-complete")],
55
55
  },
56
+ {
57
+ // The config route is unauthenticated and (when card payments are on)
58
+ // mints a client token — cached now, but still worth capping so an
59
+ // anonymous flood can't hammer the DB/settings reads behind it.
60
+ matcher: "/store/paypal/config",
61
+ method: ["GET"],
62
+ middlewares: [createRateLimiter("config")],
63
+ },
56
64
  {
57
65
  matcher: "/store/paypal/:path*",
58
66
  middlewares: [],
@@ -5,7 +5,8 @@ import { randomUUID } from "crypto"
5
5
  import type PayPalModuleService from "../../../../modules/paypal/service"
6
6
  import { getPayPalApiBase } from "../../../../modules/paypal/utils/paypal-auth"
7
7
  import { PAYPAL_PARTNER_ATTRIBUTION_ID as BN_CODE } from "../../../../modules/paypal/utils/partner"
8
- import { paypalFetch } from "../../../../modules/paypal/utils/paypal-fetch"
8
+ import { paypalFetchWithRetry } from "../../../../modules/paypal/utils/paypal-fetch"
9
+ import { extractPayPalDecline } from "../../../../modules/paypal/utils/decline-codes"
9
10
  import { extractCaptureStatus } from "../../../../modules/paypal/payment-provider/status-utils"
10
11
  import {
11
12
  findPayPalSessionForCart,
@@ -244,7 +245,7 @@ export async function POST(req: MedusaRequest, res: MedusaResponse) {
244
245
  const accessToken = await paypal.getAppAccessToken()
245
246
 
246
247
  const fetchLiveOrder = async () => {
247
- const resp = await paypalFetch(
248
+ const resp = await paypalFetchWithRetry(
248
249
  `${base}/v2/checkout/orders/${encodeURIComponent(orderId)}`,
249
250
  {
250
251
  method: "GET",
@@ -300,7 +301,9 @@ export async function POST(req: MedusaRequest, res: MedusaResponse) {
300
301
  ? `${base}/v2/checkout/orders/${safeOrderId}/authorize`
301
302
  : `${base}/v2/checkout/orders/${safeOrderId}/capture`
302
303
 
303
- const ppResp = await paypalFetch(endpoint, {
304
+ // Retry transient 5xx/429/timeout/network errors: the PayPal-Request-Id
305
+ // makes the capture idempotent, so a retry replays the same capture.
306
+ const ppResp = await paypalFetchWithRetry(endpoint, {
304
307
  method: "POST",
305
308
  headers: {
306
309
  Authorization: `Bearer ${accessToken}`,
@@ -313,6 +316,27 @@ export async function POST(req: MedusaRequest, res: MedusaResponse) {
313
316
  const ppText = await ppResp.text()
314
317
  debugId = ppResp.headers.get("paypal-debug-id")
315
318
  if (!ppResp.ok) {
319
+ // A 4xx decline (INSTRUMENT_DECLINED & co.) is the buyer's problem to
320
+ // fix, not a server failure: surface a structured, buyer-readable
321
+ // decline instead of a generic 500.
322
+ let errBody: unknown = null
323
+ try {
324
+ errBody = JSON.parse(ppText)
325
+ } catch {
326
+ // non-JSON error body — fall through to the generic error
327
+ }
328
+ const decline = extractPayPalDecline(errBody)
329
+ if (decline && ppResp.status < 500) {
330
+ logger.warn(
331
+ `[paypal] capture declined (request_id=${requestId}, order_id=${orderId}, code=${decline.code}${debugId ? `, debug_id=${debugId}` : ""})`
332
+ )
333
+ await paypal.recordMetric("capture_order_declined").catch(() => {})
334
+ return res.status(402).json({
335
+ message: decline.message,
336
+ decline,
337
+ request_id: requestId,
338
+ })
339
+ }
316
340
  throw new Error(
317
341
  `PayPal capture error (${ppResp.status}): ${ppText}${debugId ? ` debug_id=${debugId}` : ""}`
318
342
  )
@@ -335,6 +359,23 @@ export async function POST(req: MedusaRequest, res: MedusaResponse) {
335
359
  // only a COMPLETED capture is reported as success — the webhook will
336
360
  // reconcile a later PENDING→COMPLETED transition.
337
361
  const captureStatus = extractCaptureStatus(payload)
362
+ if (captureStatus === "DECLINED" || captureStatus === "FAILED") {
363
+ const decline = extractPayPalDecline(payload) ?? {
364
+ code: captureStatus,
365
+ message:
366
+ "The payment was declined. Please try again or use a different payment method.",
367
+ retryable: true,
368
+ }
369
+ logger.warn(
370
+ `[paypal] capture declined (request_id=${requestId}, order_id=${orderId}, code=${decline.code}${debugId ? `, debug_id=${debugId}` : ""})`
371
+ )
372
+ await paypal.recordMetric("capture_order_declined").catch(() => {})
373
+ return res.status(402).json({
374
+ message: decline.message,
375
+ decline,
376
+ request_id: requestId,
377
+ })
378
+ }
338
379
  if (captureStatus !== "COMPLETED") {
339
380
  throw new Error(
340
381
  `PayPal capture did not complete (status=${captureStatus || "UNKNOWN"})${
@@ -489,6 +489,77 @@ export async function POST(req: MedusaRequest, res: MedusaResponse) {
489
489
  `[paypal] create-order line items (request_id=${requestId}): send_item_details=${sendItemDetails}, cart_items=${lineItems.length}, sent_items=${finalPurchaseItems.length}, items_total=${itemsTotalMajor}, subtotal=${subtotalMajor}, total=${totalMajor}`
490
490
  )
491
491
 
492
+ // Opt-in: attach the cart's shipping address to the PayPal order
493
+ // (`SET_PROVIDED_ADDRESS`). Improves PayPal Seller Protection eligibility —
494
+ // PayPal only protects shipments to the address on the order. Deliberately
495
+ // a SEPARATE query: adding relation fields to the totals query above has
496
+ // broken the totals decorator before (see the shipping_methods warning).
497
+ const sendShippingAddress =
498
+ additionalSettings.sendShippingAddress === true ||
499
+ String(process.env.PAYPAL_SEND_SHIPPING_ADDRESS || "")
500
+ .trim()
501
+ .toLowerCase() === "true"
502
+ let paypalShipping: Record<string, any> | null = null
503
+ if (sendShippingAddress && !isCardPayment) {
504
+ try {
505
+ const { data: addrData } = await query.graph({
506
+ entity: "cart",
507
+ fields: [
508
+ "id",
509
+ "shipping_address.first_name",
510
+ "shipping_address.last_name",
511
+ "shipping_address.address_1",
512
+ "shipping_address.address_2",
513
+ "shipping_address.city",
514
+ "shipping_address.province",
515
+ "shipping_address.postal_code",
516
+ "shipping_address.country_code",
517
+ ],
518
+ filters: { id: cartId },
519
+ })
520
+ const addr = (addrData?.[0] as any)?.shipping_address
521
+ const line1 = String(addr?.address_1 || "").trim()
522
+ const postal = String(addr?.postal_code || "").trim()
523
+ const country = String(addr?.country_code || "")
524
+ .trim()
525
+ .toUpperCase()
526
+ // PayPal rejects incomplete addresses — only send a usable one.
527
+ if (addr && line1 && postal && country.length === 2) {
528
+ const fullName = [addr.first_name, addr.last_name]
529
+ .map((part: unknown) => String(part || "").trim())
530
+ .filter(Boolean)
531
+ .join(" ")
532
+ paypalShipping = {
533
+ ...(fullName
534
+ ? { name: { full_name: fullName.slice(0, 300) } }
535
+ : {}),
536
+ address: {
537
+ address_line_1: line1.slice(0, 300),
538
+ ...(addr.address_2
539
+ ? { address_line_2: String(addr.address_2).slice(0, 300) }
540
+ : {}),
541
+ ...(addr.city
542
+ ? { admin_area_2: String(addr.city).slice(0, 120) }
543
+ : {}),
544
+ ...(addr.province
545
+ ? { admin_area_1: String(addr.province).slice(0, 300) }
546
+ : {}),
547
+ postal_code: postal.slice(0, 60),
548
+ country_code: country,
549
+ },
550
+ }
551
+ applicationContext.shipping_preference = "SET_PROVIDED_ADDRESS"
552
+ }
553
+ } catch (e: unknown) {
554
+ // Seller protection is an optimization, never a checkout blocker.
555
+ logger.warn(
556
+ `[paypal] create-order: could not attach shipping address (request_id=${requestId}): ${
557
+ e instanceof Error ? e.message : String(e)
558
+ }`
559
+ )
560
+ }
561
+ }
562
+
492
563
  // Use the module's cached app access token (single-flight refresh, ~9h TTL)
493
564
  // instead of minting a fresh OAuth token on every create-order call.
494
565
  const base = getPayPalApiBase(creds.environment)
@@ -537,6 +608,7 @@ export async function POST(req: MedusaRequest, res: MedusaResponse) {
537
608
  ...(finalPurchaseItems.length > 0
538
609
  ? { items: finalPurchaseItems }
539
610
  : {}),
611
+ ...(paypalShipping ? { shipping: paypalShipping } : {}),
540
612
  },
541
613
  ],
542
614
  ...(threeDsMethod
@@ -293,7 +293,7 @@ export async function POST(req: MedusaRequest, res: MedusaResponse) {
293
293
  }
294
294
 
295
295
  const eventVersion = normalizeEventVersion(payload)
296
- let recordId: string | null = null
296
+ let recordId: string | null
297
297
 
298
298
  try {
299
299
  const recordResult = await paypal.createWebhookEventRecord({
@@ -38,7 +38,7 @@ export default async function paypalWebhookRetry(container: MedusaContainer) {
38
38
  // event is processed at most once). Falls back to running directly if the
39
39
  // raw connection isn't resolvable, so the job degrades gracefully rather
40
40
  // than breaking.
41
- let pg: any = null
41
+ let pg: any
42
42
  try {
43
43
  pg = container.resolve(ContainerRegistrationKeys.PG_CONNECTION)
44
44
  } catch {
@@ -141,6 +141,15 @@ async function attemptRetry(
141
141
  attempts: attemptCount,
142
142
  })
143
143
  await paypal.recordMetric("webhook_dead_letter").catch(() => {})
144
+ // Dead-lettered money events need a human: push to the configured alert
145
+ // webhooks (no-op when none are configured).
146
+ await paypal
147
+ .sendAlert({
148
+ type: "webhook_dead_letter",
149
+ message: `PayPal webhook ${event.event_type} dead-lettered after ${attemptCount} attempts`,
150
+ metadata: { id: event.id, event_id: event.event_id },
151
+ })
152
+ .catch(() => {})
144
153
  return
145
154
  }
146
155
 
@@ -228,6 +237,13 @@ async function attemptRetry(
228
237
  error: error?.message,
229
238
  })
230
239
  await paypal.recordMetric("webhook_dead_letter").catch(() => {})
240
+ await paypal
241
+ .sendAlert({
242
+ type: "webhook_dead_letter",
243
+ message: `PayPal webhook ${eventType} dead-lettered: ${error?.message || error}`,
244
+ metadata: { id: event.id, attempt: nextAttempt, retryable },
245
+ })
246
+ .catch(() => {})
231
247
  } else {
232
248
  const nextRetry = computeNextRetryAt(nextAttempt)
233
249
  await paypal
@@ -7,20 +7,42 @@ import { model } from "@medusajs/framework/utils"
7
7
  * (`pending` → `processing` → `processed` | `failed` | `dead_letter` |
8
8
  * `ignored`).
9
9
  */
10
- const PayPalWebhookEvent = model.define("paypal_webhook_event", {
11
- id: model.id().primaryKey(),
12
- event_id: model.text().unique(),
13
- event_type: model.text(),
14
- event_version: model.text().nullable(),
15
- transmission_id: model.text().nullable(),
16
- transmission_time: model.dateTime().nullable(),
17
- status: model.text().default("pending"),
18
- attempt_count: model.number().default(0),
19
- next_retry_at: model.dateTime().nullable(),
20
- processed_at: model.dateTime().nullable(),
21
- last_error: model.text().nullable(),
22
- resource_id: model.text().nullable(),
23
- payload: model.json().default({}),
24
- })
10
+ const PayPalWebhookEvent = model
11
+ .define("paypal_webhook_event", {
12
+ id: model.id().primaryKey(),
13
+ event_id: model.text().unique(),
14
+ event_type: model.text(),
15
+ event_version: model.text().nullable(),
16
+ transmission_id: model.text().nullable(),
17
+ transmission_time: model.dateTime().nullable(),
18
+ status: model.text().default("pending"),
19
+ attempt_count: model.number().default(0),
20
+ next_retry_at: model.dateTime().nullable(),
21
+ processed_at: model.dateTime().nullable(),
22
+ last_error: model.text().nullable(),
23
+ resource_id: model.text().nullable(),
24
+ payload: model.json().default({}),
25
+ })
26
+ .indexes([
27
+ // Declared on the model (with the migrations' exact names and predicates)
28
+ // so a future `db:generate` diff doesn't try to drop or duplicate the
29
+ // indexes the migrations created.
30
+ // Dedup lookup on every incoming delivery.
31
+ {
32
+ name: "idx_paypal_webhook_event_transmission_id",
33
+ on: ["transmission_id"],
34
+ where: '"transmission_id" IS NOT NULL',
35
+ },
36
+ // Retry sweep: failed events ordered by next_retry_at.
37
+ {
38
+ name: "idx_paypal_webhook_event_status_retry",
39
+ on: ["status", "next_retry_at"],
40
+ where: "status = 'failed'",
41
+ },
42
+ {
43
+ name: "idx_paypal_webhook_event_type",
44
+ on: ["event_type"],
45
+ },
46
+ ])
25
47
 
26
48
  export default PayPalWebhookEvent
@@ -1,22 +1,35 @@
1
- # PayPal Payment Provider (Checkout)
2
-
3
- This folder adds a **Payment Module Provider** so PayPal can appear in checkout.
4
-
5
- Register it in `medusa-config.ts` under the Payment module:
6
-
7
- ```ts
8
- {
9
- resolve: "@medusajs/medusa/payment",
10
- options: {
11
- providers: [
12
- {
13
- resolve: "./src/modules/paypal/payment-provider",
14
- id: "paypal",
15
- options: {},
16
- },
17
- ],
18
- },
19
- }
20
- ```
21
-
22
- Then enable PayPal in Admin -> Regions -> Payment Providers (use `paypal`).
1
+ # PayPal Payment Providers (Checkout)
2
+
3
+ This folder implements the two **Payment Module Providers** this plugin ships —
4
+ PayPal Buttons (`paypal`) and hosted card fields (`paypal_card`) — plus their
5
+ shared base class (`base-provider.ts`), which owns the money-critical logic
6
+ (capture reconciliation, refund amount validation, idempotency keys).
7
+
8
+ Register them in `medusa-config.ts` under the Payment module (see the package
9
+ README for the full config):
10
+
11
+ ```ts
12
+ {
13
+ resolve: "@medusajs/medusa/payment",
14
+ options: {
15
+ providers: [
16
+ {
17
+ resolve: "@easypayment/medusa-payment-paypal/providers/paypal",
18
+ id: "paypal",
19
+ options: {},
20
+ dependencies: ["paypal_onboarding"],
21
+ },
22
+ {
23
+ resolve: "@easypayment/medusa-payment-paypal/providers/paypal_card",
24
+ id: "paypal_card",
25
+ options: {},
26
+ dependencies: ["paypal_onboarding"],
27
+ },
28
+ ],
29
+ },
30
+ }
31
+ ```
32
+
33
+ Then enable the providers in Admin → Settings → Regions → Payment Providers.
34
+ Their full ids are `pp_paypal_paypal` and `pp_paypal_card_paypal_card`
35
+ (exported from `../utils/provider-ids.ts`).
@@ -21,7 +21,7 @@ import {
21
21
  } from "../utils/currencies"
22
22
  import { PayPalCredentialResolver } from "../utils/credential-resolver"
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 { getPayPalWebhookActionAndData } from "./webhook-utils"
26
26
  import {
27
27
  extractCaptureStatus,
@@ -65,7 +65,7 @@ function mergeCaptureEntries(
65
65
  return [...byId.values(), ...anonymous]
66
66
  }
67
67
 
68
- export type Options = {}
68
+ export type Options = Record<string, unknown>
69
69
 
70
70
  /**
71
71
  * Shared base for the two PayPal payment providers (wallet buttons and advanced
@@ -169,7 +169,7 @@ export abstract class PayPalProviderBase extends AbstractPaymentProvider<Options
169
169
 
170
170
  protected async getOrderDetails(orderId: string) {
171
171
  const { accessToken, base } = await this.getPayPalAccessToken()
172
- const resp = await paypalFetch(
172
+ const resp = await paypalFetchWithRetry(
173
173
  `${base}/v2/checkout/orders/${encodeURIComponent(orderId)}`,
174
174
  {
175
175
  method: "GET",
@@ -189,6 +189,32 @@ export abstract class PayPalProviderBase extends AbstractPaymentProvider<Options
189
189
  return JSON.parse(text)
190
190
  }
191
191
 
192
+ /**
193
+ * Resolve and validate the refund amount Medusa passed.
194
+ *
195
+ * A PayPal refund request with an EMPTY body refunds the FULL remaining
196
+ * capture. A missing/zero/NaN amount must therefore never fall through to
197
+ * an empty payload — a buggy BigNumber coercion would silently turn a
198
+ * partial refund into a full one. Refunds always require an explicit
199
+ * positive amount; a merchant refunding everything passes the full amount.
200
+ */
201
+ protected resolveRefundAmount(input: { amount?: unknown }): number {
202
+ if (input.amount === null || input.amount === undefined) {
203
+ throw new MedusaError(
204
+ MedusaError.Types.INVALID_DATA,
205
+ "Refund amount is required. Refusing to send an unbounded refund to PayPal without an explicit amount."
206
+ )
207
+ }
208
+ const amount = toAmountNumber(input.amount)
209
+ if (!Number.isFinite(amount) || amount <= 0) {
210
+ throw new MedusaError(
211
+ MedusaError.Types.INVALID_DATA,
212
+ `Invalid refund amount (${String(amount)}): must be a positive number.`
213
+ )
214
+ }
215
+ return amount
216
+ }
217
+
192
218
  protected getIdempotencyKey(
193
219
  input: { context?: { idempotency_key?: string } },
194
220
  suffix: string
@@ -514,7 +540,7 @@ export abstract class PayPalProviderBase extends AbstractPaymentProvider<Options
514
540
  if (liveAuthorizationId) {
515
541
  authorizationId = String(liveAuthorizationId)
516
542
  } else {
517
- const authorizeResp = await paypalFetch(
543
+ const authorizeResp = await paypalFetchWithRetry(
518
544
  `${base}/v2/checkout/orders/${encodeURIComponent(orderId)}/authorize`,
519
545
  {
520
546
  method: "POST",