@easypayment/medusa-payment-paypal 1.1.2 → 1.2.0

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 (68) hide show
  1. package/.medusa/server/src/admin/index.js +72 -72
  2. package/.medusa/server/src/admin/index.mjs +72 -72
  3. package/.medusa/server/src/api/middlewares.d.ts.map +1 -1
  4. package/.medusa/server/src/api/middlewares.js +16 -2
  5. package/.medusa/server/src/api/middlewares.js.map +1 -1
  6. package/.medusa/server/src/api/store/paypal/capture-order/route.d.ts.map +1 -1
  7. package/.medusa/server/src/api/store/paypal/capture-order/route.js +66 -13
  8. package/.medusa/server/src/api/store/paypal/capture-order/route.js.map +1 -1
  9. package/.medusa/server/src/api/store/paypal/create-order/route.d.ts.map +1 -1
  10. package/.medusa/server/src/api/store/paypal/create-order/route.js +11 -6
  11. package/.medusa/server/src/api/store/paypal/create-order/route.js.map +1 -1
  12. package/.medusa/server/src/api/utils/rate-limit.d.ts +13 -1
  13. package/.medusa/server/src/api/utils/rate-limit.d.ts.map +1 -1
  14. package/.medusa/server/src/api/utils/rate-limit.js +7 -5
  15. package/.medusa/server/src/api/utils/rate-limit.js.map +1 -1
  16. package/.medusa/server/src/jobs/paypal-webhook-retry.d.ts.map +1 -1
  17. package/.medusa/server/src/jobs/paypal-webhook-retry.js +4 -0
  18. package/.medusa/server/src/jobs/paypal-webhook-retry.js.map +1 -1
  19. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.d.ts +15 -0
  20. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.d.ts.map +1 -1
  21. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.js +26 -0
  22. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.js.map +1 -1
  23. package/.medusa/server/src/modules/paypal/payment-provider/card-service.d.ts.map +1 -1
  24. package/.medusa/server/src/modules/paypal/payment-provider/card-service.js +244 -169
  25. package/.medusa/server/src/modules/paypal/payment-provider/card-service.js.map +1 -1
  26. package/.medusa/server/src/modules/paypal/payment-provider/service.d.ts +0 -4
  27. package/.medusa/server/src/modules/paypal/payment-provider/service.d.ts.map +1 -1
  28. package/.medusa/server/src/modules/paypal/payment-provider/service.js +8 -25
  29. package/.medusa/server/src/modules/paypal/payment-provider/service.js.map +1 -1
  30. package/.medusa/server/src/modules/paypal/service.d.ts +2 -0
  31. package/.medusa/server/src/modules/paypal/service.d.ts.map +1 -1
  32. package/.medusa/server/src/modules/paypal/service.js +54 -13
  33. package/.medusa/server/src/modules/paypal/service.js.map +1 -1
  34. package/.medusa/server/src/modules/paypal/types/config.d.ts.map +1 -1
  35. package/.medusa/server/src/modules/paypal/types/config.js +13 -0
  36. package/.medusa/server/src/modules/paypal/types/config.js.map +1 -1
  37. package/.medusa/server/src/modules/paypal/utils/amounts.d.ts +1 -1
  38. package/.medusa/server/src/modules/paypal/utils/credential-resolver.d.ts.map +1 -1
  39. package/.medusa/server/src/modules/paypal/utils/credential-resolver.js +10 -34
  40. package/.medusa/server/src/modules/paypal/utils/credential-resolver.js.map +1 -1
  41. package/.medusa/server/src/modules/paypal/utils/metrics.d.ts +18 -0
  42. package/.medusa/server/src/modules/paypal/utils/metrics.d.ts.map +1 -0
  43. package/.medusa/server/src/modules/paypal/utils/metrics.js +45 -0
  44. package/.medusa/server/src/modules/paypal/utils/metrics.js.map +1 -0
  45. package/.medusa/server/src/modules/paypal/webhook-processor.d.ts +16 -0
  46. package/.medusa/server/src/modules/paypal/webhook-processor.d.ts.map +1 -1
  47. package/.medusa/server/src/modules/paypal/webhook-processor.js +85 -2
  48. package/.medusa/server/src/modules/paypal/webhook-processor.js.map +1 -1
  49. package/.medusa/server/src/subscribers/paypal-webhook-process.d.ts.map +1 -1
  50. package/.medusa/server/src/subscribers/paypal-webhook-process.js +4 -0
  51. package/.medusa/server/src/subscribers/paypal-webhook-process.js.map +1 -1
  52. package/CHANGELOG.md +208 -146
  53. package/README.md +175 -184
  54. package/package.json +91 -88
  55. package/src/api/middlewares.ts +16 -2
  56. package/src/api/store/paypal/capture-order/route.ts +83 -12
  57. package/src/api/store/paypal/create-order/route.ts +11 -7
  58. package/src/api/utils/rate-limit.ts +20 -5
  59. package/src/jobs/paypal-webhook-retry.ts +4 -0
  60. package/src/modules/paypal/payment-provider/base-provider.ts +31 -0
  61. package/src/modules/paypal/payment-provider/card-service.ts +84 -0
  62. package/src/modules/paypal/payment-provider/service.ts +12 -30
  63. package/src/modules/paypal/service.ts +1703 -1651
  64. package/src/modules/paypal/types/config.ts +16 -0
  65. package/src/modules/paypal/utils/credential-resolver.ts +9 -36
  66. package/src/modules/paypal/utils/metrics.ts +48 -0
  67. package/src/modules/paypal/webhook-processor.ts +101 -2
  68. package/src/subscribers/paypal-webhook-process.ts +4 -0
@@ -1,1651 +1,1703 @@
1
- import { MedusaService } from "@medusajs/framework/utils"
2
- import { paypalFetch } from "./utils/paypal-fetch"
3
- import { decryptSecret, encryptSecret } from "./utils/secret-crypto"
4
- import PayPalConnection from "./models/paypal_connection"
5
- import PayPalMetric from "./models/paypal_metric"
6
- import PayPalSettings from "./models/paypal_settings"
7
- import PayPalWebhookEvent from "./models/paypal_webhook_event"
8
- import { getPayPalConfig } from "./types/config"
9
- import { normalizeCurrencyCode } from "./utils/currencies"
10
-
11
- type Environment = "sandbox" | "live"
12
-
13
- type Status =
14
- | "disconnected"
15
- | "pending"
16
- | "pending_credentials"
17
- | "connected"
18
- | "revoked"
19
-
20
- const SENSITIVE_KEY_RE =
21
- /secret|password|client_secret|access_token|refresh_token|authorization|auth_code|api[_-]?key/i
22
-
23
- /**
24
- * Defensive redaction for audit logs: replace values of keys that look
25
- * sensitive with "[REDACTED]". Bounded depth/breadth so a pathological payload
26
- * can't blow up logging.
27
- */
28
- function redactSensitive(value: unknown, depth = 0): unknown {
29
- if (depth > 6 || value === null || typeof value !== "object") {
30
- return value
31
- }
32
- if (Array.isArray(value)) {
33
- return value.slice(0, 50).map((v) => redactSensitive(v, depth + 1))
34
- }
35
- const out: Record<string, unknown> = {}
36
- for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
37
- out[k] = SENSITIVE_KEY_RE.test(k) ? "[REDACTED]" : redactSensitive(v, depth + 1)
38
- }
39
- return out
40
- }
41
-
42
- class PayPalModuleService extends MedusaService({
43
- PayPalConnection,
44
- PayPalMetric,
45
- PayPalSettings,
46
- PayPalWebhookEvent,
47
- }) {
48
- protected cfg = getPayPalConfig()
49
- private tokenRefreshPromise: Promise<string> | null = null
50
-
51
- private get bnCode(): string {
52
- return this.cfg.bnCode || "MBJTechnolabs_SI_SPB"
53
- }
54
-
55
- private async getSettingsData() {
56
- const settings = await this.getSettings()
57
- return (settings?.data || {}) as Record<string, any>
58
- }
59
-
60
- private async ensureSettingsDefaults() {
61
- const data = await this.getSettingsData()
62
- const onboarding = { ...(data.onboarding_config || {}) } as Record<string, any>
63
- const apiDetails = { ...(data.api_details || {}) } as Record<string, any>
64
- let changed = false
65
-
66
- if (!onboarding.partner_service_url) {
67
- onboarding.partner_service_url = this.cfg.partnerServiceUrl
68
- changed = true
69
- }
70
- if (!onboarding.partner_js_url) {
71
- onboarding.partner_js_url = this.cfg.partnerJsUrl
72
- changed = true
73
- }
74
- if (!onboarding.backend_url) {
75
- onboarding.backend_url = this.cfg.backendUrl
76
- changed = true
77
- }
78
- if (!onboarding.seller_nonce) {
79
- onboarding.seller_nonce = this.cfg.sellerNonce
80
- changed = true
81
- }
82
- if (!onboarding.bn_code && this.cfg.bnCode) {
83
- onboarding.bn_code = this.cfg.bnCode
84
- changed = true
85
- }
86
- if (!onboarding.partner_merchant_id_sandbox) {
87
- onboarding.partner_merchant_id_sandbox = this.cfg.partnerMerchantIdSandbox
88
- changed = true
89
- }
90
- if (!onboarding.partner_merchant_id_live) {
91
- onboarding.partner_merchant_id_live = this.cfg.partnerMerchantIdLive
92
- changed = true
93
- }
94
-
95
- if (!apiDetails.currency_code) {
96
- const raw = (process.env.PAYPAL_CURRENCY || "").trim()
97
- apiDetails.currency_code = raw ? normalizeCurrencyCode(raw) : "EUR"
98
- changed = true
99
- }
100
- if (!apiDetails.storefront_url) {
101
- const storeUrl = process.env.STOREFRONT_URL || process.env.STORE_URL
102
- if (storeUrl) {
103
- apiDetails.storefront_url = storeUrl
104
- changed = true
105
- }
106
- }
107
-
108
- if (changed) {
109
- await this.saveSettings({
110
- onboarding_config: onboarding,
111
- api_details: apiDetails,
112
- })
113
- }
114
-
115
- return { onboarding, apiDetails }
116
- }
117
-
118
- async getApiDetails() {
119
- const { onboarding, apiDetails } = await this.ensureSettingsDefaults()
120
- return {
121
- onboarding,
122
- apiDetails,
123
- }
124
- }
125
-
126
- private getAlertWebhookUrls() {
127
- return (this.cfg.alertWebhookUrls || []).map((url) => url.trim()).filter(Boolean)
128
- }
129
-
130
- private async getPartnerMerchantId(env: Environment) {
131
- const { onboarding } = await this.ensureSettingsDefaults()
132
- return env === "live" ? onboarding.partner_merchant_id_live : onboarding.partner_merchant_id_sandbox
133
- }
134
-
135
- private async getCurrentRow(): Promise<any | null> {
136
- const rows = await this.listPayPalConnections(
137
- {},
138
- { take: 1, order: { created_at: "DESC" } }
139
- )
140
- return rows?.[0] ?? null
141
- }
142
-
143
- private async getCurrentEnvironment(): Promise<Environment> {
144
- try {
145
- const row = await this.getCurrentRow()
146
- const env = (row?.environment as Environment) || "live"
147
- return env === "sandbox" ? "sandbox" : "live"
148
- } catch {
149
- return "live"
150
- }
151
- }
152
-
153
- private getEnvCreds(
154
- row: any,
155
- env: Environment
156
- ): { clientId?: string; clientSecret?: string; sellerMerchantId?: string; sellerEmail?: string } {
157
- const meta = (row?.metadata || {}) as any
158
- const creds = meta?.credentials?.[env] || {}
159
- return {
160
- clientId: creds.client_id || creds.clientId || undefined,
161
- // Secrets are encrypted at rest when PAYPAL_ENCRYPTION_KEY is set; decrypt
162
- // here so every consumer (auth, status) sees plaintext. Legacy plaintext
163
- // values pass through unchanged.
164
- clientSecret: decryptSecret(creds.client_secret || creds.clientSecret) || undefined,
165
- sellerMerchantId:
166
- creds.seller_merchant_id ||
167
- creds.sellerMerchantId ||
168
- creds.payer_id ||
169
- creds.merchant_id ||
170
- creds.merchantId ||
171
- undefined,
172
- sellerEmail: creds.seller_email || creds.sellerEmail || undefined,
173
- }
174
- }
175
-
176
- private extractSellerEmail(...candidates: unknown[]): string | null {
177
- const queue = [...candidates]
178
- const seen = new WeakSet<object>()
179
- const MAX_ITERATIONS = 500
180
-
181
- let iterations = 0
182
- while (queue.length > 0 && iterations < MAX_ITERATIONS) {
183
- iterations++
184
- const value = queue.shift()
185
- if (!value) {
186
- continue
187
- }
188
-
189
- if (typeof value === "string") {
190
- const trimmed = value.trim()
191
- if (trimmed && trimmed.includes("@")) {
192
- return trimmed
193
- }
194
- continue
195
- }
196
-
197
- if (typeof value !== "object") {
198
- continue
199
- }
200
-
201
- if (seen.has(value as object)) {
202
- continue
203
- }
204
- seen.add(value as object)
205
-
206
- if (Array.isArray(value)) {
207
- queue.push(...value)
208
- continue
209
- }
210
-
211
- const obj = value as Record<string, unknown>
212
- const prioritized = [
213
- obj.email,
214
- obj.primary_email,
215
- obj.merchant_email,
216
- obj.email_address,
217
- obj.account_email,
218
- obj.contact_email,
219
- obj.value,
220
- obj.address,
221
- ]
222
- queue.push(...prioritized)
223
-
224
- for (const [k, v] of Object.entries(obj)) {
225
- const key = String(k).toLowerCase()
226
- if (key.includes("email") || key.includes("address")) {
227
- queue.push(v)
228
- }
229
- }
230
-
231
- queue.push(...Object.values(obj))
232
- }
233
-
234
- return null
235
- }
236
-
237
- private async fetchMerchantIntegrationDetails(
238
- env: Environment,
239
- merchantId: string,
240
- accessTokenOverride?: string
241
- ) {
242
- const partnerMerchantId = await this.getPartnerMerchantId(env)
243
- if (!partnerMerchantId) {
244
- throw new Error("Missing PayPal partner merchant id configuration.")
245
- }
246
-
247
- const baseUrl = env === "live" ? "https://api-m.paypal.com" : "https://api-m.sandbox.paypal.com"
248
- const accessToken = accessTokenOverride ?? await this.getAppAccessToken()
249
-
250
- const resp = await paypalFetch(
251
- `${baseUrl}/v1/customer/partners/${encodeURIComponent(
252
- partnerMerchantId
253
- )}/merchant-integrations/${encodeURIComponent(merchantId)}`,
254
- {
255
- method: "GET",
256
- headers: {
257
- "Content-Type": "application/json",
258
- Authorization: `Bearer ${accessToken}`,
259
- "PayPal-Partner-Attribution-Id": this.bnCode,
260
- },
261
- }
262
- )
263
-
264
- const text = await resp.text().catch(() => "")
265
- let json: any = {}
266
- try {
267
- json = text ? JSON.parse(text) : {}
268
- } catch (e: any) {
269
- console.warn("[PayPal] Failed to parse response JSON — using empty object:", e?.message)
270
- }
271
-
272
- if (!resp.ok) {
273
- throw new Error(
274
- `PayPal merchant integration lookup failed (${resp.status}): ${text || JSON.stringify(json)}`
275
- )
276
- }
277
-
278
- return json
279
- }
280
-
281
- private async getAppAccessTokenForCredentials(
282
- env: Environment,
283
- credentials: { clientId: string; clientSecret: string }
284
- ) {
285
- const baseUrl = env === "live" ? "https://api-m.paypal.com" : "https://api-m.sandbox.paypal.com"
286
- const basic = Buffer.from(`${credentials.clientId}:${credentials.clientSecret}`).toString("base64")
287
-
288
- const body = new URLSearchParams()
289
- body.set("grant_type", "client_credentials")
290
-
291
- const res = await paypalFetch(`${baseUrl}/v1/oauth2/token`, {
292
- method: "POST",
293
- headers: {
294
- "Content-Type": "application/x-www-form-urlencoded",
295
- Authorization: `Basic ${basic}`,
296
- "PayPal-Partner-Attribution-Id": this.bnCode,
297
- },
298
- body,
299
- })
300
-
301
- const text = await res.text().catch(() => "")
302
- let json: any = {}
303
- try {
304
- json = text ? JSON.parse(text) : {}
305
- } catch (e: any) {
306
- console.warn("[PayPal] Failed to parse app token response JSON:", e?.message)
307
- }
308
-
309
- if (!res.ok) {
310
- throw new Error(`PayPal client_credentials failed (${res.status}): ${text || JSON.stringify(json)}`)
311
- }
312
-
313
- const accessToken = String(json.access_token || "")
314
- if (!accessToken) {
315
- throw new Error("PayPal client_credentials succeeded but access_token is missing.")
316
- }
317
-
318
- return { accessToken, tokenPayload: json }
319
- }
320
-
321
- private async fetchSellerProfileFromDirectCredentials(
322
- env: Environment,
323
- credentials?: { clientId: string; clientSecret: string }
324
- ): Promise<{ sellerMerchantId: string | null; sellerEmail: string | null }> {
325
- const baseUrl = env === "live" ? "https://api-m.paypal.com" : "https://api-m.sandbox.paypal.com"
326
- const partnerMerchantId = await this.getPartnerMerchantId(env)
327
- let tokenPayload: Record<string, any> | null = null
328
-
329
- let accessToken = ""
330
- if (credentials) {
331
- const tokenResp = await this.getAppAccessTokenForCredentials(env, {
332
- clientId: credentials.clientId,
333
- clientSecret: credentials.clientSecret,
334
- })
335
- accessToken = tokenResp.accessToken
336
- tokenPayload = tokenResp.tokenPayload
337
- } else {
338
- accessToken = await this.getAppAccessToken()
339
- }
340
-
341
- let sellerEmail = this.extractSellerEmail(tokenPayload || undefined)
342
- let sellerMerchantId = String(
343
- tokenPayload?.merchant_id || tokenPayload?.payer_id || tokenPayload?.account_id || ""
344
- ).trim() || null
345
-
346
- try {
347
- const userInfoResp = await paypalFetch(`${baseUrl}/v1/identity/oauth2/userinfo?schema=paypalv1`, {
348
- method: "GET",
349
- headers: {
350
- Authorization: `Bearer ${accessToken}`,
351
- "Content-Type": "application/json",
352
- Accept: "application/json",
353
- "PayPal-Partner-Attribution-Id": this.bnCode,
354
- },
355
- })
356
- if (userInfoResp.ok) {
357
- const userInfo = await userInfoResp.json().catch(() => ({}))
358
- sellerEmail = sellerEmail || this.extractSellerEmail(userInfo)
359
- sellerMerchantId =
360
- sellerMerchantId ||
361
- String(userInfo?.merchant_id || userInfo?.payer_id || userInfo?.user_id || userInfo?.sub || "").trim() ||
362
- null
363
- }
364
- } catch (e: any) {
365
- console.warn("[PayPal] userinfo lookup failed:", e?.message || e)
366
- }
367
-
368
- if (partnerMerchantId) {
369
- try {
370
- const credsResp = await paypalFetch(
371
- `${baseUrl}/v1/customer/partners/${encodeURIComponent(
372
- partnerMerchantId
373
- )}/merchant-integrations/credentials/`,
374
- {
375
- method: "GET",
376
- headers: {
377
- Authorization: `Bearer ${accessToken}`,
378
- "Content-Type": "application/json",
379
- "PayPal-Partner-Attribution-Id": this.bnCode,
380
- },
381
- }
382
- )
383
- if (credsResp.ok) {
384
- const credsJson = await credsResp.json().catch(() => ({}))
385
- sellerEmail = sellerEmail || this.extractSellerEmail(credsJson)
386
- sellerMerchantId = sellerMerchantId || String(credsJson?.merchant_id || "").trim() || null
387
- }
388
- } catch (e: any) {
389
- console.warn("[PayPal] direct credential profile lookup failed:", e?.message || e)
390
- }
391
- }
392
-
393
- const hydrated = await this.hydrateSellerMetadataFromCredentials(env, {
394
- accessToken,
395
- sellerMerchantId,
396
- sellerEmail,
397
- })
398
-
399
- return {
400
- sellerMerchantId: hydrated.sellerMerchantId,
401
- sellerEmail: hydrated.sellerEmail,
402
- }
403
- }
404
-
405
- private async hydrateSellerMetadataFromCredentials(
406
- env: Environment,
407
- input: {
408
- accessToken?: string
409
- sellerMerchantId?: string | null
410
- sellerEmail?: string | null
411
- metadataCandidates?: any[]
412
- }
413
- ): Promise<{ sellerMerchantId: string | null; sellerEmail: string | null }> {
414
- let sellerMerchantId = (input.sellerMerchantId || "").trim() || null
415
- let sellerEmail = (input.sellerEmail || "").trim() || null
416
-
417
- if (!sellerEmail && input.metadataCandidates?.length) {
418
- sellerEmail = this.extractSellerEmail(...input.metadataCandidates)
419
- }
420
-
421
- if (sellerMerchantId && !sellerEmail) {
422
- try {
423
- const details = await this.fetchMerchantIntegrationDetails(env, sellerMerchantId, input.accessToken)
424
- sellerEmail = this.extractSellerEmail(details)
425
- } catch (e: any) {
426
- console.warn("[PayPal] merchant integration lookup failed:", e?.message || e)
427
- }
428
- }
429
-
430
- return { sellerMerchantId, sellerEmail }
431
- }
432
-
433
- private async syncRowFieldsFromMetadata(row: any, env: Environment) {
434
- const c = this.getEnvCreds(row, env)
435
- await this.updatePayPalConnections({
436
- id: row.id,
437
- status: c.clientId && c.clientSecret ? "connected" : "disconnected",
438
- seller_client_id: c.clientId || null,
439
- // c.clientSecret is decrypted (from getEnvCreds); re-encrypt for the column.
440
- seller_client_secret: encryptSecret(c.clientSecret) || null,
441
- seller_merchant_id: c.sellerMerchantId || null,
442
- seller_email: c.sellerEmail || null,
443
- metadata: {
444
- ...(row.metadata || {}),
445
- active_environment: env,
446
- },
447
- })
448
- }
449
-
450
- async setEnvironment(env: Environment) {
451
- const nextEnv: Environment = env === "sandbox" ? "sandbox" : "live"
452
- const row = await this.getCurrentRow()
453
- const previousEnv = (row?.environment as Environment) || "live"
454
-
455
- if (!row) {
456
- const created = await this.createPayPalConnections({
457
- environment: nextEnv,
458
- status: "disconnected",
459
- shared_id: null,
460
- auth_code: null,
461
- seller_client_id: null,
462
- seller_client_secret: null,
463
- seller_merchant_id: null,
464
- seller_email: null,
465
- app_access_token: null,
466
- app_access_token_expires_at: null,
467
- metadata: { credentials: {}, active_environment: nextEnv },
468
- })
469
- await this.recordAuditEvent("environment_switched", {
470
- previous_environment: previousEnv,
471
- environment: nextEnv,
472
- })
473
- return created
474
- }
475
-
476
- await this.updatePayPalConnections({
477
- id: row.id,
478
- environment: nextEnv,
479
- app_access_token: null,
480
- app_access_token_expires_at: null,
481
- metadata: {
482
- ...(row.metadata || {}),
483
- active_environment: nextEnv,
484
- },
485
- })
486
-
487
- const updated = await this.getCurrentRow()
488
- if (updated) {
489
- await this.syncRowFieldsFromMetadata(updated, nextEnv)
490
- }
491
-
492
- await this.recordAuditEvent("environment_switched", {
493
- previous_environment: previousEnv,
494
- environment: nextEnv,
495
- })
496
- return await this.getCurrentRow()
497
- }
498
-
499
- async createOnboardingLink(input?: { email?: string; products?: string[]; env?: Environment }) {
500
- const { onboarding } = await this.ensureSettingsDefaults()
501
- // Honor an explicit environment from the caller so the generated link can't
502
- // depend on a racing "set environment" request having landed first.
503
- const env =
504
- input?.env === "sandbox" || input?.env === "live"
505
- ? input.env
506
- : await this.getCurrentEnvironment()
507
- // The popup lands here after onboarding, as a plain top-level navigation with
508
- // no auth token — so it must be the PUBLIC store bridge route, not an
509
- // /admin/* route (which would 401 and leave the popup stuck). The bridge
510
- // exchanges the auth code for seller credentials server-side, relays the
511
- // result to the opener, and closes the popup. We pin the environment in the
512
- // URL so the bridge saves credentials under the correct env even though
513
- // PayPal's redirect carries no auth/session.
514
- // Use the /hooks namespace: Medusa's publishable-key middleware rejects
515
- // unauthenticated top-level navigations to /store/* routes, so the popup
516
- // would land on a NOT_ALLOWED error page instead of the bridge.
517
- const return_url = `${String(onboarding.backend_url || "").replace(/\/$/, "")}/hooks/paypal/onboard-return?env=${env}`
518
- const partner_merchant_id = await this.getPartnerMerchantId(env)
519
-
520
- const email = (input?.email || "").trim()
521
-
522
- if (!partner_merchant_id) {
523
- throw new Error("Missing PAYPAL_PARTNER_MERCHANT_ID_* env for current environment")
524
- }
525
-
526
- const form = new URLSearchParams()
527
- if (email) {
528
- form.set("email", email)
529
- }
530
- form.set("sandbox", env === "live" ? "no" : "yes")
531
- form.set("return_url", return_url)
532
- form.set("return_url_description", "Return to your shop.")
533
- form.set("partner_merchant_id", partner_merchant_id)
534
- form.set("from", "medusa")
535
-
536
- const products = input?.products?.length ? input.products : ["PPCP"]
537
-
538
- products.forEach((p) => {
539
- form.append("products[]", p)
540
- })
541
-
542
- const res = await paypalFetch(onboarding.partner_service_url, {
543
- method: "POST",
544
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
545
- body: form.toString(),
546
- })
547
-
548
- const text = await res.text().catch(() => "")
549
- if (!res.ok) {
550
- throw new Error(`Onboarding service failed (${res.status}): ${text}`)
551
- }
552
-
553
- const trimmed = text.trim()
554
-
555
- if (trimmed.startsWith("http")) {
556
- return { onboarding_url: trimmed, return_url }
557
- }
558
-
559
- let json: any
560
- try {
561
- json = JSON.parse(trimmed)
562
- } catch {
563
- throw new Error(`Invalid onboarding link response (not JSON / URL): ${trimmed.slice(0, 200)}`)
564
- }
565
-
566
- if (json?.body) {
567
- const inner = typeof json.body === "string" ? json.body.trim() : json.body
568
-
569
- if (typeof inner === "string" && inner.startsWith("http")) {
570
- return { onboarding_url: inner, return_url }
571
- }
572
-
573
- try {
574
- json = typeof inner === "string" ? JSON.parse(inner) : inner
575
- } catch {
576
- throw new Error(
577
- `Onboarding wrapper JSON 'body' is not valid JSON / URL: ${
578
- typeof inner === "string" ? inner.slice(0, 200) : "[object]"
579
- }`
580
- )
581
- }
582
- }
583
-
584
- if (json?.name && json?.message && (json?.debug_id || json?.details || json?.links)) {
585
- const debug = json.debug_id ? ` debug_id=${json.debug_id}` : ""
586
- const details = Array.isArray(json.details)
587
- ? json.details
588
- .slice(0, 3)
589
- .map((d: any) => {
590
- const issue = d?.issue ? String(d.issue) : ""
591
- const desc = d?.description ? String(d.description) : ""
592
- const field = d?.field ? String(d.field) : ""
593
- return [issue, desc, field].filter(Boolean).join(" | ")
594
- })
595
- .filter(Boolean)
596
- .join("; ")
597
- : ""
598
-
599
- throw new Error(`PayPal onboarding error: ${json.name}: ${json.message}.${debug}${details ? ` Details: ${details}` : ""}`)
600
- }
601
-
602
- if (json?.onboarding_url && String(json.onboarding_url).startsWith("http")) {
603
- return { onboarding_url: String(json.onboarding_url), return_url }
604
- }
605
-
606
- const links = Array.isArray(json?.links) ? json.links : null
607
- if (links) {
608
- const action = links.find(
609
- (l: any) => l?.rel === "action_url" || l?.rel === "actionUrl" || l?.rel === "action-url"
610
- )
611
- const href = action?.href ? String(action.href) : null
612
- if (href && href.startsWith("http")) {
613
- return { onboarding_url: href, return_url }
614
- }
615
- }
616
-
617
- throw new Error(
618
- `Onboarding JSON missing action_url link. Keys: ${Object.keys(json || {}).join(", ")}`
619
- )
620
- }
621
-
622
- async startOnboarding() {
623
- const row = await this.getCurrentRow()
624
- const env = await this.getCurrentEnvironment()
625
-
626
- if (row) {
627
- await this.updatePayPalConnections({ id: row.id, status: "pending" })
628
- return
629
- }
630
-
631
- await this.createPayPalConnections({
632
- environment: env,
633
- status: "pending",
634
- metadata: {},
635
- })
636
- }
637
-
638
- async saveOnboardCallback(input: { authCode: string; sharedId: string }) {
639
- const row = await this.getCurrentRow()
640
- const env = await this.getCurrentEnvironment()
641
-
642
- if (!row) {
643
- return await this.createPayPalConnections({
644
- environment: env,
645
- status: "pending_credentials",
646
- auth_code: input.authCode,
647
- shared_id: input.sharedId,
648
- metadata: {},
649
- })
650
- }
651
-
652
- return await this.updatePayPalConnections({
653
- id: row.id,
654
- status: "pending_credentials",
655
- auth_code: input.authCode,
656
- shared_id: input.sharedId,
657
- })
658
- }
659
-
660
- async exchangeAndSaveSellerCredentials(input: {
661
- authCode: string
662
- sharedId: string
663
- env?: "sandbox" | "live"
664
- }) {
665
- const env = (input.env || (await this.getCurrentEnvironment())) as Environment
666
-
667
- // Onboarding completion can now arrive via several redundant paths
668
- // (partner.js's onboardingCallback in the opener, the return_url bridge that
669
- // runs inside the popup, and admin status polling). PayPal's authorization
670
- // code is single-use, so a second exchange of the same code would fail with
671
- // invalid_grant. If we already exchanged this exact code and hold seller
672
- // credentials for this environment, treat the duplicate as a success no-op.
673
- const existingRow = await this.getCurrentRow()
674
- if (existingRow && existingRow.auth_code === input.authCode) {
675
- const existingCreds = this.getEnvCreds(existingRow, env)
676
- if (existingCreds.clientId && existingCreds.clientSecret) {
677
- return
678
- }
679
- }
680
-
681
- await this.saveOnboardCallback({ authCode: input.authCode, sharedId: input.sharedId })
682
- const baseUrl = env === "live" ? "https://api-m.paypal.com" : "https://api-m.sandbox.paypal.com"
683
-
684
- const { onboarding } = await this.ensureSettingsDefaults()
685
- const sellerNonce = (onboarding.seller_nonce || "").trim()
686
- if (!sellerNonce) {
687
- throw new Error("PayPal seller nonce is not configured. Set PAYPAL_SELLER_NONCE.")
688
- }
689
-
690
- const tokenBody = new URLSearchParams()
691
- tokenBody.set("grant_type", "authorization_code")
692
- tokenBody.set("code", input.authCode)
693
- tokenBody.set("code_verifier", sellerNonce)
694
-
695
- const basic = Buffer.from(`${input.sharedId}:`).toString("base64")
696
-
697
- const tokenRes = await paypalFetch(`${baseUrl}/v1/oauth2/token`, {
698
- method: "POST",
699
- headers: {
700
- "Content-Type": "application/x-www-form-urlencoded",
701
- Authorization: `Basic ${basic}`,
702
- "PayPal-Partner-Attribution-Id": this.bnCode,
703
- },
704
- body: tokenBody,
705
- })
706
-
707
- const tokenText = await tokenRes.text().catch(() => "")
708
- let tokenJson: any = {}
709
- try {
710
- tokenJson = tokenText ? JSON.parse(tokenText) : {}
711
- } catch (e: any) {
712
- console.warn("[PayPal] Failed to parse token response JSON:", e?.message)
713
- }
714
-
715
- if (!tokenRes.ok) {
716
- // Two redundant completion paths can race to exchange the same single-use
717
- // code; the loser gets invalid_grant. If credentials were saved in the
718
- // meantime (the other path won), the onboarding actually succeeded.
719
- const racedRow = await this.getCurrentRow()
720
- if (racedRow) {
721
- const racedCreds = this.getEnvCreds(racedRow, env)
722
- if (racedCreds.clientId && racedCreds.clientSecret) {
723
- return
724
- }
725
- }
726
- throw new Error(
727
- `PayPal authorization_code token exchange failed (${tokenRes.status}): ${tokenText || JSON.stringify(tokenJson)}`
728
- )
729
- }
730
-
731
- const sellerAccessToken = String(tokenJson.access_token || "")
732
- if (!sellerAccessToken) {
733
- throw new Error("PayPal token exchange succeeded but access_token is missing.")
734
- }
735
-
736
- const partnerMerchantId = await this.getPartnerMerchantId(env)
737
- if (!partnerMerchantId) {
738
- throw new Error("Missing PayPal partner merchant id configuration.")
739
- }
740
-
741
- const credRes = await paypalFetch(
742
- `${baseUrl}/v1/customer/partners/${encodeURIComponent(partnerMerchantId)}/merchant-integrations/credentials/`,
743
- {
744
- method: "GET",
745
- headers: {
746
- "Content-Type": "application/json",
747
- Authorization: `Bearer ${sellerAccessToken}`,
748
- "PayPal-Partner-Attribution-Id": this.bnCode,
749
- },
750
- }
751
- )
752
-
753
- const credText = await credRes.text().catch(() => "")
754
- let credJson: any = {}
755
- try {
756
- credJson = credText ? JSON.parse(credText) : {}
757
- } catch (e: any) {
758
- console.warn("[PayPal] Failed to parse token response JSON:", e?.message)
759
- }
760
-
761
- if (!credRes.ok) {
762
- throw new Error(
763
- `PayPal credentials fetch failed (${credRes.status}): ${credText || JSON.stringify(credJson)}`
764
- )
765
- }
766
-
767
- const clientId = String(credJson.client_id || credJson.clientId || "")
768
- const clientSecret = String(credJson.client_secret || credJson.clientSecret || "")
769
- if (!clientId || !clientSecret) {
770
- throw new Error(
771
- `PayPal credentials response missing client_id/client_secret. Keys: ${Object.keys(credJson || {}).join(", ")}`
772
- )
773
- }
774
-
775
- let sellerEmail = this.extractSellerEmail(credJson, tokenJson)
776
- let sellerMerchantId =
777
- String(credJson.payer_id || credJson.merchant_id || tokenJson.payer_id || tokenJson.merchant_id || "").trim() ||
778
- null
779
-
780
- if (!sellerEmail) {
781
- const merchantCandidates = [
782
- String(credJson.payer_id || "").trim(),
783
- String(credJson.merchant_id || "").trim(),
784
- String(tokenJson.payer_id || "").trim(),
785
- String(tokenJson.merchant_id || "").trim(),
786
- ].filter(Boolean).filter((v, i, arr) => arr.indexOf(v) === i)
787
-
788
- for (const merchantId of merchantCandidates) {
789
- try {
790
- const merchantDetails = await this.fetchMerchantIntegrationDetails(env, merchantId, sellerAccessToken)
791
- sellerMerchantId = sellerMerchantId || merchantId
792
- sellerEmail = this.extractSellerEmail(merchantDetails)
793
- if (sellerEmail) {
794
- break
795
- }
796
- } catch (e: any) {
797
- console.warn(`[PayPal] Merchant integration lookup for ${merchantId} failed:`, e?.message || e)
798
- }
799
- }
800
- }
801
-
802
- await this.saveSellerCredentials({
803
- clientId,
804
- clientSecret,
805
- sellerMerchantId,
806
- sellerEmail,
807
- })
808
-
809
- if (!sellerEmail && sellerMerchantId) {
810
- try {
811
- const appAccessToken = await this.getAppAccessToken()
812
- const details = await this.fetchMerchantIntegrationDetails(env, sellerMerchantId, appAccessToken)
813
- sellerEmail = this.extractSellerEmail(details)
814
- if (sellerEmail) {
815
- await this.saveSellerCredentials({ clientId, clientSecret, sellerMerchantId, sellerEmail })
816
- }
817
- } catch (e: any) {
818
- console.warn("[PayPal] Post-save merchant_id email lookup failed:", e?.message || e)
819
- }
820
- }
821
- }
822
-
823
- async saveSellerCredentials(input: {
824
- clientId: string
825
- clientSecret: string
826
- sellerMerchantId?: string | null
827
- sellerEmail?: string | null
828
- environment?: Environment
829
- }) {
830
- const row = await this.getCurrentRow()
831
- const currentEnv = await this.getCurrentEnvironment()
832
- const env = (input.environment || currentEnv) as Environment
833
-
834
- const existingCreds = row ? this.getEnvCreds(row, env) : {}
835
- const nextSellerMerchantId =
836
- (input.sellerMerchantId || "").trim() || existingCreds.sellerMerchantId || row?.seller_merchant_id || null
837
- const nextSellerEmail =
838
- (input.sellerEmail || "").trim() || existingCreds.sellerEmail || row?.seller_email || null
839
-
840
- // Encrypt once and store the same ciphertext in both the metadata copy and
841
- // the denormalized column (no-op when encryption is disabled).
842
- const storedClientSecret = encryptSecret(input.clientSecret)
843
-
844
- const nextCreds = {
845
- client_id: input.clientId,
846
- client_secret: storedClientSecret,
847
- merchant_id: nextSellerMerchantId,
848
- seller_merchant_id: nextSellerMerchantId,
849
- seller_email: nextSellerEmail,
850
- }
851
-
852
- if (!row) {
853
- const created = await this.createPayPalConnections({
854
- environment: env,
855
- status: "connected",
856
- seller_client_id: input.clientId,
857
- seller_client_secret: storedClientSecret,
858
- seller_merchant_id: nextSellerMerchantId,
859
- seller_email: nextSellerEmail,
860
- app_access_token: null,
861
- app_access_token_expires_at: null,
862
- metadata: {
863
- credentials: {
864
- [env]: nextCreds,
865
- },
866
- active_environment: env,
867
- },
868
- })
869
- await this.recordAuditEvent("credentials_saved", {
870
- environment: env,
871
- client_id: input.clientId,
872
- })
873
- await this.ensureWebhookRegistration()
874
- return created
875
- }
876
-
877
- const meta = (row.metadata || {}) as any
878
- const creds = { ...(meta.credentials || {}) }
879
- creds[env] = {
880
- ...(creds[env] || {}),
881
- ...nextCreds,
882
- }
883
-
884
- const updated = await this.updatePayPalConnections({
885
- id: row.id,
886
- status: "connected",
887
- seller_client_id: input.clientId,
888
- seller_client_secret: storedClientSecret,
889
- seller_merchant_id: nextSellerMerchantId,
890
- seller_email: nextSellerEmail,
891
- app_access_token: null,
892
- app_access_token_expires_at: null,
893
- metadata: {
894
- ...(row.metadata || {}),
895
- credentials: creds,
896
- active_environment: env,
897
- },
898
- })
899
- await this.recordAuditEvent("credentials_saved", {
900
- environment: env,
901
- client_id: input.clientId,
902
- })
903
- await this.ensureWebhookRegistration()
904
- return updated
905
- }
906
-
907
- async saveAndHydrateSellerCredentials(input: {
908
- clientId: string
909
- clientSecret: string
910
- environment?: Environment
911
- }) {
912
- const env = (input.environment || (await this.getCurrentEnvironment())) as Environment
913
-
914
- await this.saveSellerCredentials({
915
- clientId: input.clientId,
916
- clientSecret: input.clientSecret,
917
- environment: env,
918
- })
919
-
920
- try {
921
- const hydrated = await this.fetchSellerProfileFromDirectCredentials(env, {
922
- clientId: input.clientId,
923
- clientSecret: input.clientSecret,
924
- })
925
-
926
- if (hydrated.sellerEmail || hydrated.sellerMerchantId) {
927
- await this.saveSellerCredentials({
928
- clientId: input.clientId,
929
- clientSecret: input.clientSecret,
930
- sellerMerchantId: hydrated.sellerMerchantId,
931
- sellerEmail: hydrated.sellerEmail,
932
- environment: env,
933
- })
934
- }
935
-
936
- const refreshedRow = await this.getCurrentRow()
937
- if (refreshedRow) {
938
- await this.syncRowFieldsFromMetadata(refreshedRow, env)
939
- }
940
- } catch (e: any) {
941
- console.warn("[PayPal] saveAndHydrateSellerCredentials lookup failed:", e?.message || e)
942
- }
943
-
944
- // This is a write context (credentials were just saved), so it is allowed to
945
- // backfill the seller profile if it is still missing.
946
- return await this.getStatus(env, { hydrateMissingProfile: true })
947
- }
948
-
949
- private async resolveWebhookUrl() {
950
- const { onboarding } = await this.ensureSettingsDefaults()
951
- const base = String(onboarding.backend_url || "").replace(/\/$/, "")
952
- if (!base) {
953
- throw new Error("PayPal backend URL is not configured.")
954
- }
955
- // The /hooks namespace has no publishable-key guard. PayPal cannot send
956
- // Medusa's x-publishable-api-key header, so a webhook registered at the
957
- // old /store/paypal/webhook path is rejected before the handler runs.
958
- return `${base}/hooks/paypal/webhook`
959
- }
960
-
961
- /** Legacy webhook path (blocked by Medusa's store publishable-key guard). */
962
- private async resolveLegacyWebhookUrl() {
963
- const { onboarding } = await this.ensureSettingsDefaults()
964
- const base = String(onboarding.backend_url || "").replace(/\/$/, "")
965
- if (!base) return ""
966
- return `${base}/store/paypal/webhook`
967
- }
968
-
969
- private isLocalWebhookUrl(url: string) {
970
- try {
971
- const parsed = new URL(url)
972
- return ["localhost", "127.0.0.1", "::1"].includes(parsed.hostname)
973
- } catch {
974
- return false
975
- }
976
- }
977
-
978
- // Only probe PayPal for a stale legacy webhook URL once per process per
979
- // environment — this runs on admin status reads and must stay cheap.
980
- private webhookUrlMigrationChecked: Record<string, boolean> = {}
981
- private webhookHealScheduled: Record<string, boolean> = {}
982
-
983
- private async migrateLegacyWebhookUrl(env: string, webhookId: string) {
984
- if (this.webhookUrlMigrationChecked[env]) return
985
- this.webhookUrlMigrationChecked[env] = true
986
-
987
- const newUrl = await this.resolveWebhookUrl().catch(() => "")
988
- const legacyUrl = await this.resolveLegacyWebhookUrl()
989
- if (!newUrl || !legacyUrl || this.isLocalWebhookUrl(newUrl)) return
990
-
991
- const accessToken = await this.getAppAccessToken()
992
- const baseUrl =
993
- env === "live" ? "https://api-m.paypal.com" : "https://api-m.sandbox.paypal.com"
994
-
995
- const getResp = await paypalFetch(
996
- `${baseUrl}/v1/notifications/webhooks/${encodeURIComponent(webhookId)}`,
997
- {
998
- headers: {
999
- Authorization: `Bearer ${accessToken}`,
1000
- "Content-Type": "application/json",
1001
- "PayPal-Partner-Attribution-Id": this.bnCode,
1002
- },
1003
- }
1004
- )
1005
- const getJson = await getResp.json().catch(() => ({}))
1006
- if (!getResp.ok) return
1007
-
1008
- const currentUrl = String(getJson?.url || "")
1009
- if (currentUrl !== legacyUrl) return
1010
-
1011
- const patchResp = await paypalFetch(
1012
- `${baseUrl}/v1/notifications/webhooks/${encodeURIComponent(webhookId)}`,
1013
- {
1014
- method: "PATCH",
1015
- headers: {
1016
- Authorization: `Bearer ${accessToken}`,
1017
- "Content-Type": "application/json",
1018
- "PayPal-Partner-Attribution-Id": this.bnCode,
1019
- },
1020
- body: JSON.stringify([
1021
- { op: "replace", path: "/url", value: newUrl },
1022
- ]),
1023
- }
1024
- )
1025
- if (patchResp.ok) {
1026
- await this.recordAuditEvent("webhook_url_migrated", {
1027
- environment: env,
1028
- webhook_id: webhookId,
1029
- from: legacyUrl,
1030
- to: newUrl,
1031
- })
1032
- console.info(
1033
- `[PayPal] migrated webhook ${webhookId} URL from ${legacyUrl} to ${newUrl}`
1034
- )
1035
- }
1036
- }
1037
-
1038
- private async ensureWebhookRegistration() {
1039
- const env = await this.getCurrentEnvironment()
1040
- const { apiDetails } = await this.ensureSettingsDefaults()
1041
- const webhookIds = { ...(apiDetails.webhook_ids || {}) } as Record<string, string>
1042
-
1043
- if (webhookIds[env]) {
1044
- // Existing installs registered the webhook at /store/paypal/webhook,
1045
- // which Medusa's publishable-key middleware blocks for external callers.
1046
- // Migrate the registered URL to /hooks/paypal/webhook in place
1047
- // (best-effort — a failure keeps the stored id and current behavior).
1048
- await this.migrateLegacyWebhookUrl(env, webhookIds[env]).catch((e: any) => {
1049
- console.warn(
1050
- "[PayPal] webhook URL migration check failed:",
1051
- e?.message || e
1052
- )
1053
- })
1054
- return webhookIds[env]
1055
- }
1056
-
1057
- const accessToken = await this.getAppAccessToken()
1058
- const baseUrl = env === "live" ? "https://api-m.paypal.com" : "https://api-m.sandbox.paypal.com"
1059
- const webhookUrl = await this.resolveWebhookUrl()
1060
-
1061
- if (this.isLocalWebhookUrl(webhookUrl)) {
1062
- await this.recordAuditEvent("webhook_skipped_localhost", {
1063
- environment: env,
1064
- webhook_url: webhookUrl,
1065
- })
1066
- return webhookIds[env] || ""
1067
- }
1068
-
1069
- const listResp = await paypalFetch(`${baseUrl}/v1/notifications/webhooks`, {
1070
- headers: {
1071
- Authorization: `Bearer ${accessToken}`,
1072
- "Content-Type": "application/json",
1073
- "PayPal-Partner-Attribution-Id": this.bnCode,
1074
- },
1075
- })
1076
-
1077
- const listJson = await listResp.json().catch(() => ({}))
1078
- if (!listResp.ok) {
1079
- throw new Error(`PayPal webhook list failed (${listResp.status}): ${JSON.stringify(listJson)}`)
1080
- }
1081
-
1082
- const existing = Array.isArray(listJson?.webhooks)
1083
- ? listJson.webhooks.find((hook: any) => hook?.url === webhookUrl)
1084
- : null
1085
-
1086
- let webhookId = existing?.id ? String(existing.id) : ""
1087
-
1088
- if (!webhookId) {
1089
- const createResp = await paypalFetch(`${baseUrl}/v1/notifications/webhooks`, {
1090
- method: "POST",
1091
- headers: {
1092
- Authorization: `Bearer ${accessToken}`,
1093
- "Content-Type": "application/json",
1094
- "PayPal-Partner-Attribution-Id": this.bnCode,
1095
- },
1096
- body: JSON.stringify({
1097
- url: webhookUrl,
1098
- event_types: [
1099
- { name: "CHECKOUT.ORDER.APPROVED" },
1100
- { name: "CHECKOUT.ORDER.CANCELLED" },
1101
- { name: "PAYMENT.CAPTURE.COMPLETED" },
1102
- { name: "PAYMENT.CAPTURE.DENIED" },
1103
- { name: "PAYMENT.CAPTURE.REFUNDED" },
1104
- { name: "PAYMENT.CAPTURE.REVERSED" },
1105
- { name: "PAYMENT.AUTHORIZATION.CREATED" },
1106
- { name: "PAYMENT.AUTHORIZATION.VOIDED" },
1107
- { name: "PAYMENT.AUTHORIZATION.DENIED" },
1108
- { name: "PAYMENT.REFUND.COMPLETED" },
1109
- { name: "PAYMENT.REFUND.DENIED" },
1110
- ],
1111
- }),
1112
- })
1113
-
1114
- const createJson = await createResp.json().catch(() => ({}))
1115
- if (!createResp.ok) {
1116
- throw new Error(
1117
- `PayPal webhook create failed (${createResp.status}): ${JSON.stringify(createJson)}`
1118
- )
1119
- }
1120
-
1121
- webhookId = String(createJson?.id || "")
1122
- }
1123
-
1124
- if (!webhookId) {
1125
- throw new Error("PayPal webhook registration did not return an id")
1126
- }
1127
-
1128
- const nextWebhookIds = { ...webhookIds, [env]: webhookId }
1129
- await this.saveSettings({
1130
- api_details: {
1131
- ...apiDetails,
1132
- webhook_ids: nextWebhookIds,
1133
- },
1134
- })
1135
-
1136
- await this.recordAuditEvent("webhook_registered", {
1137
- environment: env,
1138
- webhook_id: webhookId,
1139
- webhook_url: webhookUrl,
1140
- })
1141
-
1142
- return webhookId
1143
- }
1144
-
1145
- private maskValue(value?: string | null, visibleChars = 4) {
1146
- if (!value) return null
1147
- const trimmed = String(value)
1148
- if (trimmed.length <= visibleChars) {
1149
- return "•".repeat(trimmed.length)
1150
- }
1151
- return `${"•".repeat(Math.max(0, trimmed.length - visibleChars))}${trimmed.slice(
1152
- -visibleChars
1153
- )}`
1154
- }
1155
-
1156
- /**
1157
- * Report the current connection status.
1158
- *
1159
- * `hydrateMissingProfile` is opt-in and OFF by default: status is read on
1160
- * `GET /admin/paypal/status` (and other read-only routes), where it must be a
1161
- * safe, side-effect-free read. The seller-profile backfill makes an outbound
1162
- * PayPal call and persists to the DB, so it only runs from write contexts
1163
- * (e.g. saving credentials) that explicitly request it.
1164
- */
1165
- async getStatus(
1166
- envOverride?: Environment,
1167
- opts: { hydrateMissingProfile?: boolean } = {}
1168
- ) {
1169
- const row = await this.getCurrentRow()
1170
- const env = envOverride ?? (await this.getCurrentEnvironment())
1171
-
1172
- if (!row) {
1173
- return { environment: env, status: "disconnected" as Status, seller_client_id_present: false }
1174
- }
1175
-
1176
- const c = this.getEnvCreds(row, env)
1177
- const hasCreds = !!(c.clientId && c.clientSecret)
1178
- let sellerEmail: string | null = c.sellerEmail || row.seller_email || null
1179
- let sellerMerchantId: string | null = c.sellerMerchantId || row.seller_merchant_id || null
1180
-
1181
- // Self-heal the webhook registration for already-connected merchants:
1182
- // installs that registered the webhook at the old (blocked)
1183
- // /store/paypal/webhook path get migrated to /hooks/paypal/webhook the
1184
- // first time an admin views the status page after upgrading. Fire and
1185
- // forget — status reads must never block on PayPal, and the migration is
1186
- // throttled to once per process per environment internally.
1187
- if (hasCreds && !this.webhookHealScheduled[env]) {
1188
- this.webhookHealScheduled[env] = true
1189
- void this.ensureWebhookRegistration().catch((e: any) => {
1190
- console.warn("[PayPal] webhook self-heal failed:", e?.message || e)
1191
- })
1192
- }
1193
-
1194
- if (!sellerEmail && hasCreds && opts.hydrateMissingProfile) {
1195
- try {
1196
- const hydrated = await this.fetchSellerProfileFromDirectCredentials(env)
1197
- if (hydrated.sellerEmail || hydrated.sellerMerchantId) {
1198
- await this.saveSellerCredentials({
1199
- clientId: c.clientId!,
1200
- clientSecret: c.clientSecret!,
1201
- sellerMerchantId: hydrated.sellerMerchantId || sellerMerchantId,
1202
- sellerEmail: hydrated.sellerEmail || sellerEmail,
1203
- environment: env,
1204
- })
1205
-
1206
- const refreshedRow = await this.getCurrentRow()
1207
- if (refreshedRow) {
1208
- const refreshedCreds = this.getEnvCreds(refreshedRow, env)
1209
- sellerEmail = refreshedCreds.sellerEmail || refreshedRow.seller_email || sellerEmail
1210
- sellerMerchantId =
1211
- refreshedCreds.sellerMerchantId || refreshedRow.seller_merchant_id || sellerMerchantId
1212
- }
1213
- }
1214
- } catch (e: any) {
1215
- console.warn("[PayPal] status direct credential lookup failed:", e?.message || e)
1216
- }
1217
- }
1218
-
1219
- return {
1220
- environment: env,
1221
- status: (hasCreds ? "connected" : "disconnected") as Status,
1222
- shared_id: row.shared_id ?? null,
1223
- auth_code: row.auth_code ? "***stored***" : null,
1224
- seller_client_id_present: hasCreds,
1225
- seller_client_id_masked: this.maskValue(c.clientId),
1226
- seller_client_secret_masked: c.clientSecret ? "••••••••" : null,
1227
- seller_merchant_id: sellerMerchantId,
1228
- seller_email: sellerEmail,
1229
- updated_at: (row.updated_at as any)?.toISOString?.() ?? null,
1230
- }
1231
- }
1232
-
1233
- async disconnect() {
1234
- const row = await this.getCurrentRow()
1235
- if (!row) return
1236
- const env = await this.getCurrentEnvironment()
1237
-
1238
- const meta = (row.metadata || {}) as any
1239
- const creds = { ...(meta.credentials || {}) }
1240
- delete creds[env]
1241
-
1242
- const hasAnyCreds = Object.values(creds).some((v: any) => {
1243
- return v && typeof v === "object" && (v as any).client_id && (v as any).client_secret
1244
- })
1245
-
1246
- await this.updatePayPalConnections({
1247
- id: row.id,
1248
- status: hasAnyCreds ? "connected" : "disconnected",
1249
- shared_id: null,
1250
- auth_code: null,
1251
- seller_client_id: null,
1252
- seller_client_secret: null,
1253
- seller_merchant_id: null,
1254
- seller_email: null,
1255
- app_access_token: null,
1256
- app_access_token_expires_at: null,
1257
- metadata: {
1258
- ...(row.metadata || {}),
1259
- credentials: creds,
1260
- active_environment: env,
1261
- },
1262
- })
1263
- const updated = await this.getCurrentRow()
1264
- if (updated) {
1265
- await this.syncRowFieldsFromMetadata(updated, env)
1266
- }
1267
- await this.recordAuditEvent("disconnected", { environment: env })
1268
- }
1269
-
1270
- async getAppAccessToken(): Promise<string> {
1271
- const row = await this.getCurrentRow()
1272
-
1273
- if (!row) {
1274
- throw new Error("PayPal connection row not found. Please complete onboarding.")
1275
- }
1276
-
1277
- const expiresAt = row.app_access_token_expires_at ? new Date(row.app_access_token_expires_at as string) : null
1278
- if (row.app_access_token && expiresAt) {
1279
- const msLeft = expiresAt.getTime() - Date.now()
1280
- // Token is encrypted at rest when a key is configured; decrypt the cached
1281
- // value (legacy plaintext passes through unchanged).
1282
- if (msLeft > 2 * 60 * 1000) return decryptSecret(row.app_access_token as string) as string
1283
- }
1284
-
1285
- if (this.tokenRefreshPromise) {
1286
- return this.tokenRefreshPromise
1287
- }
1288
-
1289
- this.tokenRefreshPromise = this.refreshAccessToken(row).finally(() => {
1290
- this.tokenRefreshPromise = null
1291
- })
1292
-
1293
- return this.tokenRefreshPromise
1294
- }
1295
-
1296
- private async refreshAccessToken(row: { id: string }): Promise<string> {
1297
- const env = await this.getCurrentEnvironment()
1298
- const creds = await this.getActiveCredentials()
1299
- const baseUrl = env === "live" ? "https://api-m.paypal.com" : "https://api-m.sandbox.paypal.com"
1300
- const basic = Buffer.from(`${creds.client_id}:${creds.client_secret}`).toString("base64")
1301
-
1302
- const body = new URLSearchParams()
1303
- body.set("grant_type", "client_credentials")
1304
-
1305
- const res = await paypalFetch(`${baseUrl}/v1/oauth2/token`, {
1306
- method: "POST",
1307
- headers: {
1308
- "Content-Type": "application/x-www-form-urlencoded",
1309
- Authorization: `Basic ${basic}`,
1310
- "PayPal-Partner-Attribution-Id": this.bnCode,
1311
- },
1312
- body,
1313
- signal: AbortSignal.timeout(30_000),
1314
- })
1315
-
1316
- const json = await res.json().catch(() => ({}))
1317
- if (!res.ok) throw new Error(`PayPal client_credentials failed (${res.status}): ${JSON.stringify(json)}`)
1318
-
1319
- const accessToken = String(json.access_token || "")
1320
- if (!accessToken) {
1321
- throw new Error("PayPal client_credentials succeeded but access_token is missing.")
1322
- }
1323
- const expiresIn = Number(json.expires_in || 3600)
1324
- const newExpiresAt = new Date(Date.now() + expiresIn * 1000)
1325
-
1326
- await this.updatePayPalConnections({
1327
- id: row.id,
1328
- app_access_token: encryptSecret(accessToken),
1329
- app_access_token_expires_at: newExpiresAt as unknown as Date,
1330
- })
1331
-
1332
- return accessToken
1333
- }
1334
-
1335
- async generateClientToken(opts?: { locale?: string }): Promise<string> {
1336
- const env = await this.getCurrentEnvironment()
1337
- const baseUrl = env === "live" ? "https://api-m.paypal.com" : "https://api-m.sandbox.paypal.com"
1338
-
1339
- const accessToken = await this.getAppAccessToken()
1340
-
1341
- const res = await paypalFetch(`${baseUrl}/v1/identity/generate-token`, {
1342
- method: "POST",
1343
- headers: {
1344
- Authorization: `Bearer ${accessToken}`,
1345
- "Content-Type": "application/json",
1346
- Accept: "application/json",
1347
- "PayPal-Partner-Attribution-Id": this.bnCode,
1348
- ...(opts?.locale ? { "Accept-Language": opts.locale } : {}),
1349
- },
1350
- })
1351
-
1352
- const json = await res.json().catch(() => ({}))
1353
- if (!res.ok) {
1354
- throw new Error(`PayPal generate-token failed (${res.status}): ${JSON.stringify(json)}`)
1355
- }
1356
-
1357
- const token = String((json as any)?.client_token || "")
1358
- if (!token) {
1359
- throw new Error("PayPal client_token is missing in generate-token response")
1360
- }
1361
-
1362
- return token
1363
- }
1364
-
1365
- async getSettings() {
1366
- const rows = await this.listPayPalSettings({}, { take: 1 })
1367
- const row = rows?.[0]
1368
- return { data: (row?.data || {}) as Record<string, any> }
1369
- }
1370
-
1371
- private deepMerge(
1372
- target: Record<string, any>,
1373
- source: Record<string, any>
1374
- ): Record<string, any> {
1375
- const result = { ...target }
1376
- for (const key of Object.keys(source)) {
1377
- const sv = source[key]
1378
- const tv = target[key]
1379
- if (
1380
- sv !== null &&
1381
- typeof sv === "object" &&
1382
- !Array.isArray(sv) &&
1383
- tv !== null &&
1384
- typeof tv === "object" &&
1385
- !Array.isArray(tv)
1386
- ) {
1387
- result[key] = this.deepMerge(tv, sv)
1388
- } else {
1389
- result[key] = sv
1390
- }
1391
- }
1392
- return result
1393
- }
1394
-
1395
- async saveSettings(patch: Record<string, any>) {
1396
- const rows = await this.listPayPalSettings({}, { take: 1 })
1397
- const row = rows?.[0]
1398
- const current = (row?.data || {}) as Record<string, any>
1399
-
1400
- const next = this.deepMerge(current, patch)
1401
-
1402
- if (!row) {
1403
- const created = await this.createPayPalSettings({ data: next })
1404
- return { data: (created.data || {}) as Record<string, any> }
1405
- }
1406
-
1407
- await this.updatePayPalSettings({ id: row.id, data: next })
1408
- return { data: next }
1409
- }
1410
-
1411
- async getActiveCredentials() {
1412
- const row = await this.getCurrentRow()
1413
- const env = await this.getCurrentEnvironment()
1414
-
1415
- if (!row) {
1416
- throw new Error("PayPal connection row not found. Please complete onboarding.")
1417
- }
1418
-
1419
- const c = this.getEnvCreds(row, env)
1420
- const clientSecret = c.clientSecret || ""
1421
-
1422
- if (!c.clientId || !clientSecret) {
1423
- throw new Error(
1424
- `PayPal credentials missing for environment "${env}". Please save credentials.`
1425
- )
1426
- }
1427
-
1428
- return {
1429
- environment: env,
1430
- client_id: c.clientId,
1431
- client_secret: clientSecret,
1432
- }
1433
- }
1434
-
1435
- async getOrderDetails(orderId: string) {
1436
- if (!orderId) {
1437
- throw new Error("PayPal orderId is required")
1438
- }
1439
-
1440
- const env = await this.getCurrentEnvironment()
1441
- const base =
1442
- env === "live"
1443
- ? "https://api-m.paypal.com"
1444
- : "https://api-m.sandbox.paypal.com"
1445
-
1446
- const accessToken = await this.getAppAccessToken()
1447
-
1448
- const resp = await paypalFetch(
1449
- `${base}/v2/checkout/orders/${encodeURIComponent(orderId)}`,
1450
- {
1451
- method: "GET",
1452
- headers: {
1453
- Authorization: `Bearer ${accessToken}`,
1454
- "Content-Type": "application/json",
1455
- "PayPal-Partner-Attribution-Id": this.bnCode,
1456
- },
1457
- signal: AbortSignal.timeout(30_000),
1458
- }
1459
- )
1460
-
1461
- const text = await resp.text()
1462
- if (!resp.ok) {
1463
- throw new Error(`PayPal get order error (${resp.status}): ${text}`)
1464
- }
1465
-
1466
- return JSON.parse(text)
1467
- }
1468
-
1469
- async createWebhookEventRecord(input: {
1470
- event_id: string
1471
- event_type: string
1472
- resource_id?: string | null
1473
- payload?: Record<string, unknown>
1474
- event_version?: string | null
1475
- transmission_id?: string | null
1476
- transmission_time?: Date | null
1477
- status?: string
1478
- attempt_count?: number
1479
- }) {
1480
- try {
1481
- const created = await this.createPayPalWebhookEvents({
1482
- event_id: input.event_id,
1483
- event_type: input.event_type,
1484
- resource_id: input.resource_id ?? null,
1485
- payload: input.payload ?? {},
1486
- event_version: input.event_version ?? null,
1487
- transmission_id: input.transmission_id ?? null,
1488
- transmission_time: input.transmission_time ?? null,
1489
- status: input.status ?? "pending",
1490
- attempt_count: input.attempt_count ?? 0,
1491
- next_retry_at: null,
1492
- processed_at: null,
1493
- last_error: null,
1494
- })
1495
- return { created: true, event: created }
1496
- } catch (error: any) {
1497
- const message = String(error?.message || "")
1498
- const code = String(error?.code || "")
1499
- if (
1500
- message.includes("paypal_webhook_event_event_id_unique") ||
1501
- code === "23505" ||
1502
- (message.includes("unique") && message.includes("event_id"))
1503
- ) {
1504
- const existing = await this.listPayPalWebhookEvents({ event_id: input.event_id })
1505
- return { created: false, event: existing?.[0] ?? null }
1506
- }
1507
- throw error
1508
- }
1509
- }
1510
-
1511
- async updateWebhookEventRecord(input: {
1512
- id: string
1513
- status?: string
1514
- attempt_count?: number
1515
- next_retry_at?: Date | null
1516
- processed_at?: Date | null
1517
- last_error?: string | null
1518
- resource_id?: string | null
1519
- }) {
1520
- return await this.updatePayPalWebhookEvents({
1521
- id: input.id,
1522
- status: input.status,
1523
- attempt_count: input.attempt_count,
1524
- next_retry_at: input.next_retry_at ?? null,
1525
- processed_at: input.processed_at ?? null,
1526
- last_error: input.last_error ?? null,
1527
- resource_id: input.resource_id ?? null,
1528
- })
1529
- }
1530
-
1531
- /**
1532
- * Emit an audit event as a single structured log line.
1533
- *
1534
- * The dedicated audit-log table was removed; for high-volume/containerized
1535
- * deployments the audit trail lives in aggregated stdout logs. This records a
1536
- * greppable `paypal_audit` line (filter on `"log":"paypal_audit"`) with
1537
- * sensitive keys redacted. It never throws — audit logging must not break the
1538
- * caller's payment flow.
1539
- */
1540
- async recordAuditEvent(eventType: string, metadata?: Record<string, unknown>) {
1541
- try {
1542
- console.info(
1543
- JSON.stringify({
1544
- log: "paypal_audit",
1545
- event_type: eventType,
1546
- at: new Date().toISOString(),
1547
- ...(metadata ? { metadata: redactSensitive(metadata) } : {}),
1548
- })
1549
- )
1550
- } catch {
1551
- // never let audit logging interfere with the payment flow
1552
- }
1553
- return null
1554
- }
1555
-
1556
- async recordMetric(name: string, metadata?: Record<string, unknown>) {
1557
- try {
1558
- const existing = await this.listPayPalMetrics({ name })
1559
- const row = existing?.[0]
1560
- const current = (row?.data || {}) as Record<string, any>
1561
- const next = {
1562
- ...current,
1563
- ...(metadata || {}),
1564
- count: Number(current.count || 0) + 1,
1565
- last_recorded_at: new Date().toISOString(),
1566
- }
1567
-
1568
- if (!row) {
1569
- try {
1570
- return await this.createPayPalMetrics({ name, data: next })
1571
- } catch {
1572
- const retry = await this.listPayPalMetrics({ name })
1573
- const retryRow = retry?.[0]
1574
- if (retryRow) {
1575
- const retryData = (retryRow.data || {}) as Record<string, any>
1576
- return await this.updatePayPalMetrics({
1577
- id: retryRow.id,
1578
- name,
1579
- data: {
1580
- ...retryData,
1581
- ...(metadata || {}),
1582
- count: Number(retryData.count || 0) + 1,
1583
- last_recorded_at: new Date().toISOString(),
1584
- },
1585
- })
1586
- }
1587
- throw new Error(`Failed to record metric "${name}"`)
1588
- }
1589
- }
1590
-
1591
- return await this.updatePayPalMetrics({ id: row.id, name, data: next })
1592
- } catch (e: unknown) {
1593
- console.warn("[PayPal] recordMetric failed:", e instanceof Error ? e.message : e)
1594
- return null
1595
- }
1596
- }
1597
-
1598
- async recordPaymentLog(eventType: string, metadata?: Record<string, unknown>) {
1599
- return await this.recordAuditEvent(`payment_${eventType}`, metadata)
1600
- }
1601
-
1602
- async sendAlert(input: {
1603
- type: string
1604
- message: string
1605
- metadata?: Record<string, unknown>
1606
- }) {
1607
- const urls = this.getAlertWebhookUrls()
1608
- if (urls.length === 0) {
1609
- return
1610
- }
1611
-
1612
- const payload = {
1613
- type: input.type,
1614
- message: input.message,
1615
- metadata: input.metadata ?? {},
1616
- source: "paypal",
1617
- timestamp: new Date().toISOString(),
1618
- }
1619
-
1620
- await Promise.all(
1621
- urls.map(async (url) => {
1622
- try {
1623
- const resp = await paypalFetch(url, {
1624
- method: "POST",
1625
- headers: {
1626
- "Content-Type": "application/json",
1627
- },
1628
- body: JSON.stringify(payload),
1629
- })
1630
- if (!resp.ok) {
1631
- const text = await resp.text().catch(() => "")
1632
- await this.recordAuditEvent("alert_failed", {
1633
- url,
1634
- status: resp.status,
1635
- response: text,
1636
- })
1637
- } else {
1638
- await this.recordAuditEvent("alert_sent", { url, type: input.type })
1639
- }
1640
- } catch (error: any) {
1641
- await this.recordAuditEvent("alert_failed", {
1642
- url,
1643
- message: error?.message,
1644
- })
1645
- }
1646
- })
1647
- )
1648
- }
1649
- }
1650
-
1651
- export default PayPalModuleService
1
+ import { MedusaService } from "@medusajs/framework/utils"
2
+ import { recordMetricAtomic } from "./utils/metrics"
3
+ import { paypalFetch } from "./utils/paypal-fetch"
4
+ import { decryptSecret, encryptSecret } from "./utils/secret-crypto"
5
+ import PayPalConnection from "./models/paypal_connection"
6
+ import PayPalMetric from "./models/paypal_metric"
7
+ import PayPalSettings from "./models/paypal_settings"
8
+ import PayPalWebhookEvent from "./models/paypal_webhook_event"
9
+ import { getPayPalConfig } from "./types/config"
10
+ import { getPayPalApiBase } from "./utils/paypal-auth"
11
+ import { normalizeCurrencyCode } from "./utils/currencies"
12
+
13
+ type Environment = "sandbox" | "live"
14
+
15
+ type Status =
16
+ | "disconnected"
17
+ | "pending"
18
+ | "pending_credentials"
19
+ | "connected"
20
+ | "revoked"
21
+
22
+ const SENSITIVE_KEY_RE =
23
+ /secret|password|client_secret|access_token|refresh_token|authorization|auth_code|api[_-]?key/i
24
+
25
+ /**
26
+ * Defensive redaction for audit logs: replace values of keys that look
27
+ * sensitive with "[REDACTED]". Bounded depth/breadth so a pathological payload
28
+ * can't blow up logging.
29
+ */
30
+ function redactSensitive(value: unknown, depth = 0): unknown {
31
+ if (depth > 6 || value === null || typeof value !== "object") {
32
+ return value
33
+ }
34
+ if (Array.isArray(value)) {
35
+ return value.slice(0, 50).map((v) => redactSensitive(v, depth + 1))
36
+ }
37
+ const out: Record<string, unknown> = {}
38
+ for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
39
+ out[k] = SENSITIVE_KEY_RE.test(k) ? "[REDACTED]" : redactSensitive(v, depth + 1)
40
+ }
41
+ return out
42
+ }
43
+
44
+ class PayPalModuleService extends MedusaService({
45
+ PayPalConnection,
46
+ PayPalMetric,
47
+ PayPalSettings,
48
+ PayPalWebhookEvent,
49
+ }) {
50
+ protected cfg = getPayPalConfig()
51
+ private tokenRefreshPromise: Promise<string> | null = null
52
+ // Raw knex connection for the atomic metric upsert; null when the container
53
+ // doesn't expose it (recordMetric then falls back to the ORM path).
54
+ private pgForMetrics: { raw: (sql: string, bindings: unknown[]) => Promise<unknown> } | null =
55
+ null
56
+
57
+ constructor(...args: any[]) {
58
+ // MedusaService's generated constructor signature varies across framework
59
+ // versions — pass everything through untouched.
60
+ super(...args)
61
+ try {
62
+ const cradle = (args[0] || {}) as Record<string, any>
63
+ const pg = cradle.__pg_connection__ ?? cradle.pgConnection ?? null
64
+ this.pgForMetrics = pg && typeof pg.raw === "function" ? pg : null
65
+ } catch {
66
+ this.pgForMetrics = null
67
+ }
68
+ }
69
+
70
+ private get bnCode(): string {
71
+ return this.cfg.bnCode || "MBJTechnolabs_SI_SPB"
72
+ }
73
+
74
+ private async getSettingsData() {
75
+ const settings = await this.getSettings()
76
+ return (settings?.data || {}) as Record<string, any>
77
+ }
78
+
79
+ private async ensureSettingsDefaults() {
80
+ const data = await this.getSettingsData()
81
+ const onboarding = { ...(data.onboarding_config || {}) } as Record<string, any>
82
+ const apiDetails = { ...(data.api_details || {}) } as Record<string, any>
83
+ let changed = false
84
+
85
+ if (!onboarding.partner_service_url) {
86
+ onboarding.partner_service_url = this.cfg.partnerServiceUrl
87
+ changed = true
88
+ }
89
+ if (!onboarding.partner_js_url) {
90
+ onboarding.partner_js_url = this.cfg.partnerJsUrl
91
+ changed = true
92
+ }
93
+ if (!onboarding.backend_url) {
94
+ onboarding.backend_url = this.cfg.backendUrl
95
+ changed = true
96
+ }
97
+ if (!onboarding.seller_nonce) {
98
+ onboarding.seller_nonce = this.cfg.sellerNonce
99
+ changed = true
100
+ }
101
+ if (!onboarding.bn_code && this.cfg.bnCode) {
102
+ onboarding.bn_code = this.cfg.bnCode
103
+ changed = true
104
+ }
105
+ if (!onboarding.partner_merchant_id_sandbox) {
106
+ onboarding.partner_merchant_id_sandbox = this.cfg.partnerMerchantIdSandbox
107
+ changed = true
108
+ }
109
+ if (!onboarding.partner_merchant_id_live) {
110
+ onboarding.partner_merchant_id_live = this.cfg.partnerMerchantIdLive
111
+ changed = true
112
+ }
113
+
114
+ if (!apiDetails.currency_code) {
115
+ const raw = (process.env.PAYPAL_CURRENCY || "").trim()
116
+ apiDetails.currency_code = raw ? normalizeCurrencyCode(raw) : "EUR"
117
+ changed = true
118
+ }
119
+ if (!apiDetails.storefront_url) {
120
+ const storeUrl = process.env.STOREFRONT_URL || process.env.STORE_URL
121
+ if (storeUrl) {
122
+ apiDetails.storefront_url = storeUrl
123
+ changed = true
124
+ }
125
+ }
126
+
127
+ if (changed) {
128
+ await this.saveSettings({
129
+ onboarding_config: onboarding,
130
+ api_details: apiDetails,
131
+ })
132
+ }
133
+
134
+ return { onboarding, apiDetails }
135
+ }
136
+
137
+ async getApiDetails() {
138
+ const { onboarding, apiDetails } = await this.ensureSettingsDefaults()
139
+ return {
140
+ onboarding,
141
+ apiDetails,
142
+ }
143
+ }
144
+
145
+ private getAlertWebhookUrls() {
146
+ return (this.cfg.alertWebhookUrls || []).map((url) => url.trim()).filter(Boolean)
147
+ }
148
+
149
+ private async getPartnerMerchantId(env: Environment) {
150
+ const { onboarding } = await this.ensureSettingsDefaults()
151
+ return env === "live" ? onboarding.partner_merchant_id_live : onboarding.partner_merchant_id_sandbox
152
+ }
153
+
154
+ private async getCurrentRow(): Promise<any | null> {
155
+ const rows = await this.listPayPalConnections(
156
+ {},
157
+ { take: 1, order: { created_at: "DESC" } }
158
+ )
159
+ return rows?.[0] ?? null
160
+ }
161
+
162
+ private async getCurrentEnvironment(): Promise<Environment> {
163
+ try {
164
+ const row = await this.getCurrentRow()
165
+ const env = (row?.environment as Environment) || "live"
166
+ return env === "sandbox" ? "sandbox" : "live"
167
+ } catch {
168
+ return "live"
169
+ }
170
+ }
171
+
172
+ private getEnvCreds(
173
+ row: any,
174
+ env: Environment
175
+ ): { clientId?: string; clientSecret?: string; sellerMerchantId?: string; sellerEmail?: string } {
176
+ const meta = (row?.metadata || {}) as any
177
+ const creds = meta?.credentials?.[env] || {}
178
+ return {
179
+ clientId: creds.client_id || creds.clientId || undefined,
180
+ // Secrets are encrypted at rest when PAYPAL_ENCRYPTION_KEY is set; decrypt
181
+ // here so every consumer (auth, status) sees plaintext. Legacy plaintext
182
+ // values pass through unchanged.
183
+ clientSecret: decryptSecret(creds.client_secret || creds.clientSecret) || undefined,
184
+ sellerMerchantId:
185
+ creds.seller_merchant_id ||
186
+ creds.sellerMerchantId ||
187
+ creds.payer_id ||
188
+ creds.merchant_id ||
189
+ creds.merchantId ||
190
+ undefined,
191
+ sellerEmail: creds.seller_email || creds.sellerEmail || undefined,
192
+ }
193
+ }
194
+
195
+ private extractSellerEmail(...candidates: unknown[]): string | null {
196
+ const queue = [...candidates]
197
+ const seen = new WeakSet<object>()
198
+ const MAX_ITERATIONS = 500
199
+
200
+ let iterations = 0
201
+ while (queue.length > 0 && iterations < MAX_ITERATIONS) {
202
+ iterations++
203
+ const value = queue.shift()
204
+ if (!value) {
205
+ continue
206
+ }
207
+
208
+ if (typeof value === "string") {
209
+ const trimmed = value.trim()
210
+ if (trimmed && trimmed.includes("@")) {
211
+ return trimmed
212
+ }
213
+ continue
214
+ }
215
+
216
+ if (typeof value !== "object") {
217
+ continue
218
+ }
219
+
220
+ if (seen.has(value as object)) {
221
+ continue
222
+ }
223
+ seen.add(value as object)
224
+
225
+ if (Array.isArray(value)) {
226
+ queue.push(...value)
227
+ continue
228
+ }
229
+
230
+ const obj = value as Record<string, unknown>
231
+ const prioritized = [
232
+ obj.email,
233
+ obj.primary_email,
234
+ obj.merchant_email,
235
+ obj.email_address,
236
+ obj.account_email,
237
+ obj.contact_email,
238
+ obj.value,
239
+ obj.address,
240
+ ]
241
+ queue.push(...prioritized)
242
+
243
+ for (const [k, v] of Object.entries(obj)) {
244
+ const key = String(k).toLowerCase()
245
+ if (key.includes("email") || key.includes("address")) {
246
+ queue.push(v)
247
+ }
248
+ }
249
+
250
+ queue.push(...Object.values(obj))
251
+ }
252
+
253
+ return null
254
+ }
255
+
256
+ private async fetchMerchantIntegrationDetails(
257
+ env: Environment,
258
+ merchantId: string,
259
+ accessTokenOverride?: string
260
+ ) {
261
+ const partnerMerchantId = await this.getPartnerMerchantId(env)
262
+ if (!partnerMerchantId) {
263
+ throw new Error("Missing PayPal partner merchant id configuration.")
264
+ }
265
+
266
+ const baseUrl = getPayPalApiBase(env)
267
+ const accessToken = accessTokenOverride ?? await this.getAppAccessToken()
268
+
269
+ const resp = await paypalFetch(
270
+ `${baseUrl}/v1/customer/partners/${encodeURIComponent(
271
+ partnerMerchantId
272
+ )}/merchant-integrations/${encodeURIComponent(merchantId)}`,
273
+ {
274
+ method: "GET",
275
+ headers: {
276
+ "Content-Type": "application/json",
277
+ Authorization: `Bearer ${accessToken}`,
278
+ "PayPal-Partner-Attribution-Id": this.bnCode,
279
+ },
280
+ }
281
+ )
282
+
283
+ const text = await resp.text().catch(() => "")
284
+ let json: any = {}
285
+ try {
286
+ json = text ? JSON.parse(text) : {}
287
+ } catch (e: any) {
288
+ console.warn("[PayPal] Failed to parse response JSON — using empty object:", e?.message)
289
+ }
290
+
291
+ if (!resp.ok) {
292
+ throw new Error(
293
+ `PayPal merchant integration lookup failed (${resp.status}): ${text || JSON.stringify(json)}`
294
+ )
295
+ }
296
+
297
+ return json
298
+ }
299
+
300
+ private async getAppAccessTokenForCredentials(
301
+ env: Environment,
302
+ credentials: { clientId: string; clientSecret: string }
303
+ ) {
304
+ const baseUrl = getPayPalApiBase(env)
305
+ const basic = Buffer.from(`${credentials.clientId}:${credentials.clientSecret}`).toString("base64")
306
+
307
+ const body = new URLSearchParams()
308
+ body.set("grant_type", "client_credentials")
309
+
310
+ const res = await paypalFetch(`${baseUrl}/v1/oauth2/token`, {
311
+ method: "POST",
312
+ headers: {
313
+ "Content-Type": "application/x-www-form-urlencoded",
314
+ Authorization: `Basic ${basic}`,
315
+ "PayPal-Partner-Attribution-Id": this.bnCode,
316
+ },
317
+ body,
318
+ })
319
+
320
+ const text = await res.text().catch(() => "")
321
+ let json: any = {}
322
+ try {
323
+ json = text ? JSON.parse(text) : {}
324
+ } catch (e: any) {
325
+ console.warn("[PayPal] Failed to parse app token response JSON:", e?.message)
326
+ }
327
+
328
+ if (!res.ok) {
329
+ throw new Error(`PayPal client_credentials failed (${res.status}): ${text || JSON.stringify(json)}`)
330
+ }
331
+
332
+ const accessToken = String(json.access_token || "")
333
+ if (!accessToken) {
334
+ throw new Error("PayPal client_credentials succeeded but access_token is missing.")
335
+ }
336
+
337
+ return { accessToken, tokenPayload: json }
338
+ }
339
+
340
+ private async fetchSellerProfileFromDirectCredentials(
341
+ env: Environment,
342
+ credentials?: { clientId: string; clientSecret: string }
343
+ ): Promise<{ sellerMerchantId: string | null; sellerEmail: string | null }> {
344
+ const baseUrl = getPayPalApiBase(env)
345
+ const partnerMerchantId = await this.getPartnerMerchantId(env)
346
+ let tokenPayload: Record<string, any> | null = null
347
+
348
+ let accessToken = ""
349
+ if (credentials) {
350
+ const tokenResp = await this.getAppAccessTokenForCredentials(env, {
351
+ clientId: credentials.clientId,
352
+ clientSecret: credentials.clientSecret,
353
+ })
354
+ accessToken = tokenResp.accessToken
355
+ tokenPayload = tokenResp.tokenPayload
356
+ } else {
357
+ accessToken = await this.getAppAccessToken()
358
+ }
359
+
360
+ let sellerEmail = this.extractSellerEmail(tokenPayload || undefined)
361
+ let sellerMerchantId = String(
362
+ tokenPayload?.merchant_id || tokenPayload?.payer_id || tokenPayload?.account_id || ""
363
+ ).trim() || null
364
+
365
+ try {
366
+ const userInfoResp = await paypalFetch(`${baseUrl}/v1/identity/oauth2/userinfo?schema=paypalv1`, {
367
+ method: "GET",
368
+ headers: {
369
+ Authorization: `Bearer ${accessToken}`,
370
+ "Content-Type": "application/json",
371
+ Accept: "application/json",
372
+ "PayPal-Partner-Attribution-Id": this.bnCode,
373
+ },
374
+ })
375
+ if (userInfoResp.ok) {
376
+ const userInfo = await userInfoResp.json().catch(() => ({}))
377
+ sellerEmail = sellerEmail || this.extractSellerEmail(userInfo)
378
+ sellerMerchantId =
379
+ sellerMerchantId ||
380
+ String(userInfo?.merchant_id || userInfo?.payer_id || userInfo?.user_id || userInfo?.sub || "").trim() ||
381
+ null
382
+ }
383
+ } catch (e: any) {
384
+ console.warn("[PayPal] userinfo lookup failed:", e?.message || e)
385
+ }
386
+
387
+ if (partnerMerchantId) {
388
+ try {
389
+ const credsResp = await paypalFetch(
390
+ `${baseUrl}/v1/customer/partners/${encodeURIComponent(
391
+ partnerMerchantId
392
+ )}/merchant-integrations/credentials/`,
393
+ {
394
+ method: "GET",
395
+ headers: {
396
+ Authorization: `Bearer ${accessToken}`,
397
+ "Content-Type": "application/json",
398
+ "PayPal-Partner-Attribution-Id": this.bnCode,
399
+ },
400
+ }
401
+ )
402
+ if (credsResp.ok) {
403
+ const credsJson = await credsResp.json().catch(() => ({}))
404
+ sellerEmail = sellerEmail || this.extractSellerEmail(credsJson)
405
+ sellerMerchantId = sellerMerchantId || String(credsJson?.merchant_id || "").trim() || null
406
+ }
407
+ } catch (e: any) {
408
+ console.warn("[PayPal] direct credential profile lookup failed:", e?.message || e)
409
+ }
410
+ }
411
+
412
+ const hydrated = await this.hydrateSellerMetadataFromCredentials(env, {
413
+ accessToken,
414
+ sellerMerchantId,
415
+ sellerEmail,
416
+ })
417
+
418
+ return {
419
+ sellerMerchantId: hydrated.sellerMerchantId,
420
+ sellerEmail: hydrated.sellerEmail,
421
+ }
422
+ }
423
+
424
+ private async hydrateSellerMetadataFromCredentials(
425
+ env: Environment,
426
+ input: {
427
+ accessToken?: string
428
+ sellerMerchantId?: string | null
429
+ sellerEmail?: string | null
430
+ metadataCandidates?: any[]
431
+ }
432
+ ): Promise<{ sellerMerchantId: string | null; sellerEmail: string | null }> {
433
+ let sellerMerchantId = (input.sellerMerchantId || "").trim() || null
434
+ let sellerEmail = (input.sellerEmail || "").trim() || null
435
+
436
+ if (!sellerEmail && input.metadataCandidates?.length) {
437
+ sellerEmail = this.extractSellerEmail(...input.metadataCandidates)
438
+ }
439
+
440
+ if (sellerMerchantId && !sellerEmail) {
441
+ try {
442
+ const details = await this.fetchMerchantIntegrationDetails(env, sellerMerchantId, input.accessToken)
443
+ sellerEmail = this.extractSellerEmail(details)
444
+ } catch (e: any) {
445
+ console.warn("[PayPal] merchant integration lookup failed:", e?.message || e)
446
+ }
447
+ }
448
+
449
+ return { sellerMerchantId, sellerEmail }
450
+ }
451
+
452
+ private async syncRowFieldsFromMetadata(row: any, env: Environment) {
453
+ const c = this.getEnvCreds(row, env)
454
+ await this.updatePayPalConnections({
455
+ id: row.id,
456
+ status: c.clientId && c.clientSecret ? "connected" : "disconnected",
457
+ seller_client_id: c.clientId || null,
458
+ // c.clientSecret is decrypted (from getEnvCreds); re-encrypt for the column.
459
+ seller_client_secret: encryptSecret(c.clientSecret) || null,
460
+ seller_merchant_id: c.sellerMerchantId || null,
461
+ seller_email: c.sellerEmail || null,
462
+ metadata: {
463
+ ...(row.metadata || {}),
464
+ active_environment: env,
465
+ },
466
+ })
467
+ }
468
+
469
+ async setEnvironment(env: Environment) {
470
+ const nextEnv: Environment = env === "sandbox" ? "sandbox" : "live"
471
+ const row = await this.getCurrentRow()
472
+ const previousEnv = (row?.environment as Environment) || "live"
473
+
474
+ if (!row) {
475
+ const created = await this.createPayPalConnections({
476
+ environment: nextEnv,
477
+ status: "disconnected",
478
+ shared_id: null,
479
+ auth_code: null,
480
+ seller_client_id: null,
481
+ seller_client_secret: null,
482
+ seller_merchant_id: null,
483
+ seller_email: null,
484
+ app_access_token: null,
485
+ app_access_token_expires_at: null,
486
+ metadata: { credentials: {}, active_environment: nextEnv },
487
+ })
488
+ await this.recordAuditEvent("environment_switched", {
489
+ previous_environment: previousEnv,
490
+ environment: nextEnv,
491
+ })
492
+ return created
493
+ }
494
+
495
+ await this.updatePayPalConnections({
496
+ id: row.id,
497
+ environment: nextEnv,
498
+ app_access_token: null,
499
+ app_access_token_expires_at: null,
500
+ metadata: {
501
+ ...(row.metadata || {}),
502
+ active_environment: nextEnv,
503
+ },
504
+ })
505
+
506
+ const updated = await this.getCurrentRow()
507
+ if (updated) {
508
+ await this.syncRowFieldsFromMetadata(updated, nextEnv)
509
+ }
510
+
511
+ await this.recordAuditEvent("environment_switched", {
512
+ previous_environment: previousEnv,
513
+ environment: nextEnv,
514
+ })
515
+ return await this.getCurrentRow()
516
+ }
517
+
518
+ async createOnboardingLink(input?: { email?: string; products?: string[]; env?: Environment }) {
519
+ const { onboarding } = await this.ensureSettingsDefaults()
520
+ // Honor an explicit environment from the caller so the generated link can't
521
+ // depend on a racing "set environment" request having landed first.
522
+ const env =
523
+ input?.env === "sandbox" || input?.env === "live"
524
+ ? input.env
525
+ : await this.getCurrentEnvironment()
526
+ // The popup lands here after onboarding, as a plain top-level navigation with
527
+ // no auth token — so it must be the PUBLIC store bridge route, not an
528
+ // /admin/* route (which would 401 and leave the popup stuck). The bridge
529
+ // exchanges the auth code for seller credentials server-side, relays the
530
+ // result to the opener, and closes the popup. We pin the environment in the
531
+ // URL so the bridge saves credentials under the correct env even though
532
+ // PayPal's redirect carries no auth/session.
533
+ // Use the /hooks namespace: Medusa's publishable-key middleware rejects
534
+ // unauthenticated top-level navigations to /store/* routes, so the popup
535
+ // would land on a NOT_ALLOWED error page instead of the bridge.
536
+ const return_url = `${String(onboarding.backend_url || "").replace(/\/$/, "")}/hooks/paypal/onboard-return?env=${env}`
537
+ const partner_merchant_id = await this.getPartnerMerchantId(env)
538
+
539
+ const email = (input?.email || "").trim()
540
+
541
+ if (!partner_merchant_id) {
542
+ throw new Error("Missing PAYPAL_PARTNER_MERCHANT_ID_* env for current environment")
543
+ }
544
+
545
+ const form = new URLSearchParams()
546
+ if (email) {
547
+ form.set("email", email)
548
+ }
549
+ form.set("sandbox", env === "live" ? "no" : "yes")
550
+ form.set("return_url", return_url)
551
+ form.set("return_url_description", "Return to your shop.")
552
+ form.set("partner_merchant_id", partner_merchant_id)
553
+ form.set("from", "medusa")
554
+
555
+ const products = input?.products?.length ? input.products : ["PPCP"]
556
+
557
+ products.forEach((p) => {
558
+ form.append("products[]", p)
559
+ })
560
+
561
+ const res = await paypalFetch(onboarding.partner_service_url, {
562
+ method: "POST",
563
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
564
+ body: form.toString(),
565
+ })
566
+
567
+ const text = await res.text().catch(() => "")
568
+ if (!res.ok) {
569
+ throw new Error(`Onboarding service failed (${res.status}): ${text}`)
570
+ }
571
+
572
+ const trimmed = text.trim()
573
+
574
+ if (trimmed.startsWith("http")) {
575
+ return { onboarding_url: trimmed, return_url }
576
+ }
577
+
578
+ let json: any
579
+ try {
580
+ json = JSON.parse(trimmed)
581
+ } catch {
582
+ throw new Error(`Invalid onboarding link response (not JSON / URL): ${trimmed.slice(0, 200)}`)
583
+ }
584
+
585
+ if (json?.body) {
586
+ const inner = typeof json.body === "string" ? json.body.trim() : json.body
587
+
588
+ if (typeof inner === "string" && inner.startsWith("http")) {
589
+ return { onboarding_url: inner, return_url }
590
+ }
591
+
592
+ try {
593
+ json = typeof inner === "string" ? JSON.parse(inner) : inner
594
+ } catch {
595
+ throw new Error(
596
+ `Onboarding wrapper JSON 'body' is not valid JSON / URL: ${
597
+ typeof inner === "string" ? inner.slice(0, 200) : "[object]"
598
+ }`
599
+ )
600
+ }
601
+ }
602
+
603
+ if (json?.name && json?.message && (json?.debug_id || json?.details || json?.links)) {
604
+ const debug = json.debug_id ? ` debug_id=${json.debug_id}` : ""
605
+ const details = Array.isArray(json.details)
606
+ ? json.details
607
+ .slice(0, 3)
608
+ .map((d: any) => {
609
+ const issue = d?.issue ? String(d.issue) : ""
610
+ const desc = d?.description ? String(d.description) : ""
611
+ const field = d?.field ? String(d.field) : ""
612
+ return [issue, desc, field].filter(Boolean).join(" | ")
613
+ })
614
+ .filter(Boolean)
615
+ .join("; ")
616
+ : ""
617
+
618
+ throw new Error(`PayPal onboarding error: ${json.name}: ${json.message}.${debug}${details ? ` Details: ${details}` : ""}`)
619
+ }
620
+
621
+ if (json?.onboarding_url && String(json.onboarding_url).startsWith("http")) {
622
+ return { onboarding_url: String(json.onboarding_url), return_url }
623
+ }
624
+
625
+ const links = Array.isArray(json?.links) ? json.links : null
626
+ if (links) {
627
+ const action = links.find(
628
+ (l: any) => l?.rel === "action_url" || l?.rel === "actionUrl" || l?.rel === "action-url"
629
+ )
630
+ const href = action?.href ? String(action.href) : null
631
+ if (href && href.startsWith("http")) {
632
+ return { onboarding_url: href, return_url }
633
+ }
634
+ }
635
+
636
+ throw new Error(
637
+ `Onboarding JSON missing action_url link. Keys: ${Object.keys(json || {}).join(", ")}`
638
+ )
639
+ }
640
+
641
+ async startOnboarding() {
642
+ const row = await this.getCurrentRow()
643
+ const env = await this.getCurrentEnvironment()
644
+
645
+ if (row) {
646
+ await this.updatePayPalConnections({ id: row.id, status: "pending" })
647
+ return
648
+ }
649
+
650
+ await this.createPayPalConnections({
651
+ environment: env,
652
+ status: "pending",
653
+ metadata: {},
654
+ })
655
+ }
656
+
657
+ async saveOnboardCallback(input: { authCode: string; sharedId: string }) {
658
+ const row = await this.getCurrentRow()
659
+ const env = await this.getCurrentEnvironment()
660
+
661
+ if (!row) {
662
+ return await this.createPayPalConnections({
663
+ environment: env,
664
+ status: "pending_credentials",
665
+ auth_code: input.authCode,
666
+ shared_id: input.sharedId,
667
+ metadata: {},
668
+ })
669
+ }
670
+
671
+ return await this.updatePayPalConnections({
672
+ id: row.id,
673
+ status: "pending_credentials",
674
+ auth_code: input.authCode,
675
+ shared_id: input.sharedId,
676
+ })
677
+ }
678
+
679
+ async exchangeAndSaveSellerCredentials(input: {
680
+ authCode: string
681
+ sharedId: string
682
+ env?: "sandbox" | "live"
683
+ }) {
684
+ const env = (input.env || (await this.getCurrentEnvironment())) as Environment
685
+
686
+ // Onboarding completion can now arrive via several redundant paths
687
+ // (partner.js's onboardingCallback in the opener, the return_url bridge that
688
+ // runs inside the popup, and admin status polling). PayPal's authorization
689
+ // code is single-use, so a second exchange of the same code would fail with
690
+ // invalid_grant. If we already exchanged this exact code and hold seller
691
+ // credentials for this environment, treat the duplicate as a success no-op.
692
+ const existingRow = await this.getCurrentRow()
693
+ if (existingRow && existingRow.auth_code === input.authCode) {
694
+ const existingCreds = this.getEnvCreds(existingRow, env)
695
+ if (existingCreds.clientId && existingCreds.clientSecret) {
696
+ return
697
+ }
698
+ }
699
+
700
+ await this.saveOnboardCallback({ authCode: input.authCode, sharedId: input.sharedId })
701
+ const baseUrl = getPayPalApiBase(env)
702
+
703
+ const { onboarding } = await this.ensureSettingsDefaults()
704
+ const sellerNonce = (onboarding.seller_nonce || "").trim()
705
+ if (!sellerNonce) {
706
+ throw new Error("PayPal seller nonce is not configured. Set PAYPAL_SELLER_NONCE.")
707
+ }
708
+
709
+ const tokenBody = new URLSearchParams()
710
+ tokenBody.set("grant_type", "authorization_code")
711
+ tokenBody.set("code", input.authCode)
712
+ tokenBody.set("code_verifier", sellerNonce)
713
+
714
+ const basic = Buffer.from(`${input.sharedId}:`).toString("base64")
715
+
716
+ const tokenRes = await paypalFetch(`${baseUrl}/v1/oauth2/token`, {
717
+ method: "POST",
718
+ headers: {
719
+ "Content-Type": "application/x-www-form-urlencoded",
720
+ Authorization: `Basic ${basic}`,
721
+ "PayPal-Partner-Attribution-Id": this.bnCode,
722
+ },
723
+ body: tokenBody,
724
+ })
725
+
726
+ const tokenText = await tokenRes.text().catch(() => "")
727
+ let tokenJson: any = {}
728
+ try {
729
+ tokenJson = tokenText ? JSON.parse(tokenText) : {}
730
+ } catch (e: any) {
731
+ console.warn("[PayPal] Failed to parse token response JSON:", e?.message)
732
+ }
733
+
734
+ if (!tokenRes.ok) {
735
+ // Two redundant completion paths can race to exchange the same single-use
736
+ // code; the loser gets invalid_grant. If credentials were saved in the
737
+ // meantime (the other path won), the onboarding actually succeeded.
738
+ const racedRow = await this.getCurrentRow()
739
+ if (racedRow) {
740
+ const racedCreds = this.getEnvCreds(racedRow, env)
741
+ if (racedCreds.clientId && racedCreds.clientSecret) {
742
+ return
743
+ }
744
+ }
745
+ throw new Error(
746
+ `PayPal authorization_code token exchange failed (${tokenRes.status}): ${tokenText || JSON.stringify(tokenJson)}`
747
+ )
748
+ }
749
+
750
+ const sellerAccessToken = String(tokenJson.access_token || "")
751
+ if (!sellerAccessToken) {
752
+ throw new Error("PayPal token exchange succeeded but access_token is missing.")
753
+ }
754
+
755
+ const partnerMerchantId = await this.getPartnerMerchantId(env)
756
+ if (!partnerMerchantId) {
757
+ throw new Error("Missing PayPal partner merchant id configuration.")
758
+ }
759
+
760
+ const credRes = await paypalFetch(
761
+ `${baseUrl}/v1/customer/partners/${encodeURIComponent(partnerMerchantId)}/merchant-integrations/credentials/`,
762
+ {
763
+ method: "GET",
764
+ headers: {
765
+ "Content-Type": "application/json",
766
+ Authorization: `Bearer ${sellerAccessToken}`,
767
+ "PayPal-Partner-Attribution-Id": this.bnCode,
768
+ },
769
+ }
770
+ )
771
+
772
+ const credText = await credRes.text().catch(() => "")
773
+ let credJson: any = {}
774
+ try {
775
+ credJson = credText ? JSON.parse(credText) : {}
776
+ } catch (e: any) {
777
+ console.warn("[PayPal] Failed to parse token response JSON:", e?.message)
778
+ }
779
+
780
+ if (!credRes.ok) {
781
+ throw new Error(
782
+ `PayPal credentials fetch failed (${credRes.status}): ${credText || JSON.stringify(credJson)}`
783
+ )
784
+ }
785
+
786
+ const clientId = String(credJson.client_id || credJson.clientId || "")
787
+ const clientSecret = String(credJson.client_secret || credJson.clientSecret || "")
788
+ if (!clientId || !clientSecret) {
789
+ throw new Error(
790
+ `PayPal credentials response missing client_id/client_secret. Keys: ${Object.keys(credJson || {}).join(", ")}`
791
+ )
792
+ }
793
+
794
+ let sellerEmail = this.extractSellerEmail(credJson, tokenJson)
795
+ let sellerMerchantId =
796
+ String(credJson.payer_id || credJson.merchant_id || tokenJson.payer_id || tokenJson.merchant_id || "").trim() ||
797
+ null
798
+
799
+ if (!sellerEmail) {
800
+ const merchantCandidates = [
801
+ String(credJson.payer_id || "").trim(),
802
+ String(credJson.merchant_id || "").trim(),
803
+ String(tokenJson.payer_id || "").trim(),
804
+ String(tokenJson.merchant_id || "").trim(),
805
+ ].filter(Boolean).filter((v, i, arr) => arr.indexOf(v) === i)
806
+
807
+ for (const merchantId of merchantCandidates) {
808
+ try {
809
+ const merchantDetails = await this.fetchMerchantIntegrationDetails(env, merchantId, sellerAccessToken)
810
+ sellerMerchantId = sellerMerchantId || merchantId
811
+ sellerEmail = this.extractSellerEmail(merchantDetails)
812
+ if (sellerEmail) {
813
+ break
814
+ }
815
+ } catch (e: any) {
816
+ console.warn(`[PayPal] Merchant integration lookup for ${merchantId} failed:`, e?.message || e)
817
+ }
818
+ }
819
+ }
820
+
821
+ await this.saveSellerCredentials({
822
+ clientId,
823
+ clientSecret,
824
+ sellerMerchantId,
825
+ sellerEmail,
826
+ })
827
+
828
+ if (!sellerEmail && sellerMerchantId) {
829
+ try {
830
+ const appAccessToken = await this.getAppAccessToken()
831
+ const details = await this.fetchMerchantIntegrationDetails(env, sellerMerchantId, appAccessToken)
832
+ sellerEmail = this.extractSellerEmail(details)
833
+ if (sellerEmail) {
834
+ await this.saveSellerCredentials({ clientId, clientSecret, sellerMerchantId, sellerEmail })
835
+ }
836
+ } catch (e: any) {
837
+ console.warn("[PayPal] Post-save merchant_id email lookup failed:", e?.message || e)
838
+ }
839
+ }
840
+ }
841
+
842
+ async saveSellerCredentials(input: {
843
+ clientId: string
844
+ clientSecret: string
845
+ sellerMerchantId?: string | null
846
+ sellerEmail?: string | null
847
+ environment?: Environment
848
+ }) {
849
+ const row = await this.getCurrentRow()
850
+ const currentEnv = await this.getCurrentEnvironment()
851
+ const env = (input.environment || currentEnv) as Environment
852
+
853
+ const existingCreds = row ? this.getEnvCreds(row, env) : {}
854
+ const nextSellerMerchantId =
855
+ (input.sellerMerchantId || "").trim() || existingCreds.sellerMerchantId || row?.seller_merchant_id || null
856
+ const nextSellerEmail =
857
+ (input.sellerEmail || "").trim() || existingCreds.sellerEmail || row?.seller_email || null
858
+
859
+ // Encrypt once and store the same ciphertext in both the metadata copy and
860
+ // the denormalized column (no-op when encryption is disabled).
861
+ const storedClientSecret = encryptSecret(input.clientSecret)
862
+
863
+ const nextCreds = {
864
+ client_id: input.clientId,
865
+ client_secret: storedClientSecret,
866
+ merchant_id: nextSellerMerchantId,
867
+ seller_merchant_id: nextSellerMerchantId,
868
+ seller_email: nextSellerEmail,
869
+ }
870
+
871
+ if (!row) {
872
+ const created = await this.createPayPalConnections({
873
+ environment: env,
874
+ status: "connected",
875
+ seller_client_id: input.clientId,
876
+ seller_client_secret: storedClientSecret,
877
+ seller_merchant_id: nextSellerMerchantId,
878
+ seller_email: nextSellerEmail,
879
+ app_access_token: null,
880
+ app_access_token_expires_at: null,
881
+ metadata: {
882
+ credentials: {
883
+ [env]: nextCreds,
884
+ },
885
+ active_environment: env,
886
+ },
887
+ })
888
+ await this.recordAuditEvent("credentials_saved", {
889
+ environment: env,
890
+ client_id: input.clientId,
891
+ })
892
+ await this.ensureWebhookRegistration()
893
+ return created
894
+ }
895
+
896
+ const meta = (row.metadata || {}) as any
897
+ const creds = { ...(meta.credentials || {}) }
898
+ creds[env] = {
899
+ ...(creds[env] || {}),
900
+ ...nextCreds,
901
+ }
902
+
903
+ const updated = await this.updatePayPalConnections({
904
+ id: row.id,
905
+ status: "connected",
906
+ seller_client_id: input.clientId,
907
+ seller_client_secret: storedClientSecret,
908
+ seller_merchant_id: nextSellerMerchantId,
909
+ seller_email: nextSellerEmail,
910
+ app_access_token: null,
911
+ app_access_token_expires_at: null,
912
+ metadata: {
913
+ ...(row.metadata || {}),
914
+ credentials: creds,
915
+ active_environment: env,
916
+ },
917
+ })
918
+ await this.recordAuditEvent("credentials_saved", {
919
+ environment: env,
920
+ client_id: input.clientId,
921
+ })
922
+ await this.ensureWebhookRegistration()
923
+ return updated
924
+ }
925
+
926
+ async saveAndHydrateSellerCredentials(input: {
927
+ clientId: string
928
+ clientSecret: string
929
+ environment?: Environment
930
+ }) {
931
+ const env = (input.environment || (await this.getCurrentEnvironment())) as Environment
932
+
933
+ await this.saveSellerCredentials({
934
+ clientId: input.clientId,
935
+ clientSecret: input.clientSecret,
936
+ environment: env,
937
+ })
938
+
939
+ try {
940
+ const hydrated = await this.fetchSellerProfileFromDirectCredentials(env, {
941
+ clientId: input.clientId,
942
+ clientSecret: input.clientSecret,
943
+ })
944
+
945
+ if (hydrated.sellerEmail || hydrated.sellerMerchantId) {
946
+ await this.saveSellerCredentials({
947
+ clientId: input.clientId,
948
+ clientSecret: input.clientSecret,
949
+ sellerMerchantId: hydrated.sellerMerchantId,
950
+ sellerEmail: hydrated.sellerEmail,
951
+ environment: env,
952
+ })
953
+ }
954
+
955
+ const refreshedRow = await this.getCurrentRow()
956
+ if (refreshedRow) {
957
+ await this.syncRowFieldsFromMetadata(refreshedRow, env)
958
+ }
959
+ } catch (e: any) {
960
+ console.warn("[PayPal] saveAndHydrateSellerCredentials lookup failed:", e?.message || e)
961
+ }
962
+
963
+ // This is a write context (credentials were just saved), so it is allowed to
964
+ // backfill the seller profile if it is still missing.
965
+ return await this.getStatus(env, { hydrateMissingProfile: true })
966
+ }
967
+
968
+ private async resolveWebhookUrl() {
969
+ const { onboarding } = await this.ensureSettingsDefaults()
970
+ const base = String(onboarding.backend_url || "").replace(/\/$/, "")
971
+ if (!base) {
972
+ throw new Error("PayPal backend URL is not configured.")
973
+ }
974
+ // The /hooks namespace has no publishable-key guard. PayPal cannot send
975
+ // Medusa's x-publishable-api-key header, so a webhook registered at the
976
+ // old /store/paypal/webhook path is rejected before the handler runs.
977
+ return `${base}/hooks/paypal/webhook`
978
+ }
979
+
980
+ /** Legacy webhook path (blocked by Medusa's store publishable-key guard). */
981
+ private async resolveLegacyWebhookUrl() {
982
+ const { onboarding } = await this.ensureSettingsDefaults()
983
+ const base = String(onboarding.backend_url || "").replace(/\/$/, "")
984
+ if (!base) return ""
985
+ return `${base}/store/paypal/webhook`
986
+ }
987
+
988
+ private isLocalWebhookUrl(url: string) {
989
+ try {
990
+ const parsed = new URL(url)
991
+ return ["localhost", "127.0.0.1", "::1"].includes(parsed.hostname)
992
+ } catch {
993
+ return false
994
+ }
995
+ }
996
+
997
+ // Only probe PayPal for a stale legacy webhook URL once per process per
998
+ // environment — this runs on admin status reads and must stay cheap.
999
+ private webhookUrlMigrationChecked: Record<string, boolean> = {}
1000
+ private webhookHealScheduled: Record<string, boolean> = {}
1001
+
1002
+ private async migrateLegacyWebhookUrl(env: string, webhookId: string) {
1003
+ if (this.webhookUrlMigrationChecked[env]) return
1004
+ this.webhookUrlMigrationChecked[env] = true
1005
+
1006
+ const newUrl = await this.resolveWebhookUrl().catch(() => "")
1007
+ const legacyUrl = await this.resolveLegacyWebhookUrl()
1008
+ if (!newUrl || !legacyUrl || this.isLocalWebhookUrl(newUrl)) return
1009
+
1010
+ const accessToken = await this.getAppAccessToken()
1011
+ const baseUrl = getPayPalApiBase(env)
1012
+
1013
+ const getResp = await paypalFetch(
1014
+ `${baseUrl}/v1/notifications/webhooks/${encodeURIComponent(webhookId)}`,
1015
+ {
1016
+ headers: {
1017
+ Authorization: `Bearer ${accessToken}`,
1018
+ "Content-Type": "application/json",
1019
+ "PayPal-Partner-Attribution-Id": this.bnCode,
1020
+ },
1021
+ }
1022
+ )
1023
+ const getJson = await getResp.json().catch(() => ({}))
1024
+ if (!getResp.ok) return
1025
+
1026
+ const currentUrl = String(getJson?.url || "")
1027
+ if (currentUrl !== legacyUrl) return
1028
+
1029
+ const patchResp = await paypalFetch(
1030
+ `${baseUrl}/v1/notifications/webhooks/${encodeURIComponent(webhookId)}`,
1031
+ {
1032
+ method: "PATCH",
1033
+ headers: {
1034
+ Authorization: `Bearer ${accessToken}`,
1035
+ "Content-Type": "application/json",
1036
+ "PayPal-Partner-Attribution-Id": this.bnCode,
1037
+ },
1038
+ body: JSON.stringify([
1039
+ { op: "replace", path: "/url", value: newUrl },
1040
+ ]),
1041
+ }
1042
+ )
1043
+ if (patchResp.ok) {
1044
+ await this.recordAuditEvent("webhook_url_migrated", {
1045
+ environment: env,
1046
+ webhook_id: webhookId,
1047
+ from: legacyUrl,
1048
+ to: newUrl,
1049
+ })
1050
+ console.info(
1051
+ `[PayPal] migrated webhook ${webhookId} URL from ${legacyUrl} to ${newUrl}`
1052
+ )
1053
+ }
1054
+ }
1055
+
1056
+ private async ensureWebhookRegistration() {
1057
+ const env = await this.getCurrentEnvironment()
1058
+ const { apiDetails } = await this.ensureSettingsDefaults()
1059
+ const webhookIds = { ...(apiDetails.webhook_ids || {}) } as Record<string, string>
1060
+
1061
+ if (webhookIds[env]) {
1062
+ // Existing installs registered the webhook at /store/paypal/webhook,
1063
+ // which Medusa's publishable-key middleware blocks for external callers.
1064
+ // Migrate the registered URL to /hooks/paypal/webhook in place
1065
+ // (best-effort — a failure keeps the stored id and current behavior).
1066
+ await this.migrateLegacyWebhookUrl(env, webhookIds[env]).catch((e: any) => {
1067
+ console.warn(
1068
+ "[PayPal] webhook URL migration check failed:",
1069
+ e?.message || e
1070
+ )
1071
+ })
1072
+ return webhookIds[env]
1073
+ }
1074
+
1075
+ const accessToken = await this.getAppAccessToken()
1076
+ const baseUrl = getPayPalApiBase(env)
1077
+ const webhookUrl = await this.resolveWebhookUrl()
1078
+
1079
+ if (this.isLocalWebhookUrl(webhookUrl)) {
1080
+ await this.recordAuditEvent("webhook_skipped_localhost", {
1081
+ environment: env,
1082
+ webhook_url: webhookUrl,
1083
+ })
1084
+ return webhookIds[env] || ""
1085
+ }
1086
+
1087
+ const listResp = await paypalFetch(`${baseUrl}/v1/notifications/webhooks`, {
1088
+ headers: {
1089
+ Authorization: `Bearer ${accessToken}`,
1090
+ "Content-Type": "application/json",
1091
+ "PayPal-Partner-Attribution-Id": this.bnCode,
1092
+ },
1093
+ })
1094
+
1095
+ const listJson = await listResp.json().catch(() => ({}))
1096
+ if (!listResp.ok) {
1097
+ throw new Error(`PayPal webhook list failed (${listResp.status}): ${JSON.stringify(listJson)}`)
1098
+ }
1099
+
1100
+ const existing = Array.isArray(listJson?.webhooks)
1101
+ ? listJson.webhooks.find((hook: any) => hook?.url === webhookUrl)
1102
+ : null
1103
+
1104
+ let webhookId = existing?.id ? String(existing.id) : ""
1105
+
1106
+ if (!webhookId) {
1107
+ const createResp = await paypalFetch(`${baseUrl}/v1/notifications/webhooks`, {
1108
+ method: "POST",
1109
+ headers: {
1110
+ Authorization: `Bearer ${accessToken}`,
1111
+ "Content-Type": "application/json",
1112
+ "PayPal-Partner-Attribution-Id": this.bnCode,
1113
+ },
1114
+ body: JSON.stringify({
1115
+ url: webhookUrl,
1116
+ event_types: [
1117
+ { name: "CHECKOUT.ORDER.APPROVED" },
1118
+ { name: "CHECKOUT.ORDER.CANCELLED" },
1119
+ { name: "PAYMENT.CAPTURE.COMPLETED" },
1120
+ { name: "PAYMENT.CAPTURE.DENIED" },
1121
+ { name: "PAYMENT.CAPTURE.REFUNDED" },
1122
+ { name: "PAYMENT.CAPTURE.REVERSED" },
1123
+ { name: "PAYMENT.AUTHORIZATION.CREATED" },
1124
+ { name: "PAYMENT.AUTHORIZATION.VOIDED" },
1125
+ { name: "PAYMENT.AUTHORIZATION.DENIED" },
1126
+ { name: "PAYMENT.REFUND.COMPLETED" },
1127
+ { name: "PAYMENT.REFUND.DENIED" },
1128
+ ],
1129
+ }),
1130
+ })
1131
+
1132
+ const createJson = await createResp.json().catch(() => ({}))
1133
+ if (!createResp.ok) {
1134
+ throw new Error(
1135
+ `PayPal webhook create failed (${createResp.status}): ${JSON.stringify(createJson)}`
1136
+ )
1137
+ }
1138
+
1139
+ webhookId = String(createJson?.id || "")
1140
+ }
1141
+
1142
+ if (!webhookId) {
1143
+ throw new Error("PayPal webhook registration did not return an id")
1144
+ }
1145
+
1146
+ const nextWebhookIds = { ...webhookIds, [env]: webhookId }
1147
+ await this.saveSettings({
1148
+ api_details: {
1149
+ ...apiDetails,
1150
+ webhook_ids: nextWebhookIds,
1151
+ },
1152
+ })
1153
+
1154
+ await this.recordAuditEvent("webhook_registered", {
1155
+ environment: env,
1156
+ webhook_id: webhookId,
1157
+ webhook_url: webhookUrl,
1158
+ })
1159
+
1160
+ return webhookId
1161
+ }
1162
+
1163
+ private maskValue(value?: string | null, visibleChars = 4) {
1164
+ if (!value) return null
1165
+ const trimmed = String(value)
1166
+ if (trimmed.length <= visibleChars) {
1167
+ return "•".repeat(trimmed.length)
1168
+ }
1169
+ return `${"•".repeat(Math.max(0, trimmed.length - visibleChars))}${trimmed.slice(
1170
+ -visibleChars
1171
+ )}`
1172
+ }
1173
+
1174
+ /**
1175
+ * Report the current connection status.
1176
+ *
1177
+ * `hydrateMissingProfile` is opt-in and OFF by default: status is read on
1178
+ * `GET /admin/paypal/status` (and other read-only routes), where it must be a
1179
+ * safe, side-effect-free read. The seller-profile backfill makes an outbound
1180
+ * PayPal call and persists to the DB, so it only runs from write contexts
1181
+ * (e.g. saving credentials) that explicitly request it.
1182
+ */
1183
+ async getStatus(
1184
+ envOverride?: Environment,
1185
+ opts: { hydrateMissingProfile?: boolean } = {}
1186
+ ) {
1187
+ const row = await this.getCurrentRow()
1188
+ const env = envOverride ?? (await this.getCurrentEnvironment())
1189
+
1190
+ if (!row) {
1191
+ return { environment: env, status: "disconnected" as Status, seller_client_id_present: false }
1192
+ }
1193
+
1194
+ const c = this.getEnvCreds(row, env)
1195
+ const hasCreds = !!(c.clientId && c.clientSecret)
1196
+ let sellerEmail: string | null = c.sellerEmail || row.seller_email || null
1197
+ let sellerMerchantId: string | null = c.sellerMerchantId || row.seller_merchant_id || null
1198
+
1199
+ // Self-heal the webhook registration for already-connected merchants:
1200
+ // installs that registered the webhook at the old (blocked)
1201
+ // /store/paypal/webhook path get migrated to /hooks/paypal/webhook the
1202
+ // first time an admin views the status page after upgrading. Fire and
1203
+ // forget — status reads must never block on PayPal, and the migration is
1204
+ // throttled to once per process per environment internally.
1205
+ if (hasCreds && !this.webhookHealScheduled[env]) {
1206
+ this.webhookHealScheduled[env] = true
1207
+ void this.ensureWebhookRegistration().catch((e: any) => {
1208
+ console.warn("[PayPal] webhook self-heal failed:", e?.message || e)
1209
+ })
1210
+ }
1211
+
1212
+ if (!sellerEmail && hasCreds && opts.hydrateMissingProfile) {
1213
+ try {
1214
+ const hydrated = await this.fetchSellerProfileFromDirectCredentials(env)
1215
+ if (hydrated.sellerEmail || hydrated.sellerMerchantId) {
1216
+ await this.saveSellerCredentials({
1217
+ clientId: c.clientId!,
1218
+ clientSecret: c.clientSecret!,
1219
+ sellerMerchantId: hydrated.sellerMerchantId || sellerMerchantId,
1220
+ sellerEmail: hydrated.sellerEmail || sellerEmail,
1221
+ environment: env,
1222
+ })
1223
+
1224
+ const refreshedRow = await this.getCurrentRow()
1225
+ if (refreshedRow) {
1226
+ const refreshedCreds = this.getEnvCreds(refreshedRow, env)
1227
+ sellerEmail = refreshedCreds.sellerEmail || refreshedRow.seller_email || sellerEmail
1228
+ sellerMerchantId =
1229
+ refreshedCreds.sellerMerchantId || refreshedRow.seller_merchant_id || sellerMerchantId
1230
+ }
1231
+ }
1232
+ } catch (e: any) {
1233
+ console.warn("[PayPal] status direct credential lookup failed:", e?.message || e)
1234
+ }
1235
+ }
1236
+
1237
+ return {
1238
+ environment: env,
1239
+ status: (hasCreds ? "connected" : "disconnected") as Status,
1240
+ shared_id: row.shared_id ?? null,
1241
+ auth_code: row.auth_code ? "***stored***" : null,
1242
+ seller_client_id_present: hasCreds,
1243
+ seller_client_id_masked: this.maskValue(c.clientId),
1244
+ seller_client_secret_masked: c.clientSecret ? "••••••••" : null,
1245
+ seller_merchant_id: sellerMerchantId,
1246
+ seller_email: sellerEmail,
1247
+ updated_at: (row.updated_at as any)?.toISOString?.() ?? null,
1248
+ }
1249
+ }
1250
+
1251
+ async disconnect() {
1252
+ const row = await this.getCurrentRow()
1253
+ if (!row) return
1254
+ const env = await this.getCurrentEnvironment()
1255
+
1256
+ const meta = (row.metadata || {}) as any
1257
+ const creds = { ...(meta.credentials || {}) }
1258
+ delete creds[env]
1259
+
1260
+ const hasAnyCreds = Object.values(creds).some((v: any) => {
1261
+ return v && typeof v === "object" && (v as any).client_id && (v as any).client_secret
1262
+ })
1263
+
1264
+ await this.updatePayPalConnections({
1265
+ id: row.id,
1266
+ status: hasAnyCreds ? "connected" : "disconnected",
1267
+ shared_id: null,
1268
+ auth_code: null,
1269
+ seller_client_id: null,
1270
+ seller_client_secret: null,
1271
+ seller_merchant_id: null,
1272
+ seller_email: null,
1273
+ app_access_token: null,
1274
+ app_access_token_expires_at: null,
1275
+ metadata: {
1276
+ ...(row.metadata || {}),
1277
+ credentials: creds,
1278
+ active_environment: env,
1279
+ },
1280
+ })
1281
+ const updated = await this.getCurrentRow()
1282
+ if (updated) {
1283
+ await this.syncRowFieldsFromMetadata(updated, env)
1284
+ }
1285
+ await this.recordAuditEvent("disconnected", { environment: env })
1286
+ }
1287
+
1288
+ async getAppAccessToken(): Promise<string> {
1289
+ const row = await this.getCurrentRow()
1290
+
1291
+ if (!row) {
1292
+ throw new Error("PayPal connection row not found. Please complete onboarding.")
1293
+ }
1294
+
1295
+ const expiresAt = row.app_access_token_expires_at ? new Date(row.app_access_token_expires_at as string) : null
1296
+ if (row.app_access_token && expiresAt) {
1297
+ const msLeft = expiresAt.getTime() - Date.now()
1298
+ // Token is encrypted at rest when a key is configured; decrypt the cached
1299
+ // value (legacy plaintext passes through unchanged).
1300
+ if (msLeft > 2 * 60 * 1000) return decryptSecret(row.app_access_token as string) as string
1301
+ }
1302
+
1303
+ if (this.tokenRefreshPromise) {
1304
+ return this.tokenRefreshPromise
1305
+ }
1306
+
1307
+ this.tokenRefreshPromise = this.refreshAccessToken(row).finally(() => {
1308
+ this.tokenRefreshPromise = null
1309
+ })
1310
+
1311
+ return this.tokenRefreshPromise
1312
+ }
1313
+
1314
+ private async refreshAccessToken(row: { id: string }): Promise<string> {
1315
+ const env = await this.getCurrentEnvironment()
1316
+ const creds = await this.getActiveCredentials()
1317
+ const baseUrl = getPayPalApiBase(env)
1318
+ const basic = Buffer.from(`${creds.client_id}:${creds.client_secret}`).toString("base64")
1319
+
1320
+ const body = new URLSearchParams()
1321
+ body.set("grant_type", "client_credentials")
1322
+
1323
+ const res = await paypalFetch(`${baseUrl}/v1/oauth2/token`, {
1324
+ method: "POST",
1325
+ headers: {
1326
+ "Content-Type": "application/x-www-form-urlencoded",
1327
+ Authorization: `Basic ${basic}`,
1328
+ "PayPal-Partner-Attribution-Id": this.bnCode,
1329
+ },
1330
+ body,
1331
+ signal: AbortSignal.timeout(30_000),
1332
+ })
1333
+
1334
+ const json = await res.json().catch(() => ({}))
1335
+ if (!res.ok) throw new Error(`PayPal client_credentials failed (${res.status}): ${JSON.stringify(json)}`)
1336
+
1337
+ const accessToken = String(json.access_token || "")
1338
+ if (!accessToken) {
1339
+ throw new Error("PayPal client_credentials succeeded but access_token is missing.")
1340
+ }
1341
+ const expiresIn = Number(json.expires_in || 3600)
1342
+ const newExpiresAt = new Date(Date.now() + expiresIn * 1000)
1343
+
1344
+ await this.updatePayPalConnections({
1345
+ id: row.id,
1346
+ app_access_token: encryptSecret(accessToken),
1347
+ app_access_token_expires_at: newExpiresAt as unknown as Date,
1348
+ })
1349
+
1350
+ return accessToken
1351
+ }
1352
+
1353
+ async generateClientToken(opts?: { locale?: string }): Promise<string> {
1354
+ const env = await this.getCurrentEnvironment()
1355
+ const baseUrl = getPayPalApiBase(env)
1356
+
1357
+ const accessToken = await this.getAppAccessToken()
1358
+
1359
+ const res = await paypalFetch(`${baseUrl}/v1/identity/generate-token`, {
1360
+ method: "POST",
1361
+ headers: {
1362
+ Authorization: `Bearer ${accessToken}`,
1363
+ "Content-Type": "application/json",
1364
+ Accept: "application/json",
1365
+ "PayPal-Partner-Attribution-Id": this.bnCode,
1366
+ ...(opts?.locale ? { "Accept-Language": opts.locale } : {}),
1367
+ },
1368
+ })
1369
+
1370
+ const json = await res.json().catch(() => ({}))
1371
+ if (!res.ok) {
1372
+ throw new Error(`PayPal generate-token failed (${res.status}): ${JSON.stringify(json)}`)
1373
+ }
1374
+
1375
+ const token = String((json as any)?.client_token || "")
1376
+ if (!token) {
1377
+ throw new Error("PayPal client_token is missing in generate-token response")
1378
+ }
1379
+
1380
+ return token
1381
+ }
1382
+
1383
+ async getSettings() {
1384
+ // Deterministic singleton read: always the OLDEST row. If a first-boot race
1385
+ // ever created a duplicate settings row, every reader (here and the
1386
+ // credential resolver's raw read) must agree on the same winner — ordering
1387
+ // by created_at ASC guarantees that; an unordered `take: 1` does not.
1388
+ const rows = await this.listPayPalSettings(
1389
+ {},
1390
+ { take: 1, order: { created_at: "ASC" } }
1391
+ )
1392
+ const row = rows?.[0]
1393
+ return { data: (row?.data || {}) as Record<string, any> }
1394
+ }
1395
+
1396
+ private deepMerge(
1397
+ target: Record<string, any>,
1398
+ source: Record<string, any>
1399
+ ): Record<string, any> {
1400
+ const result = { ...target }
1401
+ for (const key of Object.keys(source)) {
1402
+ const sv = source[key]
1403
+ const tv = target[key]
1404
+ if (
1405
+ sv !== null &&
1406
+ typeof sv === "object" &&
1407
+ !Array.isArray(sv) &&
1408
+ tv !== null &&
1409
+ typeof tv === "object" &&
1410
+ !Array.isArray(tv)
1411
+ ) {
1412
+ result[key] = this.deepMerge(tv, sv)
1413
+ } else {
1414
+ result[key] = sv
1415
+ }
1416
+ }
1417
+ return result
1418
+ }
1419
+
1420
+ async saveSettings(patch: Record<string, any>) {
1421
+ // Same deterministic ordering as getSettings so reads and writes always
1422
+ // target the same singleton row.
1423
+ const rows = await this.listPayPalSettings(
1424
+ {},
1425
+ { take: 1, order: { created_at: "ASC" } }
1426
+ )
1427
+ const row = rows?.[0]
1428
+ const current = (row?.data || {}) as Record<string, any>
1429
+
1430
+ const next = this.deepMerge(current, patch)
1431
+
1432
+ if (!row) {
1433
+ const created = await this.createPayPalSettings({ data: next })
1434
+ // First-boot race guard: if a concurrent save created a row a moment
1435
+ // earlier, the ASC ordering means that row is the canonical singleton —
1436
+ // merge this patch into it instead of leaving a divergent duplicate.
1437
+ const recheck = await this.listPayPalSettings(
1438
+ {},
1439
+ { take: 1, order: { created_at: "ASC" } }
1440
+ )
1441
+ const canonical = recheck?.[0]
1442
+ if (canonical && canonical.id !== created.id) {
1443
+ const merged = this.deepMerge(
1444
+ (canonical.data || {}) as Record<string, any>,
1445
+ patch
1446
+ )
1447
+ await this.updatePayPalSettings({ id: canonical.id, data: merged })
1448
+ return { data: merged }
1449
+ }
1450
+ return { data: (created.data || {}) as Record<string, any> }
1451
+ }
1452
+
1453
+ await this.updatePayPalSettings({ id: row.id, data: next })
1454
+ return { data: next }
1455
+ }
1456
+
1457
+ async getActiveCredentials() {
1458
+ const row = await this.getCurrentRow()
1459
+ const env = await this.getCurrentEnvironment()
1460
+
1461
+ if (!row) {
1462
+ throw new Error("PayPal connection row not found. Please complete onboarding.")
1463
+ }
1464
+
1465
+ const c = this.getEnvCreds(row, env)
1466
+ const clientSecret = c.clientSecret || ""
1467
+
1468
+ if (!c.clientId || !clientSecret) {
1469
+ throw new Error(
1470
+ `PayPal credentials missing for environment "${env}". Please save credentials.`
1471
+ )
1472
+ }
1473
+
1474
+ return {
1475
+ environment: env,
1476
+ client_id: c.clientId,
1477
+ client_secret: clientSecret,
1478
+ }
1479
+ }
1480
+
1481
+ async getOrderDetails(orderId: string) {
1482
+ if (!orderId) {
1483
+ throw new Error("PayPal orderId is required")
1484
+ }
1485
+
1486
+ const env = await this.getCurrentEnvironment()
1487
+ const base = getPayPalApiBase(env)
1488
+
1489
+ const accessToken = await this.getAppAccessToken()
1490
+
1491
+ const resp = await paypalFetch(
1492
+ `${base}/v2/checkout/orders/${encodeURIComponent(orderId)}`,
1493
+ {
1494
+ method: "GET",
1495
+ headers: {
1496
+ Authorization: `Bearer ${accessToken}`,
1497
+ "Content-Type": "application/json",
1498
+ "PayPal-Partner-Attribution-Id": this.bnCode,
1499
+ },
1500
+ signal: AbortSignal.timeout(30_000),
1501
+ }
1502
+ )
1503
+
1504
+ const text = await resp.text()
1505
+ if (!resp.ok) {
1506
+ throw new Error(`PayPal get order error (${resp.status}): ${text}`)
1507
+ }
1508
+
1509
+ return JSON.parse(text)
1510
+ }
1511
+
1512
+ async createWebhookEventRecord(input: {
1513
+ event_id: string
1514
+ event_type: string
1515
+ resource_id?: string | null
1516
+ payload?: Record<string, unknown>
1517
+ event_version?: string | null
1518
+ transmission_id?: string | null
1519
+ transmission_time?: Date | null
1520
+ status?: string
1521
+ attempt_count?: number
1522
+ }) {
1523
+ try {
1524
+ const created = await this.createPayPalWebhookEvents({
1525
+ event_id: input.event_id,
1526
+ event_type: input.event_type,
1527
+ resource_id: input.resource_id ?? null,
1528
+ payload: input.payload ?? {},
1529
+ event_version: input.event_version ?? null,
1530
+ transmission_id: input.transmission_id ?? null,
1531
+ transmission_time: input.transmission_time ?? null,
1532
+ status: input.status ?? "pending",
1533
+ attempt_count: input.attempt_count ?? 0,
1534
+ next_retry_at: null,
1535
+ processed_at: null,
1536
+ last_error: null,
1537
+ })
1538
+ return { created: true, event: created }
1539
+ } catch (error: any) {
1540
+ const message = String(error?.message || "")
1541
+ const code = String(error?.code || "")
1542
+ if (
1543
+ message.includes("paypal_webhook_event_event_id_unique") ||
1544
+ code === "23505" ||
1545
+ (message.includes("unique") && message.includes("event_id"))
1546
+ ) {
1547
+ const existing = await this.listPayPalWebhookEvents({ event_id: input.event_id })
1548
+ return { created: false, event: existing?.[0] ?? null }
1549
+ }
1550
+ throw error
1551
+ }
1552
+ }
1553
+
1554
+ async updateWebhookEventRecord(input: {
1555
+ id: string
1556
+ status?: string
1557
+ attempt_count?: number
1558
+ next_retry_at?: Date | null
1559
+ processed_at?: Date | null
1560
+ last_error?: string | null
1561
+ resource_id?: string | null
1562
+ }) {
1563
+ return await this.updatePayPalWebhookEvents({
1564
+ id: input.id,
1565
+ status: input.status,
1566
+ attempt_count: input.attempt_count,
1567
+ next_retry_at: input.next_retry_at ?? null,
1568
+ processed_at: input.processed_at ?? null,
1569
+ last_error: input.last_error ?? null,
1570
+ resource_id: input.resource_id ?? null,
1571
+ })
1572
+ }
1573
+
1574
+ /**
1575
+ * Emit an audit event as a single structured log line.
1576
+ *
1577
+ * The dedicated audit-log table was removed; for high-volume/containerized
1578
+ * deployments the audit trail lives in aggregated stdout logs. This records a
1579
+ * greppable `paypal_audit` line (filter on `"log":"paypal_audit"`) with
1580
+ * sensitive keys redacted. It never throws — audit logging must not break the
1581
+ * caller's payment flow.
1582
+ */
1583
+ async recordAuditEvent(eventType: string, metadata?: Record<string, unknown>) {
1584
+ try {
1585
+ console.info(
1586
+ JSON.stringify({
1587
+ log: "paypal_audit",
1588
+ event_type: eventType,
1589
+ at: new Date().toISOString(),
1590
+ ...(metadata ? { metadata: redactSensitive(metadata) } : {}),
1591
+ })
1592
+ )
1593
+ } catch {
1594
+ // never let audit logging interfere with the payment flow
1595
+ }
1596
+ return null
1597
+ }
1598
+
1599
+ async recordMetric(name: string, metadata?: Record<string, unknown>) {
1600
+ // Preferred path: single atomic INSERT ... ON CONFLICT (same statement the
1601
+ // credential resolver uses), so concurrent routes/webhooks never lose
1602
+ // increments to a read-modify-write race.
1603
+ if (this.pgForMetrics) {
1604
+ await recordMetricAtomic(this.pgForMetrics, name, metadata)
1605
+ return null
1606
+ }
1607
+ // Fallback (container without a raw pg connection): the previous ORM
1608
+ // read-modify-write. Best-effort only — never throws.
1609
+ try {
1610
+ const existing = await this.listPayPalMetrics({ name })
1611
+ const row = existing?.[0]
1612
+ const current = (row?.data || {}) as Record<string, any>
1613
+ const next = {
1614
+ ...current,
1615
+ ...(metadata || {}),
1616
+ count: Number(current.count || 0) + 1,
1617
+ last_recorded_at: new Date().toISOString(),
1618
+ }
1619
+
1620
+ if (!row) {
1621
+ try {
1622
+ return await this.createPayPalMetrics({ name, data: next })
1623
+ } catch {
1624
+ const retry = await this.listPayPalMetrics({ name })
1625
+ const retryRow = retry?.[0]
1626
+ if (retryRow) {
1627
+ const retryData = (retryRow.data || {}) as Record<string, any>
1628
+ return await this.updatePayPalMetrics({
1629
+ id: retryRow.id,
1630
+ name,
1631
+ data: {
1632
+ ...retryData,
1633
+ ...(metadata || {}),
1634
+ count: Number(retryData.count || 0) + 1,
1635
+ last_recorded_at: new Date().toISOString(),
1636
+ },
1637
+ })
1638
+ }
1639
+ throw new Error(`Failed to record metric "${name}"`)
1640
+ }
1641
+ }
1642
+
1643
+ return await this.updatePayPalMetrics({ id: row.id, name, data: next })
1644
+ } catch (e: unknown) {
1645
+ console.warn("[PayPal] recordMetric failed:", e instanceof Error ? e.message : e)
1646
+ return null
1647
+ }
1648
+ }
1649
+
1650
+ async recordPaymentLog(eventType: string, metadata?: Record<string, unknown>) {
1651
+ return await this.recordAuditEvent(`payment_${eventType}`, metadata)
1652
+ }
1653
+
1654
+ async sendAlert(input: {
1655
+ type: string
1656
+ message: string
1657
+ metadata?: Record<string, unknown>
1658
+ }) {
1659
+ const urls = this.getAlertWebhookUrls()
1660
+ if (urls.length === 0) {
1661
+ return
1662
+ }
1663
+
1664
+ const payload = {
1665
+ type: input.type,
1666
+ message: input.message,
1667
+ metadata: input.metadata ?? {},
1668
+ source: "paypal",
1669
+ timestamp: new Date().toISOString(),
1670
+ }
1671
+
1672
+ await Promise.all(
1673
+ urls.map(async (url) => {
1674
+ try {
1675
+ const resp = await paypalFetch(url, {
1676
+ method: "POST",
1677
+ headers: {
1678
+ "Content-Type": "application/json",
1679
+ },
1680
+ body: JSON.stringify(payload),
1681
+ })
1682
+ if (!resp.ok) {
1683
+ const text = await resp.text().catch(() => "")
1684
+ await this.recordAuditEvent("alert_failed", {
1685
+ url,
1686
+ status: resp.status,
1687
+ response: text,
1688
+ })
1689
+ } else {
1690
+ await this.recordAuditEvent("alert_sent", { url, type: input.type })
1691
+ }
1692
+ } catch (error: any) {
1693
+ await this.recordAuditEvent("alert_failed", {
1694
+ url,
1695
+ message: error?.message,
1696
+ })
1697
+ }
1698
+ })
1699
+ )
1700
+ }
1701
+ }
1702
+
1703
+ export default PayPalModuleService