@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
@@ -1,7 +1,7 @@
1
1
  import { jsx, jsxs, Fragment } from "react/jsx-runtime";
2
2
  import { defineRouteConfig } from "@medusajs/admin-sdk";
3
3
  import { Navigate, useLocation, Link } from "react-router-dom";
4
- import { useEffect, useState, useRef, useCallback, useMemo, useLayoutEffect } from "react";
4
+ import React, { useEffect, useState, useRef, useCallback, useMemo, useLayoutEffect } from "react";
5
5
  const config$1 = defineRouteConfig({
6
6
  label: "PayPal"
7
7
  });
@@ -156,9 +156,10 @@ async function adminFetch(path, opts = {}) {
156
156
  const DEFAULT_FORM$1 = {
157
157
  paymentAction: "capture",
158
158
  brandName: "PayPal",
159
- landingPage: "no_preference",
159
+ landingPage: "login",
160
160
  requireInstantPayment: false,
161
161
  sendItemDetails: true,
162
+ sendShippingAddress: true,
162
163
  invoicePrefix: "PP-",
163
164
  creditCardStatementName: "PayPal",
164
165
  debugLogging: false
@@ -168,10 +169,12 @@ function mergeWithDefaults$1(saved) {
168
169
  const entries = Object.entries(saved).filter(
169
170
  ([, value]) => value !== void 0
170
171
  );
171
- return {
172
+ const merged = {
172
173
  ...DEFAULT_FORM$1,
173
174
  ...Object.fromEntries(entries)
174
175
  };
176
+ if (merged.landingPage !== "billing") merged.landingPage = "login";
177
+ return merged;
175
178
  }
176
179
  function AdditionalSettingsTab() {
177
180
  const [form, setForm] = useState(() => ({
@@ -326,9 +329,8 @@ function AdditionalSettingsTab() {
326
329
  })),
327
330
  className: "w-full rounded-md border border-ui-border-base bg-ui-bg-base px-3 py-2 text-sm text-ui-fg-base outline-none focus:ring-2 focus:ring-ui-border-interactive",
328
331
  children: [
329
- /* @__PURE__ */ jsx("option", { value: "no_preference", children: "No Preference" }),
330
- /* @__PURE__ */ jsx("option", { value: "login", children: "Login" }),
331
- /* @__PURE__ */ jsx("option", { value: "billing", children: "Billing" })
332
+ /* @__PURE__ */ jsx("option", { value: "login", children: "Login (PayPal account)" }),
333
+ /* @__PURE__ */ jsx("option", { value: "billing", children: "Guest checkout (card form)" })
332
334
  ]
333
335
  }
334
336
  ) }),
@@ -369,6 +371,28 @@ function AdditionalSettingsTab() {
369
371
  ] })
370
372
  }
371
373
  ),
374
+ /* @__PURE__ */ jsx(
375
+ FieldRow,
376
+ {
377
+ label: "Send Shipping Address",
378
+ hint: "Send the shipping address the customer entered at checkout to PayPal, so PayPal shows that address instead of the ones saved on the customer's PayPal account. Needed for PayPal Seller Protection.",
379
+ children: /* @__PURE__ */ jsxs("label", { className: "inline-flex items-center gap-2", children: [
380
+ /* @__PURE__ */ jsx(
381
+ "input",
382
+ {
383
+ type: "checkbox",
384
+ checked: form.sendShippingAddress,
385
+ onChange: (e) => setForm((p) => ({
386
+ ...p,
387
+ sendShippingAddress: e.target.checked
388
+ })),
389
+ className: "h-4 w-4 rounded border-ui-border-base"
390
+ }
391
+ ),
392
+ /* @__PURE__ */ jsx("span", { className: "text-sm text-ui-fg-base", children: "Send the checkout shipping address to PayPal" })
393
+ ] })
394
+ }
395
+ ),
372
396
  /* @__PURE__ */ jsx(FieldRow, { label: "Invoice prefix", htmlFor: "as-invoice-prefix", children: /* @__PURE__ */ jsx(
373
397
  "input",
374
398
  {
@@ -443,6 +467,68 @@ function AdditionalSettingsTab() {
443
467
  )
444
468
  ] }) });
445
469
  }
470
+ const URL_RE = /(https?:\/\/[^\s]+[^\s.,!?])/g;
471
+ function NoticeText({ message }) {
472
+ const parts = message.split(URL_RE);
473
+ return /* @__PURE__ */ jsx(Fragment, { children: parts.map(
474
+ (part, i) => /^https?:\/\//.test(part) ? /* @__PURE__ */ jsx(
475
+ "a",
476
+ {
477
+ href: part,
478
+ target: "_blank",
479
+ rel: "noopener noreferrer",
480
+ className: "underline",
481
+ children: part
482
+ },
483
+ i
484
+ ) : /* @__PURE__ */ jsx(React.Fragment, { children: part }, i)
485
+ ) });
486
+ }
487
+ function MerchantStatusNotices({
488
+ environment,
489
+ only,
490
+ reloadKey
491
+ }) {
492
+ const [notices, setNotices] = useState([]);
493
+ useEffect(() => {
494
+ let cancelled = false;
495
+ setNotices([]);
496
+ (async () => {
497
+ try {
498
+ const json = await adminFetch(
499
+ "/admin/paypal/merchant-status",
500
+ environment ? { query: { environment } } : {}
501
+ );
502
+ if (cancelled) return;
503
+ setNotices(Array.isArray(json == null ? void 0 : json.notices) ? json.notices : []);
504
+ } catch {
505
+ }
506
+ })();
507
+ return () => {
508
+ cancelled = true;
509
+ };
510
+ }, [environment, reloadKey]);
511
+ const visible = only ? notices.filter((notice) => only.includes(notice.code)) : notices;
512
+ if (visible.length === 0) return null;
513
+ return /* @__PURE__ */ jsx("div", { className: "flex flex-col gap-2", "data-testid": "paypal-merchant-notices", children: visible.map((notice) => /* @__PURE__ */ jsx(
514
+ "div",
515
+ {
516
+ role: "alert",
517
+ className: "rounded border p-3 text-sm",
518
+ style: notice.level === "error" ? {
519
+ background: "#fef2f2",
520
+ borderColor: "#fecaca",
521
+ color: "#b91c1c"
522
+ } : {
523
+ background: "#fffbeb",
524
+ borderColor: "#fde68a",
525
+ color: "#92400e"
526
+ },
527
+ children: /* @__PURE__ */ jsx(NoticeText, { message: notice.message })
528
+ },
529
+ notice.code
530
+ )) });
531
+ }
446
532
  const DEFAULT_FORM = {
447
533
  enabled: true,
448
534
  title: "Credit or Debit Card",
@@ -528,6 +614,7 @@ function AdvancedCardPaymentsTab() {
528
614
  /* @__PURE__ */ jsx("div", { className: "flex items-start justify-between gap-4", children: /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx("h1", { className: "text-xl font-semibold text-ui-fg-base", children: "PayPal Gateway By Easy Payment" }) }) }),
529
615
  /* @__PURE__ */ jsx(PayPalTabs, {}),
530
616
  /* @__PURE__ */ jsx(Toast, { toast, onClose: dismissToast }),
617
+ /* @__PURE__ */ jsx(MerchantStatusNotices, { only: ["card_payments_not_enabled"] }),
531
618
  /* @__PURE__ */ jsx(
532
619
  SectionCard,
533
620
  {
@@ -598,9 +685,6 @@ function AdvancedCardPaymentsTab() {
598
685
  )
599
686
  ] }) });
600
687
  }
601
- function PayPalGooglePayPage() {
602
- return /* @__PURE__ */ jsx(Navigate, { to: "/settings/paypal/connection", replace: true });
603
- }
604
688
  function PayPalApplePayPage() {
605
689
  return /* @__PURE__ */ jsx(Navigate, { to: "/settings/paypal/connection", replace: true });
606
690
  }
@@ -1158,6 +1242,13 @@ function PayPalConnectionPage() {
1158
1242
  }
1159
1243
  )
1160
1244
  ] }),
1245
+ /* @__PURE__ */ jsx("div", { className: "mt-3", children: /* @__PURE__ */ jsx(
1246
+ MerchantStatusNotices,
1247
+ {
1248
+ environment: env,
1249
+ reloadKey: (statusInfo == null ? void 0 : statusInfo.seller_client_id_masked) || ""
1250
+ }
1251
+ ) }),
1161
1252
  /* @__PURE__ */ jsxs("div", { className: "mt-3 rounded-md border border-ui-border-base bg-ui-bg-subtle p-3 text-xs text-ui-fg-subtle", children: [
1162
1253
  /* @__PURE__ */ jsx("div", { className: "font-medium text-ui-fg-base", children: "Connected PayPal account" }),
1163
1254
  /* @__PURE__ */ jsxs("div", { className: "mt-1", children: [
@@ -1399,7 +1490,7 @@ function PayPalConnectionPage() {
1399
1490
  ` })
1400
1491
  ] });
1401
1492
  }
1402
- function PayPalPayLaterMessagingPage() {
1493
+ function PayPalGooglePayPage() {
1403
1494
  return /* @__PURE__ */ jsx(Navigate, { to: "/settings/paypal/connection", replace: true });
1404
1495
  }
1405
1496
  const COLOR_OPTIONS = [
@@ -1618,6 +1709,9 @@ function PayPalSettingsTab() {
1618
1709
  )
1619
1710
  ] }) });
1620
1711
  }
1712
+ function PayPalPayLaterMessagingPage() {
1713
+ return /* @__PURE__ */ jsx(Navigate, { to: "/settings/paypal/connection", replace: true });
1714
+ }
1621
1715
  const widgetModule = { widgets: [] };
1622
1716
  const routeModule = {
1623
1717
  routes: [
@@ -1633,10 +1727,6 @@ const routeModule = {
1633
1727
  Component: AdvancedCardPaymentsTab,
1634
1728
  path: "/settings/paypal/advanced-card-payments"
1635
1729
  },
1636
- {
1637
- Component: PayPalGooglePayPage,
1638
- path: "/settings/paypal/google-pay"
1639
- },
1640
1730
  {
1641
1731
  Component: PayPalApplePayPage,
1642
1732
  path: "/settings/paypal/apple-pay"
@@ -1646,12 +1736,16 @@ const routeModule = {
1646
1736
  path: "/settings/paypal/connection"
1647
1737
  },
1648
1738
  {
1649
- Component: PayPalPayLaterMessagingPage,
1650
- path: "/settings/paypal/pay-later-messaging"
1739
+ Component: PayPalGooglePayPage,
1740
+ path: "/settings/paypal/google-pay"
1651
1741
  },
1652
1742
  {
1653
1743
  Component: PayPalSettingsTab,
1654
1744
  path: "/settings/paypal/paypal-settings"
1745
+ },
1746
+ {
1747
+ Component: PayPalPayLaterMessagingPage,
1748
+ path: "/settings/paypal/pay-later-messaging"
1655
1749
  }
1656
1750
  ]
1657
1751
  };
@@ -0,0 +1,11 @@
1
+ import type { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
2
+ /**
3
+ * GET /admin/paypal/merchant-status[?environment=sandbox|live][&refresh=1]
4
+ *
5
+ * Whether the connected seller can receive payments, per PayPal's seller
6
+ * onboarding status: confirmed email, payments receivable, PayPal payments and
7
+ * Advanced Card payments — plus the notices to show the merchant when a check
8
+ * fails. Cached for a few minutes; `refresh=1` forces a new lookup.
9
+ */
10
+ export declare function GET(req: MedusaRequest, res: MedusaResponse): Promise<MedusaResponse>;
11
+ //# sourceMappingURL=route.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"route.d.ts","sourceRoot":"","sources":["../../../../../../../src/api/admin/paypal/merchant-status/route.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAA;AAG7E;;;;;;;GAOG;AACH,wBAAsB,GAAG,CAAC,GAAG,EAAE,aAAa,EAAE,GAAG,EAAE,cAAc,2BAwBhE"}
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GET = GET;
4
+ /**
5
+ * GET /admin/paypal/merchant-status[?environment=sandbox|live][&refresh=1]
6
+ *
7
+ * Whether the connected seller can receive payments, per PayPal's seller
8
+ * onboarding status: confirmed email, payments receivable, PayPal payments and
9
+ * Advanced Card payments — plus the notices to show the merchant when a check
10
+ * fails. Cached for a few minutes; `refresh=1` forces a new lookup.
11
+ */
12
+ async function GET(req, res) {
13
+ try {
14
+ const paypal = req.scope.resolve("paypal_onboarding");
15
+ const q = (req.query || {});
16
+ const envParam = (q.environment || q.env);
17
+ const env = envParam === "live"
18
+ ? "live"
19
+ : envParam === "sandbox"
20
+ ? "sandbox"
21
+ : undefined;
22
+ const refresh = q.refresh === "1" || q.refresh === "true";
23
+ return res.json(await paypal.getMerchantStatus(env, { refresh }));
24
+ }
25
+ catch (e) {
26
+ console.error("[PayPal] merchant-status GET failed:", e instanceof Error ? e.message : e);
27
+ return res
28
+ .status(500)
29
+ .json({ message: "Failed to retrieve PayPal seller status" });
30
+ }
31
+ }
32
+ //# sourceMappingURL=route.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"route.js","sourceRoot":"","sources":["../../../../../../../src/api/admin/paypal/merchant-status/route.ts"],"names":[],"mappings":";;AAWA,kBAwBC;AAhCD;;;;;;;GAOG;AACI,KAAK,UAAU,GAAG,CAAC,GAAkB,EAAE,GAAmB;IAC/D,IAAI,CAAC;QACH,MAAM,MAAM,GAAG,GAAG,CAAC,KAAK,CAAC,OAAO,CAAsB,mBAAmB,CAAC,CAAA;QAE1E,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,KAAK,IAAI,EAAE,CAAwB,CAAA;QAClD,MAAM,QAAQ,GAAG,CAAC,CAAC,CAAC,WAAW,IAAI,CAAC,CAAC,GAAG,CAAuB,CAAA;QAC/D,MAAM,GAAG,GACP,QAAQ,KAAK,MAAM;YACjB,CAAC,CAAC,MAAM;YACR,CAAC,CAAC,QAAQ,KAAK,SAAS;gBACtB,CAAC,CAAC,SAAS;gBACX,CAAC,CAAC,SAAS,CAAA;QACjB,MAAM,OAAO,GAAG,CAAC,CAAC,OAAO,KAAK,GAAG,IAAI,CAAC,CAAC,OAAO,KAAK,MAAM,CAAA;QAEzD,OAAO,GAAG,CAAC,IAAI,CAAC,MAAM,MAAM,CAAC,iBAAiB,CAAC,GAAG,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC,CAAA;IACnE,CAAC;IAAC,OAAO,CAAU,EAAE,CAAC;QACpB,OAAO,CAAC,KAAK,CACX,sCAAsC,EACtC,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CACnC,CAAA;QACD,OAAO,GAAG;aACP,MAAM,CAAC,GAAG,CAAC;aACX,IAAI,CAAC,EAAE,OAAO,EAAE,yCAAyC,EAAE,CAAC,CAAA;IACjE,CAAC;AACH,CAAC"}
@@ -5,7 +5,10 @@ import type { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
5
5
  *
6
6
  * Returns `{ id }` — the PayPal order id the storefront hands to the JS SDK.
7
7
  * Line items and an amount breakdown are sent when `sendItemDetails` is on,
8
- * with rounding drift reconciled so PayPal's strict total checks pass.
8
+ * with rounding drift reconciled so PayPal's strict total checks pass. The
9
+ * shipping address the buyer entered at checkout is sent with
10
+ * `shipping_preference: SET_PROVIDED_ADDRESS` unless `sendShippingAddress` is
11
+ * turned off.
9
12
  */
10
13
  export declare function POST(req: MedusaRequest, res: MedusaResponse): Promise<MedusaResponse>;
11
14
  //# sourceMappingURL=route.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"route.d.ts","sourceRoot":"","sources":["../../../../../../../src/api/store/paypal/create-order/route.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAA;AA6E7E;;;;;;;GAOG;AACH,wBAAsB,IAAI,CAAC,GAAG,EAAE,aAAa,EAAE,GAAG,EAAE,cAAc,2BAimBjE"}
1
+ {"version":3,"file":"route.d.ts","sourceRoot":"","sources":["../../../../../../../src/api/store/paypal/create-order/route.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAA;AAqF7E;;;;;;;;;;GAUG;AACH,wBAAsB,IAAI,CAAC,GAAG,EAAE,aAAa,EAAE,GAAG,EAAE,cAAc,2BAymBjE"}
@@ -10,6 +10,7 @@ const partner_1 = require("../../../../modules/paypal/utils/partner");
10
10
  const paypal_fetch_1 = require("../../../../modules/paypal/utils/paypal-fetch");
11
11
  const payment_session_1 = require("../../../../modules/paypal/utils/payment-session");
12
12
  const storefront_url_1 = require("../../../../modules/paypal/utils/storefront-url");
13
+ const order_context_1 = require("../../../../modules/paypal/utils/order-context");
13
14
  function resolveIdempotencyKey(req, suffix, fallback) {
14
15
  const header = req.headers["idempotency-key"] ||
15
16
  req.headers["Idempotency-Key"] ||
@@ -52,7 +53,10 @@ async function getExistingPayPalOrderId(req, cartId) {
52
53
  *
53
54
  * Returns `{ id }` — the PayPal order id the storefront hands to the JS SDK.
54
55
  * Line items and an amount breakdown are sent when `sendItemDetails` is on,
55
- * with rounding drift reconciled so PayPal's strict total checks pass.
56
+ * with rounding drift reconciled so PayPal's strict total checks pass. The
57
+ * shipping address the buyer entered at checkout is sent with
58
+ * `shipping_preference: SET_PROVIDED_ADDRESS` unless `sendShippingAddress` is
59
+ * turned off.
56
60
  */
57
61
  async function POST(req, res) {
58
62
  const paypal = req.scope.resolve("paypal_onboarding");
@@ -136,8 +140,49 @@ async function POST(req, res) {
136
140
  const exponent = (0, amounts_1.getCurrencyExponent)(currency);
137
141
  const totalMajor = Number(cart.total || 0);
138
142
  const value = totalMajor.toFixed(exponent);
143
+ // The buyer enters the shipping address in the storefront before paying, so
144
+ // it is sent with the order (`shipping_preference: SET_PROVIDED_ADDRESS`)
145
+ // and PayPal shows it as fixed instead of offering the addresses on the
146
+ // buyer's PayPal account. Required by PayPal's partner review, and PayPal
147
+ // only applies Seller Protection to the address on the order. On by
148
+ // default; `sendShippingAddress: false` (or
149
+ // PAYPAL_SEND_SHIPPING_ADDRESS=false) turns it off. Deliberately a
150
+ // SEPARATE query: adding relation fields to the totals query above has
151
+ // broken the totals decorator before (see the shipping_methods warning).
152
+ const sendShippingAddress = additionalSettings.sendShippingAddress !== false &&
153
+ String(process.env.PAYPAL_SEND_SHIPPING_ADDRESS || "")
154
+ .trim()
155
+ .toLowerCase() !== "false";
156
+ let paypalShipping = null;
157
+ if (sendShippingAddress) {
158
+ try {
159
+ const { data: addrData } = await query.graph({
160
+ entity: "cart",
161
+ fields: [
162
+ "id",
163
+ "shipping_address.first_name",
164
+ "shipping_address.last_name",
165
+ "shipping_address.address_1",
166
+ "shipping_address.address_2",
167
+ "shipping_address.city",
168
+ "shipping_address.province",
169
+ "shipping_address.postal_code",
170
+ "shipping_address.country_code",
171
+ ],
172
+ filters: { id: cartId },
173
+ });
174
+ // Null for a cart without a complete address (e.g. digital goods):
175
+ // PayPal rejects incomplete addresses, so none is sent then.
176
+ paypalShipping = (0, order_context_1.buildPayPalShipping)(addrData?.[0]?.shipping_address);
177
+ }
178
+ catch (e) {
179
+ // The address is an addition to the order, never a checkout blocker.
180
+ logger.warn(`[paypal] create-order: could not read the shipping address (request_id=${requestId}): ${e instanceof Error ? e.message : String(e)}`);
181
+ }
182
+ }
139
183
  // Reuse the stored PayPal order only when it still matches the cart: same
140
- // amount, same currency, and still in a reusable (pre-terminal) state. On
184
+ // amount, same currency, same shipping address, and still in a reusable
185
+ // (pre-terminal) state. On
141
186
  // mismatch fall through and create a fresh order (which replaces the
142
187
  // stored id on the session). If PayPal can't be reached for the check,
143
188
  // reuse the stored id — matching the previous behavior rather than
@@ -165,14 +210,18 @@ async function POST(req, res) {
165
210
  const amountMatches = String(existingAmount?.value || "") === value &&
166
211
  String(existingAmount?.currency_code || "").toUpperCase() ===
167
212
  currency;
168
- if (reusableStatus && amountMatches) {
213
+ // An order created for a previous address would show (and protect)
214
+ // the wrong destination, so it is replaced when the address changed.
215
+ const shippingMatches = !paypalShipping ||
216
+ (0, order_context_1.sameShipping)(existingOrder?.purchase_units?.[0]?.shipping, paypalShipping);
217
+ if (reusableStatus && amountMatches && shippingMatches) {
169
218
  return res.json({ id: existingOrderId });
170
219
  }
171
220
  if (existingStatus === "COMPLETED") {
172
221
  // Already paid — never mint a second order for this cart.
173
222
  return res.json({ id: existingOrderId });
174
223
  }
175
- logger.info(`[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})`);
224
+ logger.info(`[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})`);
176
225
  }
177
226
  else if (checkResp.status !== 404) {
178
227
  // Transient PayPal-side failure: reuse rather than block checkout.
@@ -192,16 +241,7 @@ async function POST(req, res) {
192
241
  const brandName = typeof additionalSettings.brandName === "string"
193
242
  ? additionalSettings.brandName
194
243
  : undefined;
195
- const landingPageRaw = typeof additionalSettings.landingPage === "string"
196
- ? additionalSettings.landingPage
197
- : undefined;
198
- const landingPage = landingPageRaw === "login"
199
- ? "LOGIN"
200
- : landingPageRaw === "billing"
201
- ? "BILLING"
202
- : landingPageRaw === "no_preference"
203
- ? "NO_PREFERENCE"
204
- : undefined;
244
+ const landingPage = (0, order_context_1.resolveLandingPage)(additionalSettings.landingPage);
205
245
  const requireInstantPayment = typeof additionalSettings.requireInstantPayment === "boolean"
206
246
  ? additionalSettings.requireInstantPayment
207
247
  : undefined;
@@ -244,13 +284,13 @@ async function POST(req, res) {
244
284
  // PayPal deprecated the order-level application_context: the checkout
245
285
  // experience now rides on payment_source.paypal.experience_context (and
246
286
  // payment_source.card.experience_context for the 3DS redirect URLs).
247
- // landing_page LOGIN and user_action PAY_NOW are the partner-recommended
248
- // defaults; the admin landingPage setting still overrides.
287
+ // landing_page LOGIN and user_action PAY_NOW are what PayPal's partner
288
+ // review asks for; the admin can still pick the guest checkout page.
249
289
  const experienceContext = {
250
290
  ...(resolvedBrandName
251
291
  ? { brand_name: resolvedBrandName.slice(0, 127) }
252
292
  : {}),
253
- landing_page: landingPage ?? "LOGIN",
293
+ landing_page: landingPage,
254
294
  user_action: "PAY_NOW",
255
295
  ...(requireInstantPayment
256
296
  ? { payment_method_preference: "IMMEDIATE_PAYMENT_REQUIRED" }
@@ -380,91 +420,30 @@ async function POST(req, res) {
380
420
  }
381
421
  }
382
422
  logger.debug(`[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}`);
383
- // Opt-in: attach the cart's shipping address to the PayPal order
384
- // (`SET_PROVIDED_ADDRESS`). Improves PayPal Seller Protection eligibility —
385
- // PayPal only protects shipments to the address on the order. Deliberately
386
- // a SEPARATE query: adding relation fields to the totals query above has
387
- // broken the totals decorator before (see the shipping_methods warning).
388
- const sendShippingAddress = additionalSettings.sendShippingAddress === true ||
389
- String(process.env.PAYPAL_SEND_SHIPPING_ADDRESS || "")
390
- .trim()
391
- .toLowerCase() === "true";
392
- let paypalShipping = null;
393
- if (sendShippingAddress && !isCardPayment) {
394
- try {
395
- const { data: addrData } = await query.graph({
396
- entity: "cart",
397
- fields: [
398
- "id",
399
- "shipping_address.first_name",
400
- "shipping_address.last_name",
401
- "shipping_address.address_1",
402
- "shipping_address.address_2",
403
- "shipping_address.city",
404
- "shipping_address.province",
405
- "shipping_address.postal_code",
406
- "shipping_address.country_code",
407
- ],
408
- filters: { id: cartId },
409
- });
410
- const addr = addrData?.[0]?.shipping_address;
411
- const line1 = String(addr?.address_1 || "").trim();
412
- const postal = String(addr?.postal_code || "").trim();
413
- const country = String(addr?.country_code || "")
414
- .trim()
415
- .toUpperCase();
416
- // PayPal rejects incomplete addresses — only send a usable one.
417
- if (addr && line1 && postal && country.length === 2) {
418
- const fullName = [addr.first_name, addr.last_name]
419
- .map((part) => String(part || "").trim())
420
- .filter(Boolean)
421
- .join(" ");
422
- paypalShipping = {
423
- ...(fullName
424
- ? { name: { full_name: fullName.slice(0, 300) } }
425
- : {}),
426
- address: {
427
- address_line_1: line1.slice(0, 300),
428
- ...(addr.address_2
429
- ? { address_line_2: String(addr.address_2).slice(0, 300) }
430
- : {}),
431
- ...(addr.city
432
- ? { admin_area_2: String(addr.city).slice(0, 120) }
433
- : {}),
434
- ...(addr.province
435
- ? { admin_area_1: String(addr.province).slice(0, 300) }
436
- : {}),
437
- postal_code: postal.slice(0, 60),
438
- country_code: country,
439
- },
440
- };
441
- experienceContext.shipping_preference = "SET_PROVIDED_ADDRESS";
442
- }
443
- }
444
- catch (e) {
445
- // Seller protection is an optimization, never a checkout blocker.
446
- logger.warn(`[paypal] create-order: could not attach shipping address (request_id=${requestId}): ${e instanceof Error ? e.message : String(e)}`);
447
- }
448
- }
449
423
  // Use the module's cached app access token (single-flight refresh, ~9h TTL)
450
424
  // instead of minting a fresh OAuth token on every create-order call.
451
425
  const base = (0, paypal_auth_1.getPayPalApiBase)(creds.environment);
452
426
  const accessToken = await paypal.getAppAccessToken();
453
- // Deterministic-per-(cart, amount, currency) idempotency key for the PayPal
454
- // call. The amount/currency MUST be part of the key: PayPal replays the
455
- // cached response for a reused PayPal-Request-Id, so a key derived from the
456
- // cart id alone would return the ORIGINAL order (at the original total)
457
- // when the buyer changes the cart and a fresh order is minted — silently
458
- // re-charging the stale amount and defeating the staleness check above.
459
- // Kept distinct from `requestId` (the log/response correlation id declared
460
- // at the top of POST) so the two never shadow each other.
461
- const paypalRequestId = resolveIdempotencyKey(req, `create-order-${cart.id}-${value}-${currency}`, `pp-create-${cart.id}-${value}-${currency}`);
462
- const ppResp = await (0, paypal_fetch_1.paypalFetch)(`${base}/v2/checkout/orders`, {
427
+ // Deterministic-per-(cart, amount, currency, address) idempotency key for
428
+ // the PayPal call. The amount/currency MUST be part of the key: PayPal
429
+ // replays the cached response for a reused PayPal-Request-Id, so a key
430
+ // derived from the cart id alone would return the ORIGINAL order (at the
431
+ // original total) when the buyer changes the cart and a fresh order is
432
+ // minted — silently re-charging the stale amount and defeating the
433
+ // staleness check above. The same goes for the shipping address now that
434
+ // it is part of the order. Kept distinct from `requestId` (the
435
+ // log/response correlation id declared at the top of POST) so the two
436
+ // never shadow each other.
437
+ const buildRequestId = (shipping) => {
438
+ const shippingKey = shipping ? `-${(0, order_context_1.shippingFingerprint)(shipping)}` : "";
439
+ return resolveIdempotencyKey(req, `create-order-${cart.id}-${value}-${currency}${shippingKey}`, `pp-create-${cart.id}-${value}-${currency}${shippingKey}`);
440
+ };
441
+ const sendCreateOrder = (shipping) => (0, paypal_fetch_1.paypalFetch)(`${base}/v2/checkout/orders`, {
463
442
  method: "POST",
464
443
  headers: {
465
444
  Authorization: `Bearer ${accessToken}`,
466
445
  "Content-Type": "application/json",
467
- "PayPal-Request-Id": paypalRequestId,
446
+ "PayPal-Request-Id": buildRequestId(shipping),
468
447
  "PayPal-Partner-Attribution-Id": partner_1.PAYPAL_PARTNER_ATTRIBUTION_ID,
469
448
  },
470
449
  body: JSON.stringify({
@@ -472,9 +451,10 @@ async function POST(req, res) {
472
451
  purchase_units: [
473
452
  {
474
453
  reference_id: "default",
475
- // Set custom_id on the purchase unit (not just the order) so PayPal
476
- // propagates the cart id onto capture/refund webhook resources,
477
- // letting webhooks resolve the session directly without a scan.
454
+ // custom_id belongs on the purchase unit (the order object has
455
+ // no such field): PayPal copies it onto capture/refund webhook
456
+ // resources, letting webhooks resolve the session directly
457
+ // without a scan.
478
458
  custom_id: cart.id,
479
459
  invoice_id: invoiceId,
480
460
  ...(statementName
@@ -488,7 +468,7 @@ async function POST(req, res) {
488
468
  ...(finalPurchaseItems.length > 0
489
469
  ? { items: finalPurchaseItems }
490
470
  : {}),
491
- ...(paypalShipping ? { shipping: paypalShipping } : {}),
471
+ ...(shipping ? { shipping } : {}),
492
472
  },
493
473
  ],
494
474
  payment_source: isCardPayment
@@ -502,7 +482,8 @@ async function POST(req, res) {
502
482
  }
503
483
  : {}),
504
484
  // Card orders only take the 3DS redirect URLs here; the rest
505
- // of experience_context is a PayPal-wallet concept.
485
+ // of experience_context (shipping_preference included) is a
486
+ // PayPal-wallet concept.
506
487
  experience_context: {
507
488
  ...(returnUrl ? { return_url: returnUrl } : {}),
508
489
  ...(cancelUrl ? { cancel_url: cancelUrl } : {}),
@@ -510,13 +491,31 @@ async function POST(req, res) {
510
491
  },
511
492
  }
512
493
  : {
513
- paypal: { experience_context: experienceContext },
494
+ paypal: {
495
+ experience_context: {
496
+ ...experienceContext,
497
+ ...(shipping
498
+ ? { shipping_preference: "SET_PROVIDED_ADDRESS" }
499
+ : {}),
500
+ },
501
+ },
514
502
  },
515
- custom_id: cart.id,
516
503
  }),
517
504
  });
518
- const ppText = await ppResp.text();
505
+ let ppResp = await sendCreateOrder(paypalShipping);
506
+ let ppText = await ppResp.text();
519
507
  debugId = ppResp.headers.get("paypal-debug-id");
508
+ // PayPal validates a provided address and rejects ones it cannot use. An
509
+ // address problem must not cost the sale: create the order without it and
510
+ // let the buyer pick an address in PayPal, as before 1.3.9.
511
+ if (!ppResp.ok &&
512
+ paypalShipping &&
513
+ (0, order_context_1.isShippingAddressRejection)(ppResp.status, ppText)) {
514
+ logger.warn(`[paypal] create-order: PayPal rejected the shipping address (debug_id=${debugId ?? "n/a"}, request_id=${requestId}) — retrying without it: ${ppText.slice(0, 500)}`);
515
+ ppResp = await sendCreateOrder(null);
516
+ ppText = await ppResp.text();
517
+ debugId = ppResp.headers.get("paypal-debug-id");
518
+ }
520
519
  if (!ppResp.ok) {
521
520
  throw new Error(`PayPal create order error (${ppResp.status}): ${ppText}${debugId ? ` debug_id=${debugId}` : ""}`);
522
521
  }