@easypayment/medusa-payment-paypal 1.3.8 → 1.3.9

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 (39) hide show
  1. package/.medusa/server/src/admin/index.js +175 -79
  2. package/.medusa/server/src/admin/index.mjs +110 -16
  3. package/.medusa/server/src/api/admin/paypal/merchant-status/route.d.ts +11 -0
  4. package/.medusa/server/src/api/admin/paypal/merchant-status/route.d.ts.map +1 -0
  5. package/.medusa/server/src/api/admin/paypal/merchant-status/route.js +32 -0
  6. package/.medusa/server/src/api/admin/paypal/merchant-status/route.js.map +1 -0
  7. package/.medusa/server/src/api/store/paypal/create-order/route.d.ts +4 -1
  8. package/.medusa/server/src/api/store/paypal/create-order/route.d.ts.map +1 -1
  9. package/.medusa/server/src/api/store/paypal/create-order/route.js +101 -102
  10. package/.medusa/server/src/api/store/paypal/create-order/route.js.map +1 -1
  11. package/.medusa/server/src/modules/paypal/service.d.ts +34 -0
  12. package/.medusa/server/src/modules/paypal/service.d.ts.map +1 -1
  13. package/.medusa/server/src/modules/paypal/service.js +161 -34
  14. package/.medusa/server/src/modules/paypal/service.js.map +1 -1
  15. package/.medusa/server/src/modules/paypal/types/config.d.ts +12 -0
  16. package/.medusa/server/src/modules/paypal/types/config.d.ts.map +1 -1
  17. package/.medusa/server/src/modules/paypal/types/config.js +25 -1
  18. package/.medusa/server/src/modules/paypal/types/config.js.map +1 -1
  19. package/.medusa/server/src/modules/paypal/utils/merchant-status.d.ts +50 -0
  20. package/.medusa/server/src/modules/paypal/utils/merchant-status.d.ts.map +1 -0
  21. package/.medusa/server/src/modules/paypal/utils/merchant-status.js +106 -0
  22. package/.medusa/server/src/modules/paypal/utils/merchant-status.js.map +1 -0
  23. package/.medusa/server/src/modules/paypal/utils/order-context.d.ts +61 -0
  24. package/.medusa/server/src/modules/paypal/utils/order-context.d.ts.map +1 -0
  25. package/.medusa/server/src/modules/paypal/utils/order-context.js +127 -0
  26. package/.medusa/server/src/modules/paypal/utils/order-context.js.map +1 -0
  27. package/CHANGELOG.md +56 -0
  28. package/README.md +3 -2
  29. package/package.json +1 -1
  30. package/src/admin/routes/settings/paypal/_components/MerchantStatusNotices.tsx +116 -0
  31. package/src/admin/routes/settings/paypal/additional-settings/page.tsx +32 -6
  32. package/src/admin/routes/settings/paypal/advanced-card-payments/page.tsx +2 -0
  33. package/src/admin/routes/settings/paypal/connection/page.tsx +7 -0
  34. package/src/api/admin/paypal/merchant-status/route.ts +36 -0
  35. package/src/api/store/paypal/create-order/route.ts +176 -157
  36. package/src/modules/paypal/service.ts +222 -43
  37. package/src/modules/paypal/types/config.ts +35 -2
  38. package/src/modules/paypal/utils/merchant-status.ts +185 -0
  39. package/src/modules/paypal/utils/order-context.ts +163 -0
@@ -17,6 +17,14 @@ import {
17
17
  updatePayPalSessionData,
18
18
  } from "../../../../modules/paypal/utils/payment-session"
19
19
  import { resolveStorefrontUrl } from "../../../../modules/paypal/utils/storefront-url"
20
+ import {
21
+ buildPayPalShipping,
22
+ isShippingAddressRejection,
23
+ resolveLandingPage,
24
+ sameShipping,
25
+ shippingFingerprint,
26
+ type PayPalShipping,
27
+ } from "../../../../modules/paypal/utils/order-context"
20
28
 
21
29
  type Body = {
22
30
  cart_id: string
@@ -81,7 +89,10 @@ async function getExistingPayPalOrderId(req: MedusaRequest, cartId: string) {
81
89
  *
82
90
  * Returns `{ id }` — the PayPal order id the storefront hands to the JS SDK.
83
91
  * Line items and an amount breakdown are sent when `sendItemDetails` is on,
84
- * with rounding drift reconciled so PayPal's strict total checks pass.
92
+ * with rounding drift reconciled so PayPal's strict total checks pass. The
93
+ * shipping address the buyer entered at checkout is sent with
94
+ * `shipping_preference: SET_PROVIDED_ADDRESS` unless `sendShippingAddress` is
95
+ * turned off.
85
96
  */
86
97
  export async function POST(req: MedusaRequest, res: MedusaResponse) {
87
98
  const paypal = req.scope.resolve<PayPalModuleService>("paypal_onboarding")
@@ -191,8 +202,56 @@ export async function POST(req: MedusaRequest, res: MedusaResponse) {
191
202
  const totalMajor = Number(cart.total || 0)
192
203
  const value = totalMajor.toFixed(exponent)
193
204
 
205
+ // The buyer enters the shipping address in the storefront before paying, so
206
+ // it is sent with the order (`shipping_preference: SET_PROVIDED_ADDRESS`)
207
+ // and PayPal shows it as fixed instead of offering the addresses on the
208
+ // buyer's PayPal account. Required by PayPal's partner review, and PayPal
209
+ // only applies Seller Protection to the address on the order. On by
210
+ // default; `sendShippingAddress: false` (or
211
+ // PAYPAL_SEND_SHIPPING_ADDRESS=false) turns it off. Deliberately a
212
+ // SEPARATE query: adding relation fields to the totals query above has
213
+ // broken the totals decorator before (see the shipping_methods warning).
214
+ const sendShippingAddress =
215
+ additionalSettings.sendShippingAddress !== false &&
216
+ String(process.env.PAYPAL_SEND_SHIPPING_ADDRESS || "")
217
+ .trim()
218
+ .toLowerCase() !== "false"
219
+ let paypalShipping: PayPalShipping | null = null
220
+ if (sendShippingAddress) {
221
+ try {
222
+ const { data: addrData } = await query.graph({
223
+ entity: "cart",
224
+ fields: [
225
+ "id",
226
+ "shipping_address.first_name",
227
+ "shipping_address.last_name",
228
+ "shipping_address.address_1",
229
+ "shipping_address.address_2",
230
+ "shipping_address.city",
231
+ "shipping_address.province",
232
+ "shipping_address.postal_code",
233
+ "shipping_address.country_code",
234
+ ],
235
+ filters: { id: cartId },
236
+ })
237
+ // Null for a cart without a complete address (e.g. digital goods):
238
+ // PayPal rejects incomplete addresses, so none is sent then.
239
+ paypalShipping = buildPayPalShipping(
240
+ (addrData?.[0] as any)?.shipping_address
241
+ )
242
+ } catch (e: unknown) {
243
+ // The address is an addition to the order, never a checkout blocker.
244
+ logger.warn(
245
+ `[paypal] create-order: could not read the shipping address (request_id=${requestId}): ${
246
+ e instanceof Error ? e.message : String(e)
247
+ }`
248
+ )
249
+ }
250
+ }
251
+
194
252
  // Reuse the stored PayPal order only when it still matches the cart: same
195
- // amount, same currency, and still in a reusable (pre-terminal) state. On
253
+ // amount, same currency, same shipping address, and still in a reusable
254
+ // (pre-terminal) state. On
196
255
  // mismatch fall through and create a fresh order (which replaces the
197
256
  // stored id on the session). If PayPal can't be reached for the check,
198
257
  // reuse the stored id — matching the previous behavior rather than
@@ -226,7 +285,15 @@ export async function POST(req: MedusaRequest, res: MedusaResponse) {
226
285
  String(existingAmount?.value || "") === value &&
227
286
  String(existingAmount?.currency_code || "").toUpperCase() ===
228
287
  currency
229
- if (reusableStatus && amountMatches) {
288
+ // An order created for a previous address would show (and protect)
289
+ // the wrong destination, so it is replaced when the address changed.
290
+ const shippingMatches =
291
+ !paypalShipping ||
292
+ sameShipping(
293
+ existingOrder?.purchase_units?.[0]?.shipping,
294
+ paypalShipping
295
+ )
296
+ if (reusableStatus && amountMatches && shippingMatches) {
230
297
  return res.json({ id: existingOrderId })
231
298
  }
232
299
  if (existingStatus === "COMPLETED") {
@@ -234,7 +301,7 @@ export async function POST(req: MedusaRequest, res: MedusaResponse) {
234
301
  return res.json({ id: existingOrderId })
235
302
  }
236
303
  logger.info(
237
- `[paypal] create-order: stored order ${existingOrderId} is stale (status=${existingStatus}, amount=${existingAmount?.value} ${existingAmount?.currency_code} vs cart ${value} ${currency}) — creating a fresh order (request_id=${requestId})`
304
+ `[paypal] create-order: stored order ${existingOrderId} is stale (status=${existingStatus}, amount=${existingAmount?.value} ${existingAmount?.currency_code} vs cart ${value} ${currency}, shipping_matches=${shippingMatches}) — creating a fresh order (request_id=${requestId})`
238
305
  )
239
306
  } else if (checkResp.status !== 404) {
240
307
  // Transient PayPal-side failure: reuse rather than block checkout.
@@ -257,18 +324,7 @@ export async function POST(req: MedusaRequest, res: MedusaResponse) {
257
324
  typeof additionalSettings.brandName === "string"
258
325
  ? additionalSettings.brandName
259
326
  : undefined
260
- const landingPageRaw =
261
- typeof additionalSettings.landingPage === "string"
262
- ? additionalSettings.landingPage
263
- : undefined
264
- const landingPage =
265
- landingPageRaw === "login"
266
- ? "LOGIN"
267
- : landingPageRaw === "billing"
268
- ? "BILLING"
269
- : landingPageRaw === "no_preference"
270
- ? "NO_PREFERENCE"
271
- : undefined
327
+ const landingPage = resolveLandingPage(additionalSettings.landingPage)
272
328
  const requireInstantPayment =
273
329
  typeof additionalSettings.requireInstantPayment === "boolean"
274
330
  ? additionalSettings.requireInstantPayment
@@ -314,13 +370,13 @@ export async function POST(req: MedusaRequest, res: MedusaResponse) {
314
370
  // PayPal deprecated the order-level application_context: the checkout
315
371
  // experience now rides on payment_source.paypal.experience_context (and
316
372
  // payment_source.card.experience_context for the 3DS redirect URLs).
317
- // landing_page LOGIN and user_action PAY_NOW are the partner-recommended
318
- // defaults; the admin landingPage setting still overrides.
373
+ // landing_page LOGIN and user_action PAY_NOW are what PayPal's partner
374
+ // review asks for; the admin can still pick the guest checkout page.
319
375
  const experienceContext: Record<string, any> = {
320
376
  ...(resolvedBrandName
321
377
  ? { brand_name: resolvedBrandName.slice(0, 127) }
322
378
  : {}),
323
- landing_page: landingPage ?? "LOGIN",
379
+ landing_page: landingPage,
324
380
  user_action: "PAY_NOW",
325
381
  ...(requireInstantPayment
326
382
  ? { payment_method_preference: "IMMEDIATE_PAYMENT_REQUIRED" }
@@ -496,155 +552,118 @@ export async function POST(req: MedusaRequest, res: MedusaResponse) {
496
552
  `[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}`
497
553
  )
498
554
 
499
- // Opt-in: attach the cart's shipping address to the PayPal order
500
- // (`SET_PROVIDED_ADDRESS`). Improves PayPal Seller Protection eligibility —
501
- // PayPal only protects shipments to the address on the order. Deliberately
502
- // a SEPARATE query: adding relation fields to the totals query above has
503
- // broken the totals decorator before (see the shipping_methods warning).
504
- const sendShippingAddress =
505
- additionalSettings.sendShippingAddress === true ||
506
- String(process.env.PAYPAL_SEND_SHIPPING_ADDRESS || "")
507
- .trim()
508
- .toLowerCase() === "true"
509
- let paypalShipping: Record<string, any> | null = null
510
- if (sendShippingAddress && !isCardPayment) {
511
- try {
512
- const { data: addrData } = await query.graph({
513
- entity: "cart",
514
- fields: [
515
- "id",
516
- "shipping_address.first_name",
517
- "shipping_address.last_name",
518
- "shipping_address.address_1",
519
- "shipping_address.address_2",
520
- "shipping_address.city",
521
- "shipping_address.province",
522
- "shipping_address.postal_code",
523
- "shipping_address.country_code",
524
- ],
525
- filters: { id: cartId },
526
- })
527
- const addr = (addrData?.[0] as any)?.shipping_address
528
- const line1 = String(addr?.address_1 || "").trim()
529
- const postal = String(addr?.postal_code || "").trim()
530
- const country = String(addr?.country_code || "")
531
- .trim()
532
- .toUpperCase()
533
- // PayPal rejects incomplete addresses — only send a usable one.
534
- if (addr && line1 && postal && country.length === 2) {
535
- const fullName = [addr.first_name, addr.last_name]
536
- .map((part: unknown) => String(part || "").trim())
537
- .filter(Boolean)
538
- .join(" ")
539
- paypalShipping = {
540
- ...(fullName
541
- ? { name: { full_name: fullName.slice(0, 300) } }
542
- : {}),
543
- address: {
544
- address_line_1: line1.slice(0, 300),
545
- ...(addr.address_2
546
- ? { address_line_2: String(addr.address_2).slice(0, 300) }
547
- : {}),
548
- ...(addr.city
549
- ? { admin_area_2: String(addr.city).slice(0, 120) }
550
- : {}),
551
- ...(addr.province
552
- ? { admin_area_1: String(addr.province).slice(0, 300) }
553
- : {}),
554
- postal_code: postal.slice(0, 60),
555
- country_code: country,
556
- },
557
- }
558
- experienceContext.shipping_preference = "SET_PROVIDED_ADDRESS"
559
- }
560
- } catch (e: unknown) {
561
- // Seller protection is an optimization, never a checkout blocker.
562
- logger.warn(
563
- `[paypal] create-order: could not attach shipping address (request_id=${requestId}): ${
564
- e instanceof Error ? e.message : String(e)
565
- }`
566
- )
567
- }
568
- }
569
-
570
555
  // Use the module's cached app access token (single-flight refresh, ~9h TTL)
571
556
  // instead of minting a fresh OAuth token on every create-order call.
572
557
  const base = getPayPalApiBase(creds.environment)
573
558
  const accessToken = await paypal.getAppAccessToken()
574
559
 
575
- // Deterministic-per-(cart, amount, currency) idempotency key for the PayPal
576
- // call. The amount/currency MUST be part of the key: PayPal replays the
577
- // cached response for a reused PayPal-Request-Id, so a key derived from the
578
- // cart id alone would return the ORIGINAL order (at the original total)
579
- // when the buyer changes the cart and a fresh order is minted — silently
580
- // re-charging the stale amount and defeating the staleness check above.
581
- // Kept distinct from `requestId` (the log/response correlation id declared
582
- // at the top of POST) so the two never shadow each other.
583
- const paypalRequestId = resolveIdempotencyKey(
584
- req,
585
- `create-order-${cart.id}-${value}-${currency}`,
586
- `pp-create-${cart.id}-${value}-${currency}`
587
- )
560
+ // Deterministic-per-(cart, amount, currency, address) idempotency key for
561
+ // the PayPal call. The amount/currency MUST be part of the key: PayPal
562
+ // replays the cached response for a reused PayPal-Request-Id, so a key
563
+ // derived from the cart id alone would return the ORIGINAL order (at the
564
+ // original total) when the buyer changes the cart and a fresh order is
565
+ // minted — silently re-charging the stale amount and defeating the
566
+ // staleness check above. The same goes for the shipping address now that
567
+ // it is part of the order. Kept distinct from `requestId` (the
568
+ // log/response correlation id declared at the top of POST) so the two
569
+ // never shadow each other.
570
+ const buildRequestId = (shipping: PayPalShipping | null) => {
571
+ const shippingKey = shipping ? `-${shippingFingerprint(shipping)}` : ""
572
+ return resolveIdempotencyKey(
573
+ req,
574
+ `create-order-${cart.id}-${value}-${currency}${shippingKey}`,
575
+ `pp-create-${cart.id}-${value}-${currency}${shippingKey}`
576
+ )
577
+ }
588
578
 
589
- const ppResp = await paypalFetch(`${base}/v2/checkout/orders`, {
590
- method: "POST",
591
- headers: {
592
- Authorization: `Bearer ${accessToken}`,
593
- "Content-Type": "application/json",
594
- "PayPal-Request-Id": paypalRequestId,
595
- "PayPal-Partner-Attribution-Id": BN_CODE,
596
- },
597
- body: JSON.stringify({
598
- intent: paymentAction,
599
- purchase_units: [
600
- {
601
- reference_id: "default",
602
- // Set custom_id on the purchase unit (not just the order) so PayPal
603
- // propagates the cart id onto capture/refund webhook resources,
604
- // letting webhooks resolve the session directly without a scan.
605
- custom_id: cart.id,
606
- invoice_id: invoiceId,
607
- ...(statementName
608
- ? { soft_descriptor: statementName.slice(0, 22) }
609
- : {}),
610
- amount: {
611
- currency_code: currency,
612
- value,
613
- ...(Object.keys(breakdown).length > 0 ? { breakdown } : {}),
579
+ const sendCreateOrder = (shipping: PayPalShipping | null) =>
580
+ paypalFetch(`${base}/v2/checkout/orders`, {
581
+ method: "POST",
582
+ headers: {
583
+ Authorization: `Bearer ${accessToken}`,
584
+ "Content-Type": "application/json",
585
+ "PayPal-Request-Id": buildRequestId(shipping),
586
+ "PayPal-Partner-Attribution-Id": BN_CODE,
587
+ },
588
+ body: JSON.stringify({
589
+ intent: paymentAction,
590
+ purchase_units: [
591
+ {
592
+ reference_id: "default",
593
+ // custom_id belongs on the purchase unit (the order object has
594
+ // no such field): PayPal copies it onto capture/refund webhook
595
+ // resources, letting webhooks resolve the session directly
596
+ // without a scan.
597
+ custom_id: cart.id,
598
+ invoice_id: invoiceId,
599
+ ...(statementName
600
+ ? { soft_descriptor: statementName.slice(0, 22) }
601
+ : {}),
602
+ amount: {
603
+ currency_code: currency,
604
+ value,
605
+ ...(Object.keys(breakdown).length > 0 ? { breakdown } : {}),
606
+ },
607
+ ...(finalPurchaseItems.length > 0
608
+ ? { items: finalPurchaseItems }
609
+ : {}),
610
+ ...(shipping ? { shipping } : {}),
614
611
  },
615
- ...(finalPurchaseItems.length > 0
616
- ? { items: finalPurchaseItems }
617
- : {}),
618
- ...(paypalShipping ? { shipping: paypalShipping } : {}),
619
- },
620
- ],
621
- payment_source: isCardPayment
622
- ? {
623
- card: {
624
- ...(threeDsMethod
625
- ? {
626
- attributes: {
627
- verification: { method: threeDsMethod },
628
- },
629
- }
630
- : {}),
631
- // Card orders only take the 3DS redirect URLs here; the rest
632
- // of experience_context is a PayPal-wallet concept.
633
- experience_context: {
634
- ...(returnUrl ? { return_url: returnUrl } : {}),
635
- ...(cancelUrl ? { cancel_url: cancelUrl } : {}),
612
+ ],
613
+ payment_source: isCardPayment
614
+ ? {
615
+ card: {
616
+ ...(threeDsMethod
617
+ ? {
618
+ attributes: {
619
+ verification: { method: threeDsMethod },
620
+ },
621
+ }
622
+ : {}),
623
+ // Card orders only take the 3DS redirect URLs here; the rest
624
+ // of experience_context (shipping_preference included) is a
625
+ // PayPal-wallet concept.
626
+ experience_context: {
627
+ ...(returnUrl ? { return_url: returnUrl } : {}),
628
+ ...(cancelUrl ? { cancel_url: cancelUrl } : {}),
629
+ },
630
+ },
631
+ }
632
+ : {
633
+ paypal: {
634
+ experience_context: {
635
+ ...experienceContext,
636
+ ...(shipping
637
+ ? { shipping_preference: "SET_PROVIDED_ADDRESS" }
638
+ : {}),
639
+ },
636
640
  },
637
641
  },
638
- }
639
- : {
640
- paypal: { experience_context: experienceContext },
641
- },
642
- custom_id: cart.id,
643
- }),
644
- })
642
+ }),
643
+ })
645
644
 
646
- const ppText = await ppResp.text()
645
+ let ppResp = await sendCreateOrder(paypalShipping)
646
+ let ppText = await ppResp.text()
647
647
  debugId = ppResp.headers.get("paypal-debug-id")
648
+
649
+ // PayPal validates a provided address and rejects ones it cannot use. An
650
+ // address problem must not cost the sale: create the order without it and
651
+ // let the buyer pick an address in PayPal, as before 1.3.9.
652
+ if (
653
+ !ppResp.ok &&
654
+ paypalShipping &&
655
+ isShippingAddressRejection(ppResp.status, ppText)
656
+ ) {
657
+ logger.warn(
658
+ `[paypal] create-order: PayPal rejected the shipping address (debug_id=${
659
+ debugId ?? "n/a"
660
+ }, request_id=${requestId}) — retrying without it: ${ppText.slice(0, 500)}`
661
+ )
662
+ ppResp = await sendCreateOrder(null)
663
+ ppText = await ppResp.text()
664
+ debugId = ppResp.headers.get("paypal-debug-id")
665
+ }
666
+
648
667
  if (!ppResp.ok) {
649
668
  throw new Error(
650
669
  `PayPal create order error (${ppResp.status}): ${ppText}${