@easypayment/medusa-payment-paypal 1.3.9 → 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.
- package/.medusa/server/src/admin/index.js +102 -31
- package/.medusa/server/src/admin/index.mjs +102 -31
- package/.medusa/server/src/api/store/paypal/create-order/route.d.ts.map +1 -1
- package/.medusa/server/src/api/store/paypal/create-order/route.js +12 -6
- package/.medusa/server/src/api/store/paypal/create-order/route.js.map +1 -1
- package/.medusa/server/src/api/utils/request-logger.d.ts.map +1 -1
- package/.medusa/server/src/api/utils/request-logger.js +4 -2
- package/.medusa/server/src/api/utils/request-logger.js.map +1 -1
- package/.medusa/server/src/modules/paypal/service.d.ts +11 -12
- package/.medusa/server/src/modules/paypal/service.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/service.js +52 -75
- package/.medusa/server/src/modules/paypal/service.js.map +1 -1
- package/.medusa/server/src/modules/paypal/types/config.d.ts +0 -12
- package/.medusa/server/src/modules/paypal/types/config.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/types/config.js +0 -23
- package/.medusa/server/src/modules/paypal/types/config.js.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/merchant-status.d.ts +1 -3
- package/.medusa/server/src/modules/paypal/utils/merchant-status.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/merchant-status.js.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/request-logger.d.ts +12 -0
- package/.medusa/server/src/modules/paypal/utils/request-logger.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/request-logger.js +26 -2
- package/.medusa/server/src/modules/paypal/utils/request-logger.js.map +1 -1
- package/CHANGELOG.md +46 -0
- package/README.md +2 -3
- package/package.json +1 -1
- package/src/admin/routes/settings/paypal/additional-settings/page.tsx +22 -6
- package/src/admin/routes/settings/paypal/connection/page.tsx +66 -6
- package/src/api/store/paypal/create-order/route.ts +15 -8
- package/src/api/utils/request-logger.ts +7 -3
- package/src/modules/paypal/service.ts +70 -100
- package/src/modules/paypal/types/config.ts +0 -32
- package/src/modules/paypal/utils/merchant-status.ts +5 -3
- package/src/modules/paypal/utils/request-logger.ts +30 -2
|
@@ -22,16 +22,20 @@ type AdditionalSettingsForm = {
|
|
|
22
22
|
|
|
23
23
|
const DEFAULT_FORM: AdditionalSettingsForm = {
|
|
24
24
|
paymentAction: "capture",
|
|
25
|
-
brandName: "
|
|
25
|
+
brandName: "",
|
|
26
26
|
landingPage: "login",
|
|
27
27
|
requireInstantPayment: false,
|
|
28
28
|
sendItemDetails: true,
|
|
29
29
|
sendShippingAddress: true,
|
|
30
30
|
invoicePrefix: "PP-",
|
|
31
|
-
creditCardStatementName: "
|
|
31
|
+
creditCardStatementName: "",
|
|
32
32
|
debugLogging: false,
|
|
33
33
|
}
|
|
34
34
|
|
|
35
|
+
function isPlaceholderName(value: unknown) {
|
|
36
|
+
return typeof value === "string" && value.trim().toLowerCase() === "paypal"
|
|
37
|
+
}
|
|
38
|
+
|
|
35
39
|
/** Overlay saved values on the defaults, ignoring `undefined` entries. */
|
|
36
40
|
function mergeWithDefaults(saved?: Partial<AdditionalSettingsForm> | null) {
|
|
37
41
|
if (!saved) return { ...DEFAULT_FORM }
|
|
@@ -45,6 +49,12 @@ function mergeWithDefaults(saved?: Partial<AdditionalSettingsForm> | null) {
|
|
|
45
49
|
// "No Preference" was removed in 1.3.9 (PayPal asks for the login page);
|
|
46
50
|
// stores that saved it are shown, and sent, "Login".
|
|
47
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
|
+
}
|
|
48
58
|
return merged
|
|
49
59
|
}
|
|
50
60
|
|
|
@@ -195,7 +205,11 @@ export default function AdditionalSettingsTab() {
|
|
|
195
205
|
<option value="authorize">Authorize</option>
|
|
196
206
|
</select>
|
|
197
207
|
</FieldRow>
|
|
198
|
-
<FieldRow
|
|
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
|
+
>
|
|
199
213
|
<input
|
|
200
214
|
id="as-brand-name"
|
|
201
215
|
value={form.brandName}
|
|
@@ -203,7 +217,7 @@ export default function AdditionalSettingsTab() {
|
|
|
203
217
|
setForm((p) => ({ ...p, brandName: e.target.value }))
|
|
204
218
|
}
|
|
205
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"
|
|
206
|
-
placeholder="
|
|
220
|
+
placeholder="Your store name"
|
|
207
221
|
/>
|
|
208
222
|
</FieldRow>
|
|
209
223
|
<FieldRow label="Landing Page" htmlFor="as-landing-page">
|
|
@@ -296,6 +310,7 @@ export default function AdditionalSettingsTab() {
|
|
|
296
310
|
<FieldRow
|
|
297
311
|
label="Credit Card Statement Name"
|
|
298
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."
|
|
299
314
|
>
|
|
300
315
|
<input
|
|
301
316
|
id="as-cc-statement"
|
|
@@ -307,7 +322,8 @@ export default function AdditionalSettingsTab() {
|
|
|
307
322
|
}))
|
|
308
323
|
}
|
|
309
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"
|
|
310
|
-
placeholder="
|
|
325
|
+
placeholder="Your business name"
|
|
326
|
+
maxLength={22}
|
|
311
327
|
/>
|
|
312
328
|
</FieldRow>
|
|
313
329
|
</div>
|
|
@@ -332,7 +348,7 @@ export default function AdditionalSettingsTab() {
|
|
|
332
348
|
<div className="divide-y divide-ui-border-base">
|
|
333
349
|
<FieldRow
|
|
334
350
|
label="Request/response logging"
|
|
335
|
-
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."
|
|
336
352
|
>
|
|
337
353
|
<label className="inline-flex items-center gap-2">
|
|
338
354
|
<input
|
|
@@ -14,6 +14,26 @@ export const config = defineRouteConfig({
|
|
|
14
14
|
label: "PayPal Connection",
|
|
15
15
|
})
|
|
16
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
|
+
|
|
17
37
|
// Let partner.js own the entire onboarding flow: it opens PayPal's mini-browser
|
|
18
38
|
// itself (synchronously inside the click, so no new tab / no popup block), it
|
|
19
39
|
// receives PayPal's completion postMessage, and it invokes the callback named in
|
|
@@ -347,7 +367,13 @@ export default function PayPalConnectionPage() {
|
|
|
347
367
|
|
|
348
368
|
if (!res.ok) {
|
|
349
369
|
const txt = await res.text().catch(() => "")
|
|
350
|
-
throw new Error(
|
|
370
|
+
throw new Error(
|
|
371
|
+
describeFailure(
|
|
372
|
+
res.status,
|
|
373
|
+
txt,
|
|
374
|
+
`Onboarding exchange failed (${res.status})`
|
|
375
|
+
)
|
|
376
|
+
)
|
|
351
377
|
}
|
|
352
378
|
|
|
353
379
|
closeMiniBrowser()
|
|
@@ -678,7 +704,13 @@ export default function PayPalConnectionPage() {
|
|
|
678
704
|
|
|
679
705
|
if (!res.ok) {
|
|
680
706
|
const txt = await res.text().catch(() => "")
|
|
681
|
-
throw new Error(
|
|
707
|
+
throw new Error(
|
|
708
|
+
describeFailure(
|
|
709
|
+
res.status,
|
|
710
|
+
txt,
|
|
711
|
+
`Save credentials failed (${res.status})`
|
|
712
|
+
)
|
|
713
|
+
)
|
|
682
714
|
}
|
|
683
715
|
|
|
684
716
|
const statusRes = await fetch(`${STATUS_ENDPOINT}?environment=${env}`, {
|
|
@@ -723,7 +755,9 @@ export default function PayPalConnectionPage() {
|
|
|
723
755
|
|
|
724
756
|
if (!res.ok) {
|
|
725
757
|
const t = await res.text().catch(() => "")
|
|
726
|
-
throw new Error(
|
|
758
|
+
throw new Error(
|
|
759
|
+
describeFailure(res.status, t, `Disconnect failed (${res.status})`)
|
|
760
|
+
)
|
|
727
761
|
}
|
|
728
762
|
|
|
729
763
|
clearCachedUrl(env)
|
|
@@ -733,7 +767,10 @@ export default function PayPalConnectionPage() {
|
|
|
733
767
|
await fetchFreshLink(env, currentRunId.current)
|
|
734
768
|
} catch (e: any) {
|
|
735
769
|
console.error(e)
|
|
736
|
-
|
|
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")
|
|
737
774
|
setError(e?.message || "Failed to disconnect.")
|
|
738
775
|
} finally {
|
|
739
776
|
setOnboardingInProgress(false)
|
|
@@ -798,8 +835,23 @@ export default function PayPalConnectionPage() {
|
|
|
798
835
|
<div className="max-w-xl">
|
|
799
836
|
{connState === "connected" ? (
|
|
800
837
|
<div>
|
|
801
|
-
<div className="text-sm text-green-600 bg-green-50 p-3 rounded border border-green-200">
|
|
802
|
-
|
|
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>
|
|
803
855
|
<a
|
|
804
856
|
data-paypal-button="true"
|
|
805
857
|
data-paypal-onboard-complete="onboardingCallback"
|
|
@@ -826,6 +878,14 @@ export default function PayPalConnectionPage() {
|
|
|
826
878
|
</span>
|
|
827
879
|
</div>
|
|
828
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}
|
|
829
889
|
<div className="mt-3 flex items-center gap-2">
|
|
830
890
|
<button
|
|
831
891
|
type="button"
|
|
@@ -31,6 +31,17 @@ type Body = {
|
|
|
31
31
|
is_card_payment?: boolean
|
|
32
32
|
}
|
|
33
33
|
|
|
34
|
+
/**
|
|
35
|
+
* A merchant-entered name setting, or "" when it is unset. The admin form
|
|
36
|
+
* pre-filled "PayPal" for the brand and card-statement names until 1.3.10, so
|
|
37
|
+
* stores that saved it sent "PayPal" as their own business name; that value
|
|
38
|
+
* is treated as unset (the brand name then falls back to the store's name).
|
|
39
|
+
*/
|
|
40
|
+
function merchantName(setting: unknown): string {
|
|
41
|
+
const name = typeof setting === "string" ? setting.trim() : ""
|
|
42
|
+
return name.toLowerCase() === "paypal" ? "" : name
|
|
43
|
+
}
|
|
44
|
+
|
|
34
45
|
function resolveIdempotencyKey(
|
|
35
46
|
req: MedusaRequest,
|
|
36
47
|
suffix: string,
|
|
@@ -320,20 +331,16 @@ export async function POST(req: MedusaRequest, res: MedusaResponse) {
|
|
|
320
331
|
: "capture"
|
|
321
332
|
const paymentAction =
|
|
322
333
|
paymentActionRaw === "authorize" ? "AUTHORIZE" : "CAPTURE"
|
|
323
|
-
const brandName =
|
|
324
|
-
typeof additionalSettings.brandName === "string"
|
|
325
|
-
? additionalSettings.brandName
|
|
326
|
-
: undefined
|
|
334
|
+
const brandName = merchantName(additionalSettings.brandName) || undefined
|
|
327
335
|
const landingPage = resolveLandingPage(additionalSettings.landingPage)
|
|
328
336
|
const requireInstantPayment =
|
|
329
337
|
typeof additionalSettings.requireInstantPayment === "boolean"
|
|
330
338
|
? additionalSettings.requireInstantPayment
|
|
331
339
|
: undefined
|
|
332
340
|
const sendItemDetails = additionalSettings.sendItemDetails !== false
|
|
333
|
-
const statementName =
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
: ""
|
|
341
|
+
const statementName = merchantName(
|
|
342
|
+
additionalSettings.creditCardStatementName
|
|
343
|
+
)
|
|
337
344
|
const invoicePrefix =
|
|
338
345
|
typeof additionalSettings.invoicePrefix === "string"
|
|
339
346
|
? additionalSettings.invoicePrefix
|
|
@@ -60,9 +60,13 @@ export function createInboundLogger() {
|
|
|
60
60
|
try {
|
|
61
61
|
logInbound({
|
|
62
62
|
method: req.method,
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
63
|
+
// Path only: `originalUrl` carries the query string, which the
|
|
64
|
+
// logger appends itself from `query` (it used to appear twice).
|
|
65
|
+
path: String(
|
|
66
|
+
(req as any).baseUrl
|
|
67
|
+
? `${(req as any).baseUrl}${req.path || ""}`
|
|
68
|
+
: (req as any).originalUrl || req.path || req.url || ""
|
|
69
|
+
).split("?")[0],
|
|
66
70
|
query: req.query,
|
|
67
71
|
requestHeaders: req.headers,
|
|
68
72
|
requestBody: (req as any).body,
|
|
@@ -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
|
-
*
|
|
368
|
-
*
|
|
369
|
-
*
|
|
370
|
-
*
|
|
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;
|
|
376
|
-
): Promise<
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
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
|
|
348
|
+
const lookup = this.fetchMerchantIntegrationWithSellerCredentials(
|
|
392
349
|
env,
|
|
393
350
|
merchantId,
|
|
394
351
|
opts.sellerAccessToken
|
|
395
352
|
)
|
|
396
|
-
|
|
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.
|
|
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
|
-
|
|
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
|
|
1520
|
+
private static merchantLookupCache = new Map<string, MerchantLookup>()
|
|
1521
|
+
private static merchantLookupInflight = new Map<
|
|
1550
1522
|
string,
|
|
1551
|
-
|
|
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:
|
|
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
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
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,
|
|
1584
|
+
const { details, at } = await this.lookupMerchantIntegration(
|
|
1608
1585
|
env,
|
|
1609
1586
|
String(merchantId),
|
|
1610
|
-
|
|
1611
|
-
{ sellerFallback: env === activeEnv }
|
|
1587
|
+
{ refresh: opts.refresh }
|
|
1612
1588
|
)
|
|
1613
1589
|
|
|
1614
|
-
|
|
1590
|
+
return {
|
|
1615
1591
|
environment: env,
|
|
1616
1592
|
available: true,
|
|
1617
|
-
|
|
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.
|
|
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:
|
|
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
|
-
|
|
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-"
|