@easypayment/medusa-payment-paypal 1.3.9 → 1.3.11

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 (34) hide show
  1. package/.medusa/server/src/admin/index.js +96 -25
  2. package/.medusa/server/src/admin/index.mjs +96 -25
  3. package/.medusa/server/src/api/store/paypal/create-order/route.d.ts.map +1 -1
  4. package/.medusa/server/src/api/store/paypal/create-order/route.js +12 -6
  5. package/.medusa/server/src/api/store/paypal/create-order/route.js.map +1 -1
  6. package/.medusa/server/src/api/utils/request-logger.d.ts.map +1 -1
  7. package/.medusa/server/src/api/utils/request-logger.js +4 -2
  8. package/.medusa/server/src/api/utils/request-logger.js.map +1 -1
  9. package/.medusa/server/src/modules/paypal/service.d.ts +11 -12
  10. package/.medusa/server/src/modules/paypal/service.d.ts.map +1 -1
  11. package/.medusa/server/src/modules/paypal/service.js +52 -75
  12. package/.medusa/server/src/modules/paypal/service.js.map +1 -1
  13. package/.medusa/server/src/modules/paypal/types/config.d.ts +0 -12
  14. package/.medusa/server/src/modules/paypal/types/config.d.ts.map +1 -1
  15. package/.medusa/server/src/modules/paypal/types/config.js +0 -23
  16. package/.medusa/server/src/modules/paypal/types/config.js.map +1 -1
  17. package/.medusa/server/src/modules/paypal/utils/merchant-status.d.ts +1 -3
  18. package/.medusa/server/src/modules/paypal/utils/merchant-status.d.ts.map +1 -1
  19. package/.medusa/server/src/modules/paypal/utils/merchant-status.js.map +1 -1
  20. package/.medusa/server/src/modules/paypal/utils/request-logger.d.ts +12 -0
  21. package/.medusa/server/src/modules/paypal/utils/request-logger.d.ts.map +1 -1
  22. package/.medusa/server/src/modules/paypal/utils/request-logger.js +26 -2
  23. package/.medusa/server/src/modules/paypal/utils/request-logger.js.map +1 -1
  24. package/CHANGELOG.md +50 -0
  25. package/README.md +2 -3
  26. package/package.json +1 -1
  27. package/src/admin/routes/settings/paypal/additional-settings/page.tsx +22 -6
  28. package/src/admin/routes/settings/paypal/connection/page.tsx +66 -6
  29. package/src/api/store/paypal/create-order/route.ts +15 -8
  30. package/src/api/utils/request-logger.ts +7 -3
  31. package/src/modules/paypal/service.ts +70 -100
  32. package/src/modules/paypal/types/config.ts +0 -32
  33. package/src/modules/paypal/utils/merchant-status.ts +5 -3
  34. package/src/modules/paypal/utils/request-logger.ts +30 -2
@@ -23,6 +23,12 @@ import { setRequestLoggingEnabled } from "./utils/request-logger"
23
23
 
24
24
  type Environment = "sandbox" | "live"
25
25
 
26
+ /** A seller status answer and when it was read. */
27
+ type MerchantLookup = {
28
+ details: Record<string, any>
29
+ at: number
30
+ }
31
+
26
32
  type Status =
27
33
  | "disconnected"
28
34
  | "pending"
@@ -306,94 +312,54 @@ class PayPalModuleService extends MedusaService({
306
312
  return null
307
313
  }
308
314
 
309
- /**
310
- * Seller onboarding status read by the partner service with the PARTNER's
311
- * credentials, as PayPal's partner review requires. The plugin only holds
312
- * the seller's credentials, so it cannot make this call itself.
313
- */
314
- private async fetchMerchantIntegrationViaPartner(
315
- env: Environment,
316
- merchantId: string
317
- ) {
318
- const url = this.cfg.partnerStatusUrl
319
- if (!url) {
320
- throw new Error("Partner status service URL is not configured.")
321
- }
322
-
323
- const form = new URLSearchParams()
324
- form.set("sandbox", env === "live" ? "no" : "yes")
325
- form.set("merchant_id", merchantId)
326
- form.set("from", "medusa")
327
-
328
- const res = await paypalFetch(url, {
329
- method: "POST",
330
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
331
- body: form.toString(),
332
- })
333
-
334
- const text = await res.text().catch(() => "")
335
- let json: any
336
- try {
337
- json = text ? JSON.parse(text) : null
338
- } catch {
339
- // A non-JSON answer (e.g. an HTML error page) is handled as a failure.
340
- }
341
-
342
- const body = json?.body
343
- if (
344
- !res.ok ||
345
- json?.result !== "success" ||
346
- !body ||
347
- typeof body !== "object"
348
- ) {
349
- const reason =
350
- body && typeof body === "object"
351
- ? [body.name, body.message].filter(Boolean).join(": ")
352
- : text.slice(0, 200)
353
- throw new Error(
354
- `Partner status lookup failed (${json?.http_code ?? res.status})${
355
- reason ? `: ${reason}` : ""
356
- }${json?.debug_id ? ` debug_id=${json.debug_id}` : ""}`
357
- )
358
- }
359
-
360
- return body as Record<string, any>
361
- }
362
-
363
315
  /**
364
316
  * Seller onboarding status
365
- * (`/v1/customer/partners/{partner-id}/merchant-integrations/{merchant-id}`).
317
+ * (`/v1/customer/partners/{partner-id}/merchant-integrations/{merchant-id}`),
318
+ * read with the SELLER's own credentials.
366
319
  *
367
- * Asked through the partner service first (partner credentials). When that is
368
- * unavailable or PayPal refuses the partner token for this seller, falls back
369
- * to the seller's own credentials — unless `sellerFallback` is false, which
370
- * callers pass when no usable seller token exists for `env`.
320
+ * Onboarding is `integration_type: FIRST_PARTY`, and for a first-party
321
+ * integration PayPal only accepts this call from the seller: with the
322
+ * partner's token it answers 401 AUTHORIZATION_ERROR ("If it's a first party
323
+ * integration this request shouldn't come with the partner scope"). 1.3.9
324
+ * tried the partner's credentials first, through the partner service; that
325
+ * attempt could never succeed and was removed.
371
326
  */
372
327
  private async lookupMerchantIntegration(
373
328
  env: Environment,
374
329
  merchantId: string,
375
- opts: { sellerAccessToken?: string; sellerFallback?: boolean } = {}
376
- ): Promise<{ details: Record<string, any>; source: "partner" | "seller" }> {
377
- try {
378
- const details = await this.fetchMerchantIntegrationViaPartner(
379
- env,
380
- merchantId
381
- )
382
- return { details, source: "partner" }
383
- } catch (e: any) {
384
- if (opts.sellerFallback === false) throw e
385
- console.warn(
386
- "[PayPal] partner seller-status lookup failed, using seller credentials:",
387
- e?.message || e
388
- )
330
+ opts: { sellerAccessToken?: string; refresh?: boolean } = {}
331
+ ): Promise<MerchantLookup> {
332
+ // The admin asks for the status from several places at once (the
333
+ // connection page, the card settings page, the onboarding exchange). They
334
+ // share one PayPal call: a fresh answer is reused for a few minutes, and
335
+ // callers that arrive while a lookup is in flight wait for that lookup.
336
+ const key = `${env}::${merchantId}`
337
+ const cached = PayPalModuleService.merchantLookupCache.get(key)
338
+ if (
339
+ cached &&
340
+ !opts.refresh &&
341
+ Date.now() - cached.at < PayPalModuleService.MERCHANT_STATUS_TTL_MS
342
+ ) {
343
+ return cached
389
344
  }
345
+ const inflight = PayPalModuleService.merchantLookupInflight.get(key)
346
+ if (inflight) return inflight
390
347
 
391
- const details = await this.fetchMerchantIntegrationWithSellerCredentials(
348
+ const lookup = this.fetchMerchantIntegrationWithSellerCredentials(
392
349
  env,
393
350
  merchantId,
394
351
  opts.sellerAccessToken
395
352
  )
396
- return { details, source: "seller" }
353
+ .then((details) => {
354
+ const entry: MerchantLookup = { details, at: Date.now() }
355
+ PayPalModuleService.merchantLookupCache.set(key, entry)
356
+ return entry
357
+ })
358
+ .finally(() => {
359
+ PayPalModuleService.merchantLookupInflight.delete(key)
360
+ })
361
+ PayPalModuleService.merchantLookupInflight.set(key, lookup)
362
+ return lookup
397
363
  }
398
364
 
399
365
  private async fetchMerchantIntegrationDetails(
@@ -667,7 +633,7 @@ class PayPalModuleService extends MedusaService({
667
633
  async setEnvironment(env: Environment) {
668
634
  // Tokens are minted per environment/credentials — drop them on any switch.
669
635
  PayPalModuleService.clientTokenCache.clear()
670
- PayPalModuleService.merchantStatusCache.clear()
636
+ PayPalModuleService.clearMerchantLookups()
671
637
  const nextEnv: Environment = env === "sandbox" ? "sandbox" : "live"
672
638
  const row = await this.getCurrentRow()
673
639
  const previousEnv = (row?.environment as Environment) || "live"
@@ -1114,7 +1080,12 @@ class PayPalModuleService extends MedusaService({
1114
1080
  // New credentials invalidate any client token minted for the old account.
1115
1081
  PayPalModuleService.clientTokenCache.clear()
1116
1082
  }
1117
- PayPalModuleService.merchantStatusCache.clear()
1083
+ if (!credentialsUnchanged) {
1084
+ // A different account: its status has to be read again. The same
1085
+ // credentials saved again (to add the seller's email) keep the answer.
1086
+ PayPalModuleService.clearMerchantLookups()
1087
+ }
1088
+
1118
1089
  const nextSellerMerchantId =
1119
1090
  (input.sellerMerchantId || "").trim() ||
1120
1091
  existingCreds.sellerMerchantId ||
@@ -1546,12 +1517,18 @@ class PayPalModuleService extends MedusaService({
1546
1517
  }
1547
1518
  }
1548
1519
 
1549
- private static merchantStatusCache = new Map<
1520
+ private static merchantLookupCache = new Map<string, MerchantLookup>()
1521
+ private static merchantLookupInflight = new Map<
1550
1522
  string,
1551
- { at: number; value: MerchantStatusReport }
1523
+ Promise<MerchantLookup>
1552
1524
  >()
1553
1525
  private static MERCHANT_STATUS_TTL_MS = 5 * 60 * 1000
1554
1526
 
1527
+ private static clearMerchantLookups() {
1528
+ PayPalModuleService.merchantLookupCache.clear()
1529
+ PayPalModuleService.merchantLookupInflight.clear()
1530
+ }
1531
+
1555
1532
  /**
1556
1533
  * Whether the connected seller can take payments, from PayPal's seller
1557
1534
  * onboarding status: email confirmed, payments receivable, PayPal payments
@@ -1570,7 +1547,11 @@ class PayPalModuleService extends MedusaService({
1570
1547
  const activeEnv = await this.getCurrentEnvironment()
1571
1548
  const env = envOverride ?? activeEnv
1572
1549
  const unavailable = (
1573
- reason: "not_connected" | "merchant_id_unknown" | "lookup_failed",
1550
+ reason:
1551
+ | "not_connected"
1552
+ | "merchant_id_unknown"
1553
+ | "inactive_environment"
1554
+ | "lookup_failed",
1574
1555
  message?: string
1575
1556
  ): MerchantStatusReport => ({
1576
1557
  environment: env,
@@ -1594,35 +1575,24 @@ class PayPalModuleService extends MedusaService({
1594
1575
  return unavailable("merchant_id_unknown")
1595
1576
  }
1596
1577
 
1597
- const cacheKey = `${env}::${merchantId}`
1598
- const cached = PayPalModuleService.merchantStatusCache.get(cacheKey)
1599
- if (
1600
- cached &&
1601
- !opts.refresh &&
1602
- Date.now() - cached.at < PayPalModuleService.MERCHANT_STATUS_TTL_MS
1603
- ) {
1604
- return cached.value
1578
+ if (env !== activeEnv) {
1579
+ // The status is read with the seller's app access token, and the
1580
+ // cached token belongs to the active environment only.
1581
+ return unavailable("inactive_environment")
1605
1582
  }
1606
1583
 
1607
- const { details, source } = await this.lookupMerchantIntegration(
1584
+ const { details, at } = await this.lookupMerchantIntegration(
1608
1585
  env,
1609
1586
  String(merchantId),
1610
- // The cached app token belongs to the active environment only.
1611
- { sellerFallback: env === activeEnv }
1587
+ { refresh: opts.refresh }
1612
1588
  )
1613
1589
 
1614
- const value: MerchantStatusReport = {
1590
+ return {
1615
1591
  environment: env,
1616
1592
  available: true,
1617
- source,
1618
- checked_at: new Date().toISOString(),
1593
+ checked_at: new Date(at).toISOString(),
1619
1594
  ...evaluateMerchantStatus(details),
1620
1595
  }
1621
- PayPalModuleService.merchantStatusCache.set(cacheKey, {
1622
- at: Date.now(),
1623
- value,
1624
- })
1625
- return value
1626
1596
  } catch (e: any) {
1627
1597
  console.warn("[PayPal] seller status lookup failed:", e?.message || e)
1628
1598
  return unavailable("lookup_failed", e?.message || String(e))
@@ -1636,7 +1606,7 @@ class PayPalModuleService extends MedusaService({
1636
1606
  */
1637
1607
  async disconnect() {
1638
1608
  PayPalModuleService.clientTokenCache.clear()
1639
- PayPalModuleService.merchantStatusCache.clear()
1609
+ PayPalModuleService.clearMerchantLookups()
1640
1610
  const row = await this.getCurrentRow()
1641
1611
  if (!row) return
1642
1612
  const env = await this.getCurrentEnvironment()
@@ -15,12 +15,6 @@ export const PARTNER_SELLER_NONCE =
15
15
  /** Partner-level configuration, resolved from env vars with built-in defaults. */
16
16
  export type PayPalModuleConfig = {
17
17
  partnerServiceUrl: string
18
- /**
19
- * Partner-service endpoint that reads a seller's onboarding status with the
20
- * partner's credentials. Empty when it cannot be derived from a custom
21
- * `partnerServiceUrl` and `PAYPAL_PARTNER_STATUS_URL` is not set.
22
- */
23
- partnerStatusUrl: string
24
18
  partnerJsUrl: string
25
19
  backendUrl: string
26
20
  sellerNonce: string
@@ -30,32 +24,9 @@ export type PayPalModuleConfig = {
30
24
  alertWebhookUrls?: string[]
31
25
  }
32
26
 
33
- /**
34
- * The seller-status endpoint lives next to the onboarding endpoint on the
35
- * partner service (`seller-onboarding.php` → `seller-status.php`). Returns ""
36
- * for a partner service URL that does not follow that layout.
37
- */
38
- export function derivePartnerStatusUrl(partnerServiceUrl: string): string {
39
- try {
40
- const url = new URL(partnerServiceUrl)
41
- if (!/\/seller-onboarding\.php$/.test(url.pathname)) return ""
42
- url.pathname = url.pathname.replace(
43
- /seller-onboarding\.php$/,
44
- "seller-status.php"
45
- )
46
- url.search = ""
47
- url.hash = ""
48
- return url.toString()
49
- } catch {
50
- return ""
51
- }
52
- }
53
-
54
27
  const STATIC_CFG: PayPalModuleConfig = {
55
28
  partnerServiceUrl:
56
29
  "https://mbjtechnolabs.com/medusa-seller-onboarding/seller-onboarding.php?from=medusa",
57
- partnerStatusUrl:
58
- "https://mbjtechnolabs.com/medusa-seller-onboarding/seller-status.php",
59
30
  partnerJsUrl:
60
31
  "https://www.paypal.com/webapps/merchantboarding/js/lib/lightbox/partner.js",
61
32
  backendUrl: "http://localhost:9000",
@@ -75,9 +46,6 @@ export function getPayPalConfig(): PayPalModuleConfig {
75
46
  return {
76
47
  ...STATIC_CFG,
77
48
  partnerServiceUrl,
78
- partnerStatusUrl:
79
- (process.env.PAYPAL_PARTNER_STATUS_URL || "").trim() ||
80
- derivePartnerStatusUrl(partnerServiceUrl),
81
49
  backendUrl,
82
50
  sellerNonce: process.env.PAYPAL_SELLER_NONCE || STATIC_CFG.sellerNonce,
83
51
  partnerMerchantIdSandbox:
@@ -43,14 +43,16 @@ export type MerchantStatusReport =
43
43
  | ({
44
44
  environment: string
45
45
  available: true
46
- /** Whose credentials read the status: the partner's or the seller's. */
47
- source: "partner" | "seller"
48
46
  checked_at: string
49
47
  } & MerchantStatus)
50
48
  | {
51
49
  environment: string
52
50
  available: false
53
- reason: "not_connected" | "merchant_id_unknown" | "lookup_failed"
51
+ reason:
52
+ | "not_connected"
53
+ | "merchant_id_unknown"
54
+ | "inactive_environment"
55
+ | "lookup_failed"
54
56
  message?: string
55
57
  notices: MerchantNotice[]
56
58
  }
@@ -160,9 +160,37 @@ function normalizeHeaders(headers: unknown): Record<string, string> {
160
160
  // File sink
161
161
  // ---------------------------------------------------------------------------
162
162
 
163
+ /**
164
+ * Where the request log is written: `PAYPAL_LOG_DIR` when set, otherwise
165
+ * `<project>/.medusa/paypal-logs`.
166
+ *
167
+ * The default used to be `<cwd>/logs`. `medusa develop` restarts the server
168
+ * whenever a file changes inside the project, so every logged request
169
+ * restarted it — and with in-memory sessions each restart logged the admin
170
+ * out. `.medusa` is ignored by that watcher (and by git in Medusa projects).
171
+ * The built server runs from `<project>/.medusa/server`, which each build
172
+ * wipes, so the project root is used there too and the logs survive rebuilds.
173
+ */
174
+ export function resolveLogDir(
175
+ envDir: string | undefined = process.env.PAYPAL_LOG_DIR,
176
+ cwd: string = process.cwd()
177
+ ): string {
178
+ const dir = (envDir || "").trim()
179
+ if (dir) return path.resolve(dir)
180
+
181
+ const parts = path.resolve(cwd).split(path.sep)
182
+ const inBuiltServer =
183
+ parts.length >= 2 &&
184
+ parts[parts.length - 2] === ".medusa" &&
185
+ parts[parts.length - 1] === "server"
186
+ const projectRoot = inBuiltServer
187
+ ? path.resolve(cwd, "..", "..")
188
+ : path.resolve(cwd)
189
+ return path.join(projectRoot, ".medusa", "paypal-logs")
190
+ }
191
+
163
192
  function getLogDir(): string {
164
- const dir = (process.env.PAYPAL_LOG_DIR || "").trim()
165
- return dir ? path.resolve(dir) : path.join(process.cwd(), "logs")
193
+ return resolveLogDir()
166
194
  }
167
195
 
168
196
  const LOG_PREFIX = "paypal-requests-"