@easypayment/medusa-payment-paypal 1.3.1 → 1.3.3

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.
@@ -16,6 +16,7 @@ import {
16
16
  getStoredPayPalOrderId,
17
17
  updatePayPalSessionData,
18
18
  } from "../../../../modules/paypal/utils/payment-session"
19
+ import { resolveStorefrontUrl } from "../../../../modules/paypal/utils/storefront-url"
19
20
 
20
21
  type Body = {
21
22
  cart_id: string
@@ -74,24 +75,6 @@ async function getExistingPayPalOrderId(req: MedusaRequest, cartId: string) {
74
75
  return getStoredPayPalOrderId(session?.session_data)
75
76
  }
76
77
 
77
- /** Storefront return URL from env (`STOREFRONT_URL` / `STORE_URL`), if set. */
78
- function resolveReturnUrl() {
79
- const configured = process.env.STOREFRONT_URL || process.env.STORE_URL
80
- if (!configured) {
81
- return undefined
82
- }
83
- return `${configured.replace(/\/$/, "")}/checkout`
84
- }
85
-
86
- /** Storefront cancel URL from env (`STOREFRONT_URL` / `STORE_URL`), if set. */
87
- function resolveCancelUrl() {
88
- const configured = process.env.STOREFRONT_URL || process.env.STORE_URL
89
- if (!configured) {
90
- return undefined
91
- }
92
- return `${configured.replace(/\/$/, "")}/cart`
93
- }
94
-
95
78
  /**
96
79
  * POST /store/paypal/create-order — create (or reuse) the PayPal order for a
97
80
  * cart and store its id on the cart's PayPal payment session.
@@ -301,20 +284,44 @@ export async function POST(req: MedusaRequest, res: MedusaResponse) {
301
284
  : ""
302
285
  const cartIdSuffix = cart.id.slice(-12).toUpperCase()
303
286
  const invoiceId = `${invoicePrefix}${cartIdSuffix}`.trim() || cart.id
304
- const returnUrl =
305
- typeof apiDetails.storefront_url === "string" &&
306
- apiDetails.storefront_url.trim()
307
- ? `${apiDetails.storefront_url.replace(/\/$/, "")}/checkout`
308
- : resolveReturnUrl()
309
- const cancelUrl =
310
- typeof apiDetails.storefront_url === "string" &&
311
- apiDetails.storefront_url.trim()
312
- ? `${apiDetails.storefront_url.replace(/\/$/, "")}/cart`
313
- : resolveCancelUrl()
314
-
315
- const applicationContext: Record<string, any> = {
316
- ...(brandName ? { brand_name: brandName } : {}),
317
- ...(landingPage ? { landing_page: landingPage } : {}),
287
+ const storefrontUrl = resolveStorefrontUrl({
288
+ configured: apiDetails.storefront_url,
289
+ envUrl: process.env.STOREFRONT_URL || process.env.STORE_URL,
290
+ origin: req.headers.origin,
291
+ storeCors: req.scope.resolve(ContainerRegistrationKeys.CONFIG_MODULE)
292
+ .projectConfig.http.storeCors,
293
+ })
294
+ const returnUrl = storefrontUrl ? `${storefrontUrl}/checkout` : undefined
295
+ const cancelUrl = storefrontUrl ? `${storefrontUrl}/cart` : undefined
296
+
297
+ // brand_name should show the MERCHANT, not "PayPal": use the admin-set
298
+ // brand name, falling back to the store's own name (PayPal partner review,
299
+ // 2026-10-06).
300
+ let resolvedBrandName = brandName
301
+ if (!resolvedBrandName) {
302
+ try {
303
+ const { data: storeData } = await query.graph({
304
+ entity: "store",
305
+ fields: ["name"],
306
+ })
307
+ const storeName = String(storeData?.[0]?.name || "").trim()
308
+ if (storeName) resolvedBrandName = storeName
309
+ } catch {
310
+ // brand name is cosmetic — never block checkout on it
311
+ }
312
+ }
313
+
314
+ // PayPal deprecated the order-level application_context: the checkout
315
+ // experience now rides on payment_source.paypal.experience_context (and
316
+ // 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.
319
+ const experienceContext: Record<string, any> = {
320
+ ...(resolvedBrandName
321
+ ? { brand_name: resolvedBrandName.slice(0, 127) }
322
+ : {}),
323
+ landing_page: landingPage ?? "LOGIN",
324
+ user_action: "PAY_NOW",
318
325
  ...(requireInstantPayment
319
326
  ? { payment_method_preference: "IMMEDIATE_PAYMENT_REQUIRED" }
320
327
  : {}),
@@ -548,7 +555,7 @@ export async function POST(req: MedusaRequest, res: MedusaResponse) {
548
555
  country_code: country,
549
556
  },
550
557
  }
551
- applicationContext.shipping_preference = "SET_PROVIDED_ADDRESS"
558
+ experienceContext.shipping_preference = "SET_PROVIDED_ADDRESS"
552
559
  }
553
560
  } catch (e: unknown) {
554
561
  // Seller protection is an optimization, never a checkout blocker.
@@ -611,23 +618,28 @@ export async function POST(req: MedusaRequest, res: MedusaResponse) {
611
618
  ...(paypalShipping ? { shipping: paypalShipping } : {}),
612
619
  },
613
620
  ],
614
- ...(threeDsMethod
621
+ payment_source: isCardPayment
615
622
  ? {
616
- payment_source: {
617
- card: {
618
- attributes: {
619
- verification: {
620
- method: threeDsMethod,
621
- },
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 } : {}),
623
636
  },
624
637
  },
625
638
  }
626
- : {}),
639
+ : {
640
+ paypal: { experience_context: experienceContext },
641
+ },
627
642
  custom_id: cart.id,
628
- ...(Object.keys(applicationContext).length > 0
629
- ? { application_context: applicationContext }
630
- : {}),
631
643
  }),
632
644
  })
633
645
 
@@ -119,7 +119,9 @@ class PayPalModuleService extends MedusaService({
119
119
  onboarding.backend_url = this.cfg.backendUrl
120
120
  changed = true
121
121
  }
122
- if (!onboarding.seller_nonce) {
122
+ // Overwrite, not just fill: installs on 1.1.0–1.3.2 persisted a random
123
+ // nonce the partner service never saw, which breaks the token exchange.
124
+ if (onboarding.seller_nonce !== this.cfg.sellerNonce) {
123
125
  onboarding.seller_nonce = this.cfg.sellerNonce
124
126
  changed = true
125
127
  }
@@ -1,6 +1,17 @@
1
- import { randomBytes } from "crypto"
2
1
  import { PAYPAL_PARTNER_ATTRIBUTION_ID } from "../utils/partner"
3
2
 
3
+ /**
4
+ * The seller nonce the hosted partner service (`partnerServiceUrl`) embeds in
5
+ * every partner-referral it creates. The onboarding token exchange sends it as
6
+ * the PKCE `code_verifier`, so it MUST equal the value the referral was minted
7
+ * with — the link request does not send a nonce, so a locally generated one
8
+ * makes every exchange fail with invalid_grant. It is not a secret: the
9
+ * single-use authCode and sharedId are what protect the exchange.
10
+ * Only override PAYPAL_SELLER_NONCE together with your own partner service.
11
+ */
12
+ export const PARTNER_SELLER_NONCE =
13
+ "a1233wtergfsdt4365tzrshgfbaewa36AGa1233wtergfsdt4365tzrshgfbaewa36AG"
14
+
4
15
  /** Partner-level configuration, resolved from env vars with built-in defaults. */
5
16
  export type PayPalModuleConfig = {
6
17
  partnerServiceUrl: string
@@ -19,33 +30,13 @@ const STATIC_CFG: PayPalModuleConfig = {
19
30
  partnerJsUrl:
20
31
  "https://www.paypal.com/webapps/merchantboarding/js/lib/lightbox/partner.js",
21
32
  backendUrl: "http://localhost:9000",
22
- sellerNonce: "",
33
+ sellerNonce: PARTNER_SELLER_NONCE,
23
34
  bnCode: PAYPAL_PARTNER_ATTRIBUTION_ID,
24
35
  partnerMerchantIdSandbox: "K6QLN2LPGQRHL",
25
36
  partnerMerchantIdLive: "GT5R877JNBPLL",
26
37
  alertWebhookUrls: [],
27
38
  }
28
39
 
29
- let warnedGeneratedNonce = false
30
-
31
- function generateSellerNonce(): string {
32
- // The nonce doubles as the OAuth code_verifier for the onboarding exchange,
33
- // so every instance must agree on it. It is persisted into settings on first
34
- // boot, but two instances booting simultaneously can race to persist
35
- // different generated values — an onboarding link minted against the losing
36
- // nonce then fails its token exchange with an opaque invalid_grant. Pinning
37
- // PAYPAL_SELLER_NONCE removes the race entirely.
38
- if (!warnedGeneratedNonce) {
39
- warnedGeneratedNonce = true
40
- console.warn(
41
- "[PayPal] PAYPAL_SELLER_NONCE is not set — generating a random seller nonce. " +
42
- "For multi-instance deployments, set PAYPAL_SELLER_NONCE to a fixed random string " +
43
- "so all instances share the same onboarding code_verifier."
44
- )
45
- }
46
- return randomBytes(32).toString("hex")
47
- }
48
-
49
40
  /** Resolve the module configuration from the environment. */
50
41
  export function getPayPalConfig(): PayPalModuleConfig {
51
42
  const backendUrl = process.env.MEDUSA_BACKEND_URL || STATIC_CFG.backendUrl
@@ -55,7 +46,7 @@ export function getPayPalConfig(): PayPalModuleConfig {
55
46
  partnerServiceUrl:
56
47
  process.env.PAYPAL_PARTNER_SERVICE_URL || STATIC_CFG.partnerServiceUrl,
57
48
  backendUrl,
58
- sellerNonce: process.env.PAYPAL_SELLER_NONCE || generateSellerNonce(),
49
+ sellerNonce: process.env.PAYPAL_SELLER_NONCE || STATIC_CFG.sellerNonce,
59
50
  partnerMerchantIdSandbox:
60
51
  process.env.PAYPAL_PARTNER_MERCHANT_ID_SANDBOX ||
61
52
  STATIC_CFG.partnerMerchantIdSandbox,
@@ -0,0 +1,41 @@
1
+ type ResolveStorefrontUrlInput = {
2
+ /** `api_details.storefront_url` from the admin settings. */
3
+ configured?: unknown
4
+ /** `STOREFRONT_URL` / `STORE_URL`. */
5
+ envUrl?: unknown
6
+ /** The request's `Origin` header. */
7
+ origin?: unknown
8
+ /** `projectConfig.http.storeCors`: a comma-separated list of origins. */
9
+ storeCors?: unknown
10
+ }
11
+
12
+ const clean = (value: unknown) =>
13
+ typeof value === "string" ? value.trim().replace(/\/+$/, "") : ""
14
+
15
+ /**
16
+ * The storefront base URL used for PayPal's return/cancel URLs: admin setting,
17
+ * then env, then the request's Origin.
18
+ *
19
+ * The Origin header is caller-controlled, and the result becomes a redirect
20
+ * target, so it only counts when it exactly matches a STORE_CORS entry. Wildcard
21
+ * and regex entries never match, which leaves the URL unset rather than trusted.
22
+ */
23
+ export function resolveStorefrontUrl({
24
+ configured,
25
+ envUrl,
26
+ origin,
27
+ storeCors,
28
+ }: ResolveStorefrontUrlInput): string | undefined {
29
+ const explicit = clean(configured) || clean(envUrl)
30
+ if (explicit) {
31
+ return explicit
32
+ }
33
+
34
+ const requestOrigin = clean(origin)
35
+ if (!requestOrigin || typeof storeCors !== "string") {
36
+ return undefined
37
+ }
38
+
39
+ const allowed = storeCors.split(",").map(clean)
40
+ return allowed.includes(requestOrigin) ? requestOrigin : undefined
41
+ }