@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.
- package/.medusa/server/src/admin/index.js +261 -94
- package/.medusa/server/src/admin/index.mjs +196 -31
- package/.medusa/server/src/api/admin/paypal/merchant-status/route.d.ts +11 -0
- package/.medusa/server/src/api/admin/paypal/merchant-status/route.d.ts.map +1 -0
- package/.medusa/server/src/api/admin/paypal/merchant-status/route.js +32 -0
- package/.medusa/server/src/api/admin/paypal/merchant-status/route.js.map +1 -0
- package/.medusa/server/src/api/store/paypal/create-order/route.d.ts +4 -1
- 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 +113 -108
- 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 +33 -0
- package/.medusa/server/src/modules/paypal/service.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/service.js +138 -34
- package/.medusa/server/src/modules/paypal/service.js.map +1 -1
- package/.medusa/server/src/modules/paypal/types/config.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/types/config.js +2 -1
- package/.medusa/server/src/modules/paypal/types/config.js.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/merchant-status.d.ts +48 -0
- package/.medusa/server/src/modules/paypal/utils/merchant-status.d.ts.map +1 -0
- package/.medusa/server/src/modules/paypal/utils/merchant-status.js +106 -0
- package/.medusa/server/src/modules/paypal/utils/merchant-status.js.map +1 -0
- package/.medusa/server/src/modules/paypal/utils/order-context.d.ts +61 -0
- package/.medusa/server/src/modules/paypal/utils/order-context.d.ts.map +1 -0
- package/.medusa/server/src/modules/paypal/utils/order-context.js +127 -0
- package/.medusa/server/src/modules/paypal/utils/order-context.js.map +1 -0
- 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 +102 -0
- package/README.md +4 -4
- package/package.json +1 -1
- package/src/admin/routes/settings/paypal/_components/MerchantStatusNotices.tsx +116 -0
- package/src/admin/routes/settings/paypal/additional-settings/page.tsx +54 -12
- package/src/admin/routes/settings/paypal/advanced-card-payments/page.tsx +2 -0
- package/src/admin/routes/settings/paypal/connection/page.tsx +73 -6
- package/src/api/admin/paypal/merchant-status/route.ts +36 -0
- package/src/api/store/paypal/create-order/route.ts +191 -165
- package/src/api/utils/request-logger.ts +7 -3
- package/src/modules/paypal/service.ts +192 -43
- package/src/modules/paypal/types/config.ts +3 -2
- package/src/modules/paypal/utils/merchant-status.ts +187 -0
- package/src/modules/paypal/utils/order-context.ts +163 -0
- package/src/modules/paypal/utils/request-logger.ts +30 -2
|
@@ -10,6 +10,10 @@ import { getPayPalConfig } from "./types/config"
|
|
|
10
10
|
import { getPayPalApiBase } from "./utils/paypal-auth"
|
|
11
11
|
import { normalizeCurrencyCode } from "./utils/currencies"
|
|
12
12
|
import { PAYPAL_PARTNER_ATTRIBUTION_ID } from "./utils/partner"
|
|
13
|
+
import {
|
|
14
|
+
evaluateMerchantStatus,
|
|
15
|
+
type MerchantStatusReport,
|
|
16
|
+
} from "./utils/merchant-status"
|
|
13
17
|
import {
|
|
14
18
|
getCachedSettings,
|
|
15
19
|
invalidateSettingsCache,
|
|
@@ -19,6 +23,12 @@ import { setRequestLoggingEnabled } from "./utils/request-logger"
|
|
|
19
23
|
|
|
20
24
|
type Environment = "sandbox" | "live"
|
|
21
25
|
|
|
26
|
+
/** A seller status answer and when it was read. */
|
|
27
|
+
type MerchantLookup = {
|
|
28
|
+
details: Record<string, any>
|
|
29
|
+
at: number
|
|
30
|
+
}
|
|
31
|
+
|
|
22
32
|
type Status =
|
|
23
33
|
| "disconnected"
|
|
24
34
|
| "pending"
|
|
@@ -302,10 +312,71 @@ class PayPalModuleService extends MedusaService({
|
|
|
302
312
|
return null
|
|
303
313
|
}
|
|
304
314
|
|
|
315
|
+
/**
|
|
316
|
+
* Seller onboarding status
|
|
317
|
+
* (`/v1/customer/partners/{partner-id}/merchant-integrations/{merchant-id}`),
|
|
318
|
+
* read with the SELLER's own credentials.
|
|
319
|
+
*
|
|
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.
|
|
326
|
+
*/
|
|
327
|
+
private async lookupMerchantIntegration(
|
|
328
|
+
env: Environment,
|
|
329
|
+
merchantId: string,
|
|
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
|
|
344
|
+
}
|
|
345
|
+
const inflight = PayPalModuleService.merchantLookupInflight.get(key)
|
|
346
|
+
if (inflight) return inflight
|
|
347
|
+
|
|
348
|
+
const lookup = this.fetchMerchantIntegrationWithSellerCredentials(
|
|
349
|
+
env,
|
|
350
|
+
merchantId,
|
|
351
|
+
opts.sellerAccessToken
|
|
352
|
+
)
|
|
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
|
|
363
|
+
}
|
|
364
|
+
|
|
305
365
|
private async fetchMerchantIntegrationDetails(
|
|
306
366
|
env: Environment,
|
|
307
367
|
merchantId: string,
|
|
308
368
|
accessTokenOverride?: string
|
|
369
|
+
) {
|
|
370
|
+
const { details } = await this.lookupMerchantIntegration(env, merchantId, {
|
|
371
|
+
sellerAccessToken: accessTokenOverride,
|
|
372
|
+
})
|
|
373
|
+
return details
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
private async fetchMerchantIntegrationWithSellerCredentials(
|
|
377
|
+
env: Environment,
|
|
378
|
+
merchantId: string,
|
|
379
|
+
accessTokenOverride?: string
|
|
309
380
|
) {
|
|
310
381
|
const partnerMerchantId = await this.getPartnerMerchantId(env)
|
|
311
382
|
if (!partnerMerchantId) {
|
|
@@ -562,6 +633,7 @@ class PayPalModuleService extends MedusaService({
|
|
|
562
633
|
async setEnvironment(env: Environment) {
|
|
563
634
|
// Tokens are minted per environment/credentials — drop them on any switch.
|
|
564
635
|
PayPalModuleService.clientTokenCache.clear()
|
|
636
|
+
PayPalModuleService.clearMerchantLookups()
|
|
565
637
|
const nextEnv: Environment = env === "sandbox" ? "sandbox" : "live"
|
|
566
638
|
const row = await this.getCurrentRow()
|
|
567
639
|
const previousEnv = (row?.environment as Environment) || "live"
|
|
@@ -933,7 +1005,7 @@ class PayPalModuleService extends MedusaService({
|
|
|
933
1005
|
}
|
|
934
1006
|
|
|
935
1007
|
let sellerEmail = this.extractSellerEmail(credJson, tokenJson)
|
|
936
|
-
|
|
1008
|
+
const sellerMerchantId =
|
|
937
1009
|
String(
|
|
938
1010
|
credJson.payer_id ||
|
|
939
1011
|
credJson.merchant_id ||
|
|
@@ -942,37 +1014,10 @@ class PayPalModuleService extends MedusaService({
|
|
|
942
1014
|
""
|
|
943
1015
|
).trim() || null
|
|
944
1016
|
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
String(tokenJson.payer_id || "").trim(),
|
|
950
|
-
String(tokenJson.merchant_id || "").trim(),
|
|
951
|
-
]
|
|
952
|
-
.filter(Boolean)
|
|
953
|
-
.filter((v, i, arr) => arr.indexOf(v) === i)
|
|
954
|
-
|
|
955
|
-
for (const merchantId of merchantCandidates) {
|
|
956
|
-
try {
|
|
957
|
-
const merchantDetails = await this.fetchMerchantIntegrationDetails(
|
|
958
|
-
env,
|
|
959
|
-
merchantId,
|
|
960
|
-
sellerAccessToken
|
|
961
|
-
)
|
|
962
|
-
sellerMerchantId = sellerMerchantId || merchantId
|
|
963
|
-
sellerEmail = this.extractSellerEmail(merchantDetails)
|
|
964
|
-
if (sellerEmail) {
|
|
965
|
-
break
|
|
966
|
-
}
|
|
967
|
-
} catch (e: any) {
|
|
968
|
-
console.warn(
|
|
969
|
-
`[PayPal] Merchant integration lookup for ${merchantId} failed:`,
|
|
970
|
-
e?.message || e
|
|
971
|
-
)
|
|
972
|
-
}
|
|
973
|
-
}
|
|
974
|
-
}
|
|
975
|
-
|
|
1017
|
+
// Save first: the status lookup below may need the app access token, which
|
|
1018
|
+
// is minted from the stored credentials (and cached). The token PayPal
|
|
1019
|
+
// issued for the authorization code cannot read the seller's status — the
|
|
1020
|
+
// attempt that used to be made with it here always failed with 401.
|
|
976
1021
|
await this.saveSellerCredentials({
|
|
977
1022
|
clientId,
|
|
978
1023
|
clientSecret,
|
|
@@ -982,11 +1027,9 @@ class PayPalModuleService extends MedusaService({
|
|
|
982
1027
|
|
|
983
1028
|
if (!sellerEmail && sellerMerchantId) {
|
|
984
1029
|
try {
|
|
985
|
-
const appAccessToken = await this.getAppAccessToken()
|
|
986
1030
|
const details = await this.fetchMerchantIntegrationDetails(
|
|
987
1031
|
env,
|
|
988
|
-
sellerMerchantId
|
|
989
|
-
appAccessToken
|
|
1032
|
+
sellerMerchantId
|
|
990
1033
|
)
|
|
991
1034
|
sellerEmail = this.extractSellerEmail(details)
|
|
992
1035
|
if (sellerEmail) {
|
|
@@ -1017,13 +1060,32 @@ class PayPalModuleService extends MedusaService({
|
|
|
1017
1060
|
sellerEmail?: string | null
|
|
1018
1061
|
environment?: Environment
|
|
1019
1062
|
}) {
|
|
1020
|
-
// New credentials invalidate any client token minted for the old account.
|
|
1021
|
-
PayPalModuleService.clientTokenCache.clear()
|
|
1022
1063
|
const row = await this.getCurrentRow()
|
|
1023
1064
|
const currentEnv = await this.getCurrentEnvironment()
|
|
1024
1065
|
const env = (input.environment || currentEnv) as Environment
|
|
1025
1066
|
|
|
1026
1067
|
const existingCreds = row ? this.getEnvCreds(row, env) : {}
|
|
1068
|
+
// The same credentials saved again (e.g. to add the seller's email once it
|
|
1069
|
+
// is known) keep the cached app access token: PayPal expects a token to be
|
|
1070
|
+
// re-used until it expires, not re-minted on every save.
|
|
1071
|
+
const credentialsUnchanged =
|
|
1072
|
+
!!row &&
|
|
1073
|
+
env === currentEnv &&
|
|
1074
|
+
existingCreds.clientId === input.clientId &&
|
|
1075
|
+
existingCreds.clientSecret === input.clientSecret
|
|
1076
|
+
const tokenReset = credentialsUnchanged
|
|
1077
|
+
? {}
|
|
1078
|
+
: { app_access_token: null, app_access_token_expires_at: null }
|
|
1079
|
+
if (!credentialsUnchanged) {
|
|
1080
|
+
// New credentials invalidate any client token minted for the old account.
|
|
1081
|
+
PayPalModuleService.clientTokenCache.clear()
|
|
1082
|
+
}
|
|
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
|
+
|
|
1027
1089
|
const nextSellerMerchantId =
|
|
1028
1090
|
(input.sellerMerchantId || "").trim() ||
|
|
1029
1091
|
existingCreds.sellerMerchantId ||
|
|
@@ -1086,8 +1148,7 @@ class PayPalModuleService extends MedusaService({
|
|
|
1086
1148
|
seller_client_secret: storedClientSecret,
|
|
1087
1149
|
seller_merchant_id: nextSellerMerchantId,
|
|
1088
1150
|
seller_email: nextSellerEmail,
|
|
1089
|
-
|
|
1090
|
-
app_access_token_expires_at: null,
|
|
1151
|
+
...tokenReset,
|
|
1091
1152
|
metadata: {
|
|
1092
1153
|
...(row.metadata || {}),
|
|
1093
1154
|
credentials: creds,
|
|
@@ -1121,10 +1182,15 @@ class PayPalModuleService extends MedusaService({
|
|
|
1121
1182
|
})
|
|
1122
1183
|
|
|
1123
1184
|
try {
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1185
|
+
// The credentials were just stored, so for the active environment the
|
|
1186
|
+
// cached app access token is used rather than minting a second one.
|
|
1187
|
+
const activeEnv = await this.getCurrentEnvironment()
|
|
1188
|
+
const hydrated = await this.fetchSellerProfileFromDirectCredentials(
|
|
1189
|
+
env,
|
|
1190
|
+
env === activeEnv
|
|
1191
|
+
? undefined
|
|
1192
|
+
: { clientId: input.clientId, clientSecret: input.clientSecret }
|
|
1193
|
+
)
|
|
1128
1194
|
|
|
1129
1195
|
if (hydrated.sellerEmail || hydrated.sellerMerchantId) {
|
|
1130
1196
|
await this.saveSellerCredentials({
|
|
@@ -1451,6 +1517,88 @@ class PayPalModuleService extends MedusaService({
|
|
|
1451
1517
|
}
|
|
1452
1518
|
}
|
|
1453
1519
|
|
|
1520
|
+
private static merchantLookupCache = new Map<string, MerchantLookup>()
|
|
1521
|
+
private static merchantLookupInflight = new Map<
|
|
1522
|
+
string,
|
|
1523
|
+
Promise<MerchantLookup>
|
|
1524
|
+
>()
|
|
1525
|
+
private static MERCHANT_STATUS_TTL_MS = 5 * 60 * 1000
|
|
1526
|
+
|
|
1527
|
+
private static clearMerchantLookups() {
|
|
1528
|
+
PayPalModuleService.merchantLookupCache.clear()
|
|
1529
|
+
PayPalModuleService.merchantLookupInflight.clear()
|
|
1530
|
+
}
|
|
1531
|
+
|
|
1532
|
+
/**
|
|
1533
|
+
* Whether the connected seller can take payments, from PayPal's seller
|
|
1534
|
+
* onboarding status: email confirmed, payments receivable, PayPal payments
|
|
1535
|
+
* (`PPCP_STANDARD` subscribed + `PAY_WITH_PAYPAL` active) and Advanced Card
|
|
1536
|
+
* payments (`PPCP_CUSTOM` subscribed + `CUSTOM_CARD_PROCESSING` active), plus
|
|
1537
|
+
* the notices to show the merchant when any of those is not met.
|
|
1538
|
+
*
|
|
1539
|
+
* Makes an outbound call, so it is cached for a few minutes per seller and
|
|
1540
|
+
* kept out of `getStatus()` (which must stay a side-effect-free read).
|
|
1541
|
+
* Never throws: a failed lookup is reported as `available: false`.
|
|
1542
|
+
*/
|
|
1543
|
+
async getMerchantStatus(
|
|
1544
|
+
envOverride?: Environment,
|
|
1545
|
+
opts: { refresh?: boolean } = {}
|
|
1546
|
+
): Promise<MerchantStatusReport> {
|
|
1547
|
+
const activeEnv = await this.getCurrentEnvironment()
|
|
1548
|
+
const env = envOverride ?? activeEnv
|
|
1549
|
+
const unavailable = (
|
|
1550
|
+
reason:
|
|
1551
|
+
| "not_connected"
|
|
1552
|
+
| "merchant_id_unknown"
|
|
1553
|
+
| "inactive_environment"
|
|
1554
|
+
| "lookup_failed",
|
|
1555
|
+
message?: string
|
|
1556
|
+
): MerchantStatusReport => ({
|
|
1557
|
+
environment: env,
|
|
1558
|
+
available: false,
|
|
1559
|
+
reason,
|
|
1560
|
+
...(message ? { message } : {}),
|
|
1561
|
+
notices: [],
|
|
1562
|
+
})
|
|
1563
|
+
|
|
1564
|
+
try {
|
|
1565
|
+
const row = await this.getCurrentRow()
|
|
1566
|
+
const c = row ? this.getEnvCreds(row, env) : {}
|
|
1567
|
+
if (!row || !c.clientId || !c.clientSecret) {
|
|
1568
|
+
return unavailable("not_connected")
|
|
1569
|
+
}
|
|
1570
|
+
const merchantId =
|
|
1571
|
+
c.sellerMerchantId ||
|
|
1572
|
+
(env === activeEnv ? row.seller_merchant_id : null) ||
|
|
1573
|
+
null
|
|
1574
|
+
if (!merchantId) {
|
|
1575
|
+
return unavailable("merchant_id_unknown")
|
|
1576
|
+
}
|
|
1577
|
+
|
|
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")
|
|
1582
|
+
}
|
|
1583
|
+
|
|
1584
|
+
const { details, at } = await this.lookupMerchantIntegration(
|
|
1585
|
+
env,
|
|
1586
|
+
String(merchantId),
|
|
1587
|
+
{ refresh: opts.refresh }
|
|
1588
|
+
)
|
|
1589
|
+
|
|
1590
|
+
return {
|
|
1591
|
+
environment: env,
|
|
1592
|
+
available: true,
|
|
1593
|
+
checked_at: new Date(at).toISOString(),
|
|
1594
|
+
...evaluateMerchantStatus(details),
|
|
1595
|
+
}
|
|
1596
|
+
} catch (e: any) {
|
|
1597
|
+
console.warn("[PayPal] seller status lookup failed:", e?.message || e)
|
|
1598
|
+
return unavailable("lookup_failed", e?.message || String(e))
|
|
1599
|
+
}
|
|
1600
|
+
}
|
|
1601
|
+
|
|
1454
1602
|
/**
|
|
1455
1603
|
* Remove the active environment's credentials. The other environment (if
|
|
1456
1604
|
* connected) is untouched, so the row stays "connected" when it still holds
|
|
@@ -1458,6 +1606,7 @@ class PayPalModuleService extends MedusaService({
|
|
|
1458
1606
|
*/
|
|
1459
1607
|
async disconnect() {
|
|
1460
1608
|
PayPalModuleService.clientTokenCache.clear()
|
|
1609
|
+
PayPalModuleService.clearMerchantLookups()
|
|
1461
1610
|
const row = await this.getCurrentRow()
|
|
1462
1611
|
if (!row) return
|
|
1463
1612
|
const env = await this.getCurrentEnvironment()
|
|
@@ -40,11 +40,12 @@ const STATIC_CFG: PayPalModuleConfig = {
|
|
|
40
40
|
/** Resolve the module configuration from the environment. */
|
|
41
41
|
export function getPayPalConfig(): PayPalModuleConfig {
|
|
42
42
|
const backendUrl = process.env.MEDUSA_BACKEND_URL || STATIC_CFG.backendUrl
|
|
43
|
+
const partnerServiceUrl =
|
|
44
|
+
process.env.PAYPAL_PARTNER_SERVICE_URL || STATIC_CFG.partnerServiceUrl
|
|
43
45
|
|
|
44
46
|
return {
|
|
45
47
|
...STATIC_CFG,
|
|
46
|
-
partnerServiceUrl
|
|
47
|
-
process.env.PAYPAL_PARTNER_SERVICE_URL || STATIC_CFG.partnerServiceUrl,
|
|
48
|
+
partnerServiceUrl,
|
|
48
49
|
backendUrl,
|
|
49
50
|
sellerNonce: process.env.PAYPAL_SELLER_NONCE || STATIC_CFG.sellerNonce,
|
|
50
51
|
partnerMerchantIdSandbox:
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Turn PayPal's seller onboarding status
|
|
3
|
+
* (`GET /v1/customer/partners/{partner-id}/merchant-integrations/{merchant-id}`)
|
|
4
|
+
* into what the admin needs to know: can this seller receive payments, are
|
|
5
|
+
* PayPal payments and Advanced Card payments enabled, and what should the
|
|
6
|
+
* merchant be told when they are not.
|
|
7
|
+
*
|
|
8
|
+
* The checks and the two "Attention" messages are the ones PayPal's partner
|
|
9
|
+
* integration review asks for (2026-11-17).
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
export type MerchantNoticeLevel = "error" | "warning"
|
|
13
|
+
|
|
14
|
+
export type MerchantNotice = {
|
|
15
|
+
code:
|
|
16
|
+
| "email_not_confirmed"
|
|
17
|
+
| "payments_not_receivable"
|
|
18
|
+
| "paypal_payments_not_enabled"
|
|
19
|
+
| "card_payments_not_enabled"
|
|
20
|
+
level: MerchantNoticeLevel
|
|
21
|
+
message: string
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export type MerchantFeatureStatus = {
|
|
25
|
+
enabled: boolean
|
|
26
|
+
/** `products[name].vetting_status`, or null when the product is absent. */
|
|
27
|
+
vetting_status: string | null
|
|
28
|
+
/** `capabilities[name].status`, or null when the capability is absent. */
|
|
29
|
+
capability_status: string | null
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export type MerchantStatus = {
|
|
33
|
+
merchant_id: string | null
|
|
34
|
+
payments_receivable: boolean | null
|
|
35
|
+
primary_email_confirmed: boolean | null
|
|
36
|
+
paypal_payments: MerchantFeatureStatus
|
|
37
|
+
card_payments: MerchantFeatureStatus
|
|
38
|
+
notices: MerchantNotice[]
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** What `PayPalModuleService.getMerchantStatus()` reports to the admin. */
|
|
42
|
+
export type MerchantStatusReport =
|
|
43
|
+
| ({
|
|
44
|
+
environment: string
|
|
45
|
+
available: true
|
|
46
|
+
checked_at: string
|
|
47
|
+
} & MerchantStatus)
|
|
48
|
+
| {
|
|
49
|
+
environment: string
|
|
50
|
+
available: false
|
|
51
|
+
reason:
|
|
52
|
+
| "not_connected"
|
|
53
|
+
| "merchant_id_unknown"
|
|
54
|
+
| "inactive_environment"
|
|
55
|
+
| "lookup_failed"
|
|
56
|
+
message?: string
|
|
57
|
+
notices: MerchantNotice[]
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export const EMAIL_NOT_CONFIRMED_MESSAGE =
|
|
61
|
+
"Attention: Please confirm your email address on https://www.paypal.com/businessprofile/settings in order to receive payments! You currently cannot receive payments."
|
|
62
|
+
|
|
63
|
+
export const PAYMENTS_NOT_RECEIVABLE_MESSAGE =
|
|
64
|
+
"Attention: You currently cannot receive payments due to restriction on your PayPal account. Please reach out to PayPal Customer Support or connect to https://www.paypal.com for more information."
|
|
65
|
+
|
|
66
|
+
function upper(value: unknown): string | null {
|
|
67
|
+
const text = String(value ?? "")
|
|
68
|
+
.trim()
|
|
69
|
+
.toUpperCase()
|
|
70
|
+
return text || null
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function findByName(list: unknown, name: string): Record<string, any> | null {
|
|
74
|
+
if (!Array.isArray(list)) return null
|
|
75
|
+
const match = list.find(
|
|
76
|
+
(entry) => entry && typeof entry === "object" && upper(entry.name) === name
|
|
77
|
+
)
|
|
78
|
+
return (match as Record<string, any>) || null
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function featureStatus(
|
|
82
|
+
details: Record<string, any>,
|
|
83
|
+
productName: string,
|
|
84
|
+
capabilityName: string
|
|
85
|
+
): MerchantFeatureStatus {
|
|
86
|
+
const vetting = upper(
|
|
87
|
+
findByName(details.products, productName)?.vetting_status
|
|
88
|
+
)
|
|
89
|
+
const capability = upper(
|
|
90
|
+
findByName(details.capabilities, capabilityName)?.status
|
|
91
|
+
)
|
|
92
|
+
return {
|
|
93
|
+
enabled: vetting === "SUBSCRIBED" && capability === "ACTIVE",
|
|
94
|
+
vetting_status: vetting,
|
|
95
|
+
capability_status: capability,
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Merchant-facing explanation for a feature that is not enabled. */
|
|
100
|
+
function notEnabledMessage(label: string, status: MerchantFeatureStatus) {
|
|
101
|
+
switch (status.vetting_status) {
|
|
102
|
+
case null:
|
|
103
|
+
return `${label} are not enabled on your PayPal account. Please connect your PayPal account again to apply, or contact PayPal Customer Support.`
|
|
104
|
+
case "NEED_MORE_DATA":
|
|
105
|
+
return `${label} are not enabled yet: PayPal needs more information from you. Please log in to your PayPal account and provide the requested details.`
|
|
106
|
+
case "IN_REVIEW":
|
|
107
|
+
case "PENDING":
|
|
108
|
+
return `${label} are not enabled yet: PayPal is still reviewing your application. This can take a few days; you do not need to do anything for now.`
|
|
109
|
+
case "DENIED":
|
|
110
|
+
return `${label} are not available: PayPal declined your application. Please contact PayPal Customer Support for more information.`
|
|
111
|
+
case "SUBSCRIBED":
|
|
112
|
+
return `${label} are approved on your PayPal account but not active yet (status: ${
|
|
113
|
+
status.capability_status || "not available"
|
|
114
|
+
}). Please check your PayPal account for pending actions, or contact PayPal Customer Support.`
|
|
115
|
+
default:
|
|
116
|
+
return `${label} are not enabled on your PayPal account (status: ${status.vetting_status}). Please check your PayPal account, or contact PayPal Customer Support.`
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Evaluate a merchant-integrations response. Never throws. */
|
|
121
|
+
export function evaluateMerchantStatus(input: unknown): MerchantStatus {
|
|
122
|
+
const details =
|
|
123
|
+
input && typeof input === "object" ? (input as Record<string, any>) : {}
|
|
124
|
+
|
|
125
|
+
const paymentsReceivable =
|
|
126
|
+
typeof details.payments_receivable === "boolean"
|
|
127
|
+
? details.payments_receivable
|
|
128
|
+
: null
|
|
129
|
+
const emailConfirmed =
|
|
130
|
+
typeof details.primary_email_confirmed === "boolean"
|
|
131
|
+
? details.primary_email_confirmed
|
|
132
|
+
: null
|
|
133
|
+
|
|
134
|
+
const paypalPayments = featureStatus(
|
|
135
|
+
details,
|
|
136
|
+
"PPCP_STANDARD",
|
|
137
|
+
"PAY_WITH_PAYPAL"
|
|
138
|
+
)
|
|
139
|
+
const cardPayments = featureStatus(
|
|
140
|
+
details,
|
|
141
|
+
"PPCP_CUSTOM",
|
|
142
|
+
"CUSTOM_CARD_PROCESSING"
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
const notices: MerchantNotice[] = []
|
|
146
|
+
if (emailConfirmed === false) {
|
|
147
|
+
notices.push({
|
|
148
|
+
code: "email_not_confirmed",
|
|
149
|
+
level: "error",
|
|
150
|
+
message: EMAIL_NOT_CONFIRMED_MESSAGE,
|
|
151
|
+
})
|
|
152
|
+
}
|
|
153
|
+
if (paymentsReceivable === false) {
|
|
154
|
+
notices.push({
|
|
155
|
+
code: "payments_not_receivable",
|
|
156
|
+
level: "error",
|
|
157
|
+
message: PAYMENTS_NOT_RECEIVABLE_MESSAGE,
|
|
158
|
+
})
|
|
159
|
+
}
|
|
160
|
+
if (!paypalPayments.enabled) {
|
|
161
|
+
notices.push({
|
|
162
|
+
code: "paypal_payments_not_enabled",
|
|
163
|
+
level: "error",
|
|
164
|
+
message: notEnabledMessage("PayPal payments", paypalPayments),
|
|
165
|
+
})
|
|
166
|
+
}
|
|
167
|
+
if (!cardPayments.enabled) {
|
|
168
|
+
notices.push({
|
|
169
|
+
code: "card_payments_not_enabled",
|
|
170
|
+
// Cards are an optional extra on top of PayPal payments.
|
|
171
|
+
level: "warning",
|
|
172
|
+
message: notEnabledMessage(
|
|
173
|
+
"Advanced Credit and Debit Card payments",
|
|
174
|
+
cardPayments
|
|
175
|
+
),
|
|
176
|
+
})
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
return {
|
|
180
|
+
merchant_id: String(details.merchant_id || "").trim() || null,
|
|
181
|
+
payments_receivable: paymentsReceivable,
|
|
182
|
+
primary_email_confirmed: emailConfirmed,
|
|
183
|
+
paypal_payments: paypalPayments,
|
|
184
|
+
card_payments: cardPayments,
|
|
185
|
+
notices,
|
|
186
|
+
}
|
|
187
|
+
}
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { createHash } from "crypto"
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Pieces of the Create Order payload (`POST /v2/checkout/orders`) that are
|
|
5
|
+
* worth testing on their own: the PayPal landing page and the shipping
|
|
6
|
+
* address sent with `shipping_preference: SET_PROVIDED_ADDRESS`.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export type PayPalLandingPage = "LOGIN" | "GUEST_CHECKOUT"
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* `payment_source.paypal.experience_context.landing_page` for the admin
|
|
13
|
+
* "Landing Page" setting.
|
|
14
|
+
*
|
|
15
|
+
* `LOGIN` is the default PayPal's partner review asks for. A stored
|
|
16
|
+
* "no_preference" (the admin default before 1.3.9) is treated as `LOGIN` too.
|
|
17
|
+
* "billing" selects PayPal's guest (card) checkout page, which
|
|
18
|
+
* `experience_context` calls `GUEST_CHECKOUT` — `BILLING` was its name in the
|
|
19
|
+
* deprecated `application_context`.
|
|
20
|
+
*/
|
|
21
|
+
export function resolveLandingPage(setting: unknown): PayPalLandingPage {
|
|
22
|
+
const value = String(setting ?? "")
|
|
23
|
+
.trim()
|
|
24
|
+
.toLowerCase()
|
|
25
|
+
return value === "billing" || value === "guest_checkout"
|
|
26
|
+
? "GUEST_CHECKOUT"
|
|
27
|
+
: "LOGIN"
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export type CartShippingAddress = {
|
|
31
|
+
first_name?: string | null
|
|
32
|
+
last_name?: string | null
|
|
33
|
+
address_1?: string | null
|
|
34
|
+
address_2?: string | null
|
|
35
|
+
city?: string | null
|
|
36
|
+
province?: string | null
|
|
37
|
+
postal_code?: string | null
|
|
38
|
+
country_code?: string | null
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export type PayPalShipping = {
|
|
42
|
+
name?: { full_name: string }
|
|
43
|
+
address: {
|
|
44
|
+
address_line_1: string
|
|
45
|
+
address_line_2?: string
|
|
46
|
+
admin_area_2?: string
|
|
47
|
+
admin_area_1?: string
|
|
48
|
+
postal_code: string
|
|
49
|
+
country_code: string
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function text(value: unknown): string {
|
|
54
|
+
return String(value ?? "").trim()
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Medusa stores a province either as the buyer typed it or as an ISO 3166-2
|
|
59
|
+
* code ("us-ca"). PayPal wants the subdivision without the country prefix
|
|
60
|
+
* ("CA").
|
|
61
|
+
*/
|
|
62
|
+
function normalizeProvince(province: string, country: string): string {
|
|
63
|
+
const match = province.match(/^([a-z]{2})-([a-z0-9]{1,3})$/i)
|
|
64
|
+
if (match && match[1].toUpperCase() === country) {
|
|
65
|
+
return match[2].toUpperCase()
|
|
66
|
+
}
|
|
67
|
+
return province
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* The cart's shipping address as a PayPal `purchase_units[].shipping` object,
|
|
72
|
+
* or null when the cart has no address PayPal would accept (it rejects an
|
|
73
|
+
* address without a street line, postal code or two-letter country).
|
|
74
|
+
*/
|
|
75
|
+
export function buildPayPalShipping(
|
|
76
|
+
addr: CartShippingAddress | null | undefined
|
|
77
|
+
): PayPalShipping | null {
|
|
78
|
+
if (!addr) return null
|
|
79
|
+
const line1 = text(addr.address_1)
|
|
80
|
+
const postal = text(addr.postal_code)
|
|
81
|
+
const country = text(addr.country_code).toUpperCase()
|
|
82
|
+
if (!line1 || !postal || country.length !== 2) return null
|
|
83
|
+
|
|
84
|
+
const fullName = [addr.first_name, addr.last_name]
|
|
85
|
+
.map(text)
|
|
86
|
+
.filter(Boolean)
|
|
87
|
+
.join(" ")
|
|
88
|
+
const line2 = text(addr.address_2)
|
|
89
|
+
const city = text(addr.city)
|
|
90
|
+
const province = normalizeProvince(text(addr.province), country)
|
|
91
|
+
|
|
92
|
+
return {
|
|
93
|
+
...(fullName ? { name: { full_name: fullName.slice(0, 300) } } : {}),
|
|
94
|
+
address: {
|
|
95
|
+
address_line_1: line1.slice(0, 300),
|
|
96
|
+
...(line2 ? { address_line_2: line2.slice(0, 300) } : {}),
|
|
97
|
+
...(city ? { admin_area_2: city.slice(0, 120) } : {}),
|
|
98
|
+
...(province ? { admin_area_1: province.slice(0, 300) } : {}),
|
|
99
|
+
postal_code: postal.slice(0, 60),
|
|
100
|
+
country_code: country,
|
|
101
|
+
},
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function comparable(shipping: unknown): string {
|
|
106
|
+
const s = (shipping && typeof shipping === "object" ? shipping : {}) as any
|
|
107
|
+
const a = (s.address && typeof s.address === "object" ? s.address : {}) as any
|
|
108
|
+
return [
|
|
109
|
+
s.name?.full_name,
|
|
110
|
+
a.address_line_1,
|
|
111
|
+
a.address_line_2,
|
|
112
|
+
a.admin_area_2,
|
|
113
|
+
a.admin_area_1,
|
|
114
|
+
a.postal_code,
|
|
115
|
+
a.country_code,
|
|
116
|
+
]
|
|
117
|
+
.map((part) => text(part).toLowerCase().replace(/\s+/g, " "))
|
|
118
|
+
.join("|")
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** True when two PayPal shipping objects describe the same recipient/address. */
|
|
122
|
+
export function sameShipping(a: unknown, b: unknown): boolean {
|
|
123
|
+
return comparable(a) === comparable(b)
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Short stable fingerprint of a shipping object, for the PayPal-Request-Id:
|
|
128
|
+
* PayPal replays the stored response for a repeated request id, so an order
|
|
129
|
+
* for the same cart and amount but a different address needs a different id.
|
|
130
|
+
*/
|
|
131
|
+
export function shippingFingerprint(shipping: unknown): string {
|
|
132
|
+
return createHash("sha256")
|
|
133
|
+
.update(comparable(shipping))
|
|
134
|
+
.digest("hex")
|
|
135
|
+
.slice(0, 8)
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Whether PayPal rejected a Create Order request because of the shipping
|
|
140
|
+
* address we sent (so the order can be retried without it instead of failing
|
|
141
|
+
* the checkout).
|
|
142
|
+
*/
|
|
143
|
+
export function isShippingAddressRejection(
|
|
144
|
+
status: number,
|
|
145
|
+
responseText: string
|
|
146
|
+
): boolean {
|
|
147
|
+
if (status !== 400 && status !== 422) return false
|
|
148
|
+
let json: any
|
|
149
|
+
try {
|
|
150
|
+
json = JSON.parse(responseText)
|
|
151
|
+
} catch {
|
|
152
|
+
return false
|
|
153
|
+
}
|
|
154
|
+
const details = Array.isArray(json?.details) ? json.details : []
|
|
155
|
+
return details.some((detail: any) => {
|
|
156
|
+
const field = String(detail?.field || "")
|
|
157
|
+
const issue = String(detail?.issue || "")
|
|
158
|
+
return (
|
|
159
|
+
/\/shipping(\/|$)/i.test(field) ||
|
|
160
|
+
/SHIPPING_ADDRESS|MISSING_SHIPPING/i.test(issue)
|
|
161
|
+
)
|
|
162
|
+
})
|
|
163
|
+
}
|