@easypayment/medusa-payment-paypal 1.3.8 → 1.3.10

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 (47) hide show
  1. package/.medusa/server/src/admin/index.js +261 -94
  2. package/.medusa/server/src/admin/index.mjs +196 -31
  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 +113 -108
  10. package/.medusa/server/src/api/store/paypal/create-order/route.js.map +1 -1
  11. package/.medusa/server/src/api/utils/request-logger.d.ts.map +1 -1
  12. package/.medusa/server/src/api/utils/request-logger.js +4 -2
  13. package/.medusa/server/src/api/utils/request-logger.js.map +1 -1
  14. package/.medusa/server/src/modules/paypal/service.d.ts +33 -0
  15. package/.medusa/server/src/modules/paypal/service.d.ts.map +1 -1
  16. package/.medusa/server/src/modules/paypal/service.js +138 -34
  17. package/.medusa/server/src/modules/paypal/service.js.map +1 -1
  18. package/.medusa/server/src/modules/paypal/types/config.d.ts.map +1 -1
  19. package/.medusa/server/src/modules/paypal/types/config.js +2 -1
  20. package/.medusa/server/src/modules/paypal/types/config.js.map +1 -1
  21. package/.medusa/server/src/modules/paypal/utils/merchant-status.d.ts +48 -0
  22. package/.medusa/server/src/modules/paypal/utils/merchant-status.d.ts.map +1 -0
  23. package/.medusa/server/src/modules/paypal/utils/merchant-status.js +106 -0
  24. package/.medusa/server/src/modules/paypal/utils/merchant-status.js.map +1 -0
  25. package/.medusa/server/src/modules/paypal/utils/order-context.d.ts +61 -0
  26. package/.medusa/server/src/modules/paypal/utils/order-context.d.ts.map +1 -0
  27. package/.medusa/server/src/modules/paypal/utils/order-context.js +127 -0
  28. package/.medusa/server/src/modules/paypal/utils/order-context.js.map +1 -0
  29. package/.medusa/server/src/modules/paypal/utils/request-logger.d.ts +12 -0
  30. package/.medusa/server/src/modules/paypal/utils/request-logger.d.ts.map +1 -1
  31. package/.medusa/server/src/modules/paypal/utils/request-logger.js +26 -2
  32. package/.medusa/server/src/modules/paypal/utils/request-logger.js.map +1 -1
  33. package/CHANGELOG.md +102 -0
  34. package/README.md +4 -4
  35. package/package.json +1 -1
  36. package/src/admin/routes/settings/paypal/_components/MerchantStatusNotices.tsx +116 -0
  37. package/src/admin/routes/settings/paypal/additional-settings/page.tsx +54 -12
  38. package/src/admin/routes/settings/paypal/advanced-card-payments/page.tsx +2 -0
  39. package/src/admin/routes/settings/paypal/connection/page.tsx +73 -6
  40. package/src/api/admin/paypal/merchant-status/route.ts +36 -0
  41. package/src/api/store/paypal/create-order/route.ts +191 -165
  42. package/src/api/utils/request-logger.ts +7 -3
  43. package/src/modules/paypal/service.ts +192 -43
  44. package/src/modules/paypal/types/config.ts +3 -2
  45. package/src/modules/paypal/utils/merchant-status.ts +187 -0
  46. package/src/modules/paypal/utils/order-context.ts +163 -0
  47. package/src/modules/paypal/utils/request-logger.ts +30 -2
@@ -0,0 +1,116 @@
1
+ import React, { useEffect, useState } from "react"
2
+ import { adminFetch } from "../_utils/adminFetch"
3
+
4
+ type Notice = {
5
+ code: string
6
+ level: "error" | "warning"
7
+ message: string
8
+ }
9
+
10
+ type MerchantStatusResponse = {
11
+ available?: boolean
12
+ notices?: Notice[]
13
+ }
14
+
15
+ const URL_RE = /(https?:\/\/[^\s]+[^\s.,!?])/g
16
+
17
+ /** Render a notice, turning the PayPal URLs in it into links. */
18
+ function NoticeText({ message }: { message: string }) {
19
+ const parts = message.split(URL_RE)
20
+ return (
21
+ <>
22
+ {parts.map((part, i) =>
23
+ /^https?:\/\//.test(part) ? (
24
+ <a
25
+ key={i}
26
+ href={part}
27
+ target="_blank"
28
+ rel="noopener noreferrer"
29
+ className="underline"
30
+ >
31
+ {part}
32
+ </a>
33
+ ) : (
34
+ <React.Fragment key={i}>{part}</React.Fragment>
35
+ )
36
+ )}
37
+ </>
38
+ )
39
+ }
40
+
41
+ /**
42
+ * Warnings about the connected PayPal account, from PayPal's seller onboarding
43
+ * status: unconfirmed email, payments not receivable, PayPal payments or
44
+ * Advanced Card payments not enabled. Renders nothing while loading, when the
45
+ * seller is not connected, when the status cannot be read, and when every
46
+ * check passes.
47
+ *
48
+ * `only` narrows the notices to the ones a page cares about; `reloadKey`
49
+ * re-fetches when it changes (e.g. after connecting).
50
+ */
51
+ export default function MerchantStatusNotices({
52
+ environment,
53
+ only,
54
+ reloadKey,
55
+ }: {
56
+ environment?: "sandbox" | "live"
57
+ only?: string[]
58
+ reloadKey?: string | number
59
+ }) {
60
+ const [notices, setNotices] = useState<Notice[]>([])
61
+
62
+ useEffect(() => {
63
+ let cancelled = false
64
+ setNotices([])
65
+ ;(async () => {
66
+ try {
67
+ const json = await adminFetch<MerchantStatusResponse>(
68
+ "/admin/paypal/merchant-status",
69
+ environment ? { query: { environment } } : {}
70
+ )
71
+ if (cancelled) return
72
+ setNotices(Array.isArray(json?.notices) ? json.notices : [])
73
+ } catch {
74
+ // The warnings are advisory: never break the page over them.
75
+ }
76
+ })()
77
+ return () => {
78
+ cancelled = true
79
+ }
80
+ }, [environment, reloadKey])
81
+
82
+ const visible = only
83
+ ? notices.filter((notice) => only.includes(notice.code))
84
+ : notices
85
+ if (visible.length === 0) return null
86
+
87
+ return (
88
+ <div className="flex flex-col gap-2" data-testid="paypal-merchant-notices">
89
+ {visible.map((notice) => (
90
+ <div
91
+ key={notice.code}
92
+ role="alert"
93
+ className="rounded border p-3 text-sm"
94
+ // Colors are inline: the admin's stylesheet only carries the utility
95
+ // classes Medusa itself uses, so an amber/red palette class may not
96
+ // exist there.
97
+ style={
98
+ notice.level === "error"
99
+ ? {
100
+ background: "#fef2f2",
101
+ borderColor: "#fecaca",
102
+ color: "#b91c1c",
103
+ }
104
+ : {
105
+ background: "#fffbeb",
106
+ borderColor: "#fde68a",
107
+ color: "#92400e",
108
+ }
109
+ }
110
+ >
111
+ <NoticeText message={notice.message} />
112
+ </div>
113
+ ))}
114
+ </div>
115
+ )
116
+ }
@@ -6,7 +6,7 @@ import Toast, { ToastState } from "../_components/Toast"
6
6
  import { adminFetch } from "../_utils/adminFetch"
7
7
 
8
8
  type PaymentAction = "capture" | "authorize"
9
- type LandingPage = "no_preference" | "login" | "billing"
9
+ type LandingPage = "login" | "billing"
10
10
 
11
11
  type AdditionalSettingsForm = {
12
12
  paymentAction: PaymentAction
@@ -14,6 +14,7 @@ type AdditionalSettingsForm = {
14
14
  landingPage: LandingPage
15
15
  requireInstantPayment: boolean
16
16
  sendItemDetails: boolean
17
+ sendShippingAddress: boolean
17
18
  invoicePrefix: string
18
19
  creditCardStatementName: string
19
20
  debugLogging: boolean
@@ -21,25 +22,40 @@ type AdditionalSettingsForm = {
21
22
 
22
23
  const DEFAULT_FORM: AdditionalSettingsForm = {
23
24
  paymentAction: "capture",
24
- brandName: "PayPal",
25
- landingPage: "no_preference",
25
+ brandName: "",
26
+ landingPage: "login",
26
27
  requireInstantPayment: false,
27
28
  sendItemDetails: true,
29
+ sendShippingAddress: true,
28
30
  invoicePrefix: "PP-",
29
- creditCardStatementName: "PayPal",
31
+ creditCardStatementName: "",
30
32
  debugLogging: false,
31
33
  }
32
34
 
35
+ function isPlaceholderName(value: unknown) {
36
+ return typeof value === "string" && value.trim().toLowerCase() === "paypal"
37
+ }
38
+
33
39
  /** Overlay saved values on the defaults, ignoring `undefined` entries. */
34
40
  function mergeWithDefaults(saved?: Partial<AdditionalSettingsForm> | null) {
35
41
  if (!saved) return { ...DEFAULT_FORM }
36
42
  const entries = Object.entries(saved).filter(
37
43
  ([, value]) => value !== undefined
38
44
  )
39
- return {
45
+ const merged = {
40
46
  ...DEFAULT_FORM,
41
47
  ...(Object.fromEntries(entries) as Partial<AdditionalSettingsForm>),
42
48
  }
49
+ // "No Preference" was removed in 1.3.9 (PayPal asks for the login page);
50
+ // stores that saved it are shown, and sent, "Login".
51
+ if (merged.landingPage !== "billing") merged.landingPage = "login"
52
+ // "PayPal" was the pre-filled default for both names until 1.3.10. It is
53
+ // never a merchant's own name, and it is not sent, so show the field empty.
54
+ if (isPlaceholderName(merged.brandName)) merged.brandName = ""
55
+ if (isPlaceholderName(merged.creditCardStatementName)) {
56
+ merged.creditCardStatementName = ""
57
+ }
58
+ return merged
43
59
  }
44
60
 
45
61
  /** Settings → PayPal → Additional Settings (checkout behaviour + invoice options). */
@@ -189,7 +205,11 @@ export default function AdditionalSettingsTab() {
189
205
  <option value="authorize">Authorize</option>
190
206
  </select>
191
207
  </FieldRow>
192
- <FieldRow label="Brand Name" htmlFor="as-brand-name">
208
+ <FieldRow
209
+ label="Brand Name"
210
+ htmlFor="as-brand-name"
211
+ hint="The business name customers see in the PayPal checkout. Leave empty to use your store's name."
212
+ >
193
213
  <input
194
214
  id="as-brand-name"
195
215
  value={form.brandName}
@@ -197,7 +217,7 @@ export default function AdditionalSettingsTab() {
197
217
  setForm((p) => ({ ...p, brandName: e.target.value }))
198
218
  }
199
219
  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"
200
- placeholder="PayPal"
220
+ placeholder="Your store name"
201
221
  />
202
222
  </FieldRow>
203
223
  <FieldRow label="Landing Page" htmlFor="as-landing-page">
@@ -212,9 +232,8 @@ export default function AdditionalSettingsTab() {
212
232
  }
213
233
  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"
214
234
  >
215
- <option value="no_preference">No Preference</option>
216
- <option value="login">Login</option>
217
- <option value="billing">Billing</option>
235
+ <option value="login">Login (PayPal account)</option>
236
+ <option value="billing">Guest checkout (card form)</option>
218
237
  </select>
219
238
  </FieldRow>
220
239
  <FieldRow label="Instant Payments">
@@ -256,6 +275,27 @@ export default function AdditionalSettingsTab() {
256
275
  </span>
257
276
  </label>
258
277
  </FieldRow>
278
+ <FieldRow
279
+ label="Send Shipping Address"
280
+ 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."
281
+ >
282
+ <label className="inline-flex items-center gap-2">
283
+ <input
284
+ type="checkbox"
285
+ checked={form.sendShippingAddress}
286
+ onChange={(e) =>
287
+ setForm((p) => ({
288
+ ...p,
289
+ sendShippingAddress: e.target.checked,
290
+ }))
291
+ }
292
+ className="h-4 w-4 rounded border-ui-border-base"
293
+ />
294
+ <span className="text-sm text-ui-fg-base">
295
+ Send the checkout shipping address to PayPal
296
+ </span>
297
+ </label>
298
+ </FieldRow>
259
299
  <FieldRow label="Invoice prefix" htmlFor="as-invoice-prefix">
260
300
  <input
261
301
  id="as-invoice-prefix"
@@ -270,6 +310,7 @@ export default function AdditionalSettingsTab() {
270
310
  <FieldRow
271
311
  label="Credit Card Statement Name"
272
312
  htmlFor="as-cc-statement"
313
+ hint="Shown on the customer's card statement (up to 22 characters). Leave empty to use the name on your PayPal account."
273
314
  >
274
315
  <input
275
316
  id="as-cc-statement"
@@ -281,7 +322,8 @@ export default function AdditionalSettingsTab() {
281
322
  }))
282
323
  }
283
324
  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"
284
- placeholder="PayPal"
325
+ placeholder="Your business name"
326
+ maxLength={22}
285
327
  />
286
328
  </FieldRow>
287
329
  </div>
@@ -306,7 +348,7 @@ export default function AdditionalSettingsTab() {
306
348
  <div className="divide-y divide-ui-border-base">
307
349
  <FieldRow
308
350
  label="Request/response logging"
309
- hint="When enabled, the plugin appends each request and response to logs/paypal-requests-YYYY-MM-DD.log (path configurable via PAYPAL_LOG_DIR). Remember to save after toggling."
351
+ hint="When enabled, the plugin appends each request and response to .medusa/paypal-logs/paypal-requests-YYYY-MM-DD.log in your project (path configurable via PAYPAL_LOG_DIR). Remember to save after toggling."
310
352
  >
311
353
  <label className="inline-flex items-center gap-2">
312
354
  <input
@@ -3,6 +3,7 @@ import PayPalTabs from "../_components/Tabs"
3
3
  import SectionCard from "../_components/SectionCard"
4
4
  import FieldRow from "../_components/FieldRow"
5
5
  import Toast, { ToastState } from "../_components/Toast"
6
+ import MerchantStatusNotices from "../_components/MerchantStatusNotices"
6
7
  import { adminFetch } from "../_utils/adminFetch"
7
8
 
8
9
  type ThreeDSContingency = "sli" | "when_required" | "always"
@@ -120,6 +121,7 @@ export default function AdvancedCardPaymentsTab() {
120
121
  </div>
121
122
  <PayPalTabs />
122
123
  <Toast toast={toast} onClose={dismissToast} />
124
+ <MerchantStatusNotices only={["card_payments_not_enabled"]} />
123
125
  <SectionCard
124
126
  title="Advanced Card Payments"
125
127
  description="Control card checkout settings and 3D Secure behavior."
@@ -8,11 +8,32 @@ import React, {
8
8
  } from "react"
9
9
  import { defineRouteConfig } from "@medusajs/admin-sdk"
10
10
  import PayPalTabs from "../_components/Tabs"
11
+ import MerchantStatusNotices from "../_components/MerchantStatusNotices"
11
12
 
12
13
  export const config = defineRouteConfig({
13
14
  label: "PayPal Connection",
14
15
  })
15
16
 
17
+ const SESSION_EXPIRED_MESSAGE =
18
+ "Your admin session has expired. Reload this page and log in again."
19
+
20
+ /**
21
+ * What to show for a failed admin API call. The raw response body is JSON such
22
+ * as {"message":"Unauthorized"}, which means nothing to a merchant.
23
+ */
24
+ function describeFailure(status: number, body: string, fallback: string) {
25
+ if (status === 401) return SESSION_EXPIRED_MESSAGE
26
+ try {
27
+ const message = JSON.parse(body)?.message
28
+ if (typeof message === "string" && message.trim()) return message.trim()
29
+ } catch {
30
+ // not JSON: fall through
31
+ }
32
+ const text = body.trim()
33
+ // An HTML error page is no better than the raw JSON.
34
+ return text && !text.startsWith("<") ? text.slice(0, 300) : fallback
35
+ }
36
+
16
37
  // Let partner.js own the entire onboarding flow: it opens PayPal's mini-browser
17
38
  // itself (synchronously inside the click, so no new tab / no popup block), it
18
39
  // receives PayPal's completion postMessage, and it invokes the callback named in
@@ -346,7 +367,13 @@ export default function PayPalConnectionPage() {
346
367
 
347
368
  if (!res.ok) {
348
369
  const txt = await res.text().catch(() => "")
349
- throw new Error(txt || `Onboarding exchange failed (${res.status})`)
370
+ throw new Error(
371
+ describeFailure(
372
+ res.status,
373
+ txt,
374
+ `Onboarding exchange failed (${res.status})`
375
+ )
376
+ )
350
377
  }
351
378
 
352
379
  closeMiniBrowser()
@@ -677,7 +704,13 @@ export default function PayPalConnectionPage() {
677
704
 
678
705
  if (!res.ok) {
679
706
  const txt = await res.text().catch(() => "")
680
- throw new Error(txt || `Save credentials failed (${res.status})`)
707
+ throw new Error(
708
+ describeFailure(
709
+ res.status,
710
+ txt,
711
+ `Save credentials failed (${res.status})`
712
+ )
713
+ )
681
714
  }
682
715
 
683
716
  const statusRes = await fetch(`${STATUS_ENDPOINT}?environment=${env}`, {
@@ -722,7 +755,9 @@ export default function PayPalConnectionPage() {
722
755
 
723
756
  if (!res.ok) {
724
757
  const t = await res.text().catch(() => "")
725
- throw new Error(t || `Disconnect failed (${res.status})`)
758
+ throw new Error(
759
+ describeFailure(res.status, t, `Disconnect failed (${res.status})`)
760
+ )
726
761
  }
727
762
 
728
763
  clearCachedUrl(env)
@@ -732,7 +767,10 @@ export default function PayPalConnectionPage() {
732
767
  await fetchFreshLink(env, currentRunId.current)
733
768
  } catch (e: any) {
734
769
  console.error(e)
735
- setConnState("error")
770
+ // Nothing was disconnected. Show the account as it still is rather than
771
+ // the "not connected" view this handler switched to before the call.
772
+ const stillConnected = await refreshStatusAndMaybeConnect(env)
773
+ if (!stillConnected) setConnState("error")
736
774
  setError(e?.message || "Failed to disconnect.")
737
775
  } finally {
738
776
  setOnboardingInProgress(false)
@@ -797,8 +835,23 @@ export default function PayPalConnectionPage() {
797
835
  <div className="max-w-xl">
798
836
  {connState === "connected" ? (
799
837
  <div>
800
- <div className="text-sm text-green-600 bg-green-50 p-3 rounded border border-green-200">
801
- ✅ Successfully connected to PayPal!
838
+ <div className="flex items-center gap-2 text-sm text-green-600 bg-green-50 p-3 rounded border border-green-200">
839
+ <svg
840
+ width="16"
841
+ height="16"
842
+ viewBox="0 0 24 24"
843
+ fill="none"
844
+ stroke="currentColor"
845
+ strokeWidth="2.5"
846
+ strokeLinecap="round"
847
+ strokeLinejoin="round"
848
+ aria-hidden="true"
849
+ style={{ flexShrink: 0 }}
850
+ >
851
+ <circle cx="12" cy="12" r="10" />
852
+ <path d="m8 12 3 3 5-6" />
853
+ </svg>
854
+ <span>Successfully connected to PayPal</span>
802
855
  <a
803
856
  data-paypal-button="true"
804
857
  data-paypal-onboard-complete="onboardingCallback"
@@ -808,6 +861,12 @@ export default function PayPalConnectionPage() {
808
861
  PayPal
809
862
  </a>
810
863
  </div>
864
+ <div className="mt-3">
865
+ <MerchantStatusNotices
866
+ environment={env}
867
+ reloadKey={statusInfo?.seller_client_id_masked || ""}
868
+ />
869
+ </div>
811
870
  <div className="mt-3 rounded-md border border-ui-border-base bg-ui-bg-subtle p-3 text-xs text-ui-fg-subtle">
812
871
  <div className="font-medium text-ui-fg-base">
813
872
  Connected PayPal account
@@ -819,6 +878,14 @@ export default function PayPalConnectionPage() {
819
878
  </span>
820
879
  </div>
821
880
  </div>
881
+ {error ? (
882
+ <div
883
+ role="alert"
884
+ className="mt-3 text-left text-xs bg-red-50 text-red-600 p-3 border border-red-200 rounded"
885
+ >
886
+ {error}
887
+ </div>
888
+ ) : null}
822
889
  <div className="mt-3 flex items-center gap-2">
823
890
  <button
824
891
  type="button"
@@ -0,0 +1,36 @@
1
+ import type { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
2
+ import type PayPalModuleService from "../../../../modules/paypal/service"
3
+
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
+ export async function GET(req: MedusaRequest, res: MedusaResponse) {
13
+ try {
14
+ const paypal = req.scope.resolve<PayPalModuleService>("paypal_onboarding")
15
+
16
+ const q = (req.query || {}) as Record<string, any>
17
+ const envParam = (q.environment || q.env) as string | undefined
18
+ const env =
19
+ envParam === "live"
20
+ ? "live"
21
+ : envParam === "sandbox"
22
+ ? "sandbox"
23
+ : undefined
24
+ const refresh = q.refresh === "1" || q.refresh === "true"
25
+
26
+ return res.json(await paypal.getMerchantStatus(env, { refresh }))
27
+ } catch (e: unknown) {
28
+ console.error(
29
+ "[PayPal] merchant-status GET failed:",
30
+ e instanceof Error ? e.message : e
31
+ )
32
+ return res
33
+ .status(500)
34
+ .json({ message: "Failed to retrieve PayPal seller status" })
35
+ }
36
+ }