@easypayment/medusa-payment-paypal 1.0.2 → 1.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.medusa/server/src/admin/index.js +7 -7
- package/.medusa/server/src/admin/index.mjs +7 -7
- package/.medusa/server/src/api/admin/paypal/onboard-complete/route.d.ts +2 -2
- package/.medusa/server/src/api/admin/paypal/onboard-complete/route.d.ts.map +1 -1
- package/.medusa/server/src/api/admin/paypal/onboard-complete/route.js +4 -0
- package/.medusa/server/src/api/admin/paypal/onboard-complete/route.js.map +1 -1
- package/.medusa/server/src/api/middlewares.d.ts.map +1 -1
- package/.medusa/server/src/api/middlewares.js +16 -1
- package/.medusa/server/src/api/middlewares.js.map +1 -1
- package/.medusa/server/src/api/store/paypal/capture-order/route.d.ts.map +1 -1
- package/.medusa/server/src/api/store/paypal/capture-order/route.js +45 -16
- package/.medusa/server/src/api/store/paypal/capture-order/route.js.map +1 -1
- package/.medusa/server/src/api/store/paypal/config/route.d.ts.map +1 -1
- package/.medusa/server/src/api/store/paypal/config/route.js +7 -1
- package/.medusa/server/src/api/store/paypal/config/route.js.map +1 -1
- package/.medusa/server/src/api/store/paypal/onboard-return/route.d.ts.map +1 -1
- package/.medusa/server/src/api/store/paypal/onboard-return/route.js +24 -2
- package/.medusa/server/src/api/store/paypal/onboard-return/route.js.map +1 -1
- package/.medusa/server/src/api/store/paypal/webhook/route.d.ts.map +1 -1
- package/.medusa/server/src/api/store/paypal/webhook/route.js +22 -48
- package/.medusa/server/src/api/store/paypal/webhook/route.js.map +1 -1
- package/.medusa/server/src/api/utils/rate-limit.d.ts +3 -0
- package/.medusa/server/src/api/utils/rate-limit.d.ts.map +1 -0
- package/.medusa/server/src/api/utils/rate-limit.js +92 -0
- package/.medusa/server/src/api/utils/rate-limit.js.map +1 -0
- package/.medusa/server/src/jobs/paypal-webhook-retry.d.ts.map +1 -1
- package/.medusa/server/src/jobs/paypal-webhook-retry.js +115 -90
- package/.medusa/server/src/jobs/paypal-webhook-retry.js.map +1 -1
- package/.medusa/server/src/modules/paypal/payment-provider/base-provider.d.ts +48 -0
- package/.medusa/server/src/modules/paypal/payment-provider/base-provider.d.ts.map +1 -0
- package/.medusa/server/src/modules/paypal/payment-provider/base-provider.js +159 -0
- package/.medusa/server/src/modules/paypal/payment-provider/base-provider.js.map +1 -0
- package/.medusa/server/src/modules/paypal/payment-provider/card-service.d.ts +5 -20
- package/.medusa/server/src/modules/paypal/payment-provider/card-service.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/payment-provider/card-service.js +27 -160
- package/.medusa/server/src/modules/paypal/payment-provider/card-service.js.map +1 -1
- package/.medusa/server/src/modules/paypal/payment-provider/service.d.ts +5 -20
- package/.medusa/server/src/modules/paypal/payment-provider/service.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/payment-provider/service.js +21 -138
- package/.medusa/server/src/modules/paypal/payment-provider/service.js.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/amounts.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/amounts.js +10 -0
- package/.medusa/server/src/modules/paypal/utils/amounts.js.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/credential-resolver.d.ts +1 -1
- package/.medusa/server/src/modules/paypal/utils/credential-resolver.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/credential-resolver.js +27 -26
- package/.medusa/server/src/modules/paypal/utils/credential-resolver.js.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/partner.d.ts +9 -0
- package/.medusa/server/src/modules/paypal/utils/partner.d.ts.map +1 -0
- package/.medusa/server/src/modules/paypal/utils/partner.js +12 -0
- package/.medusa/server/src/modules/paypal/utils/partner.js.map +1 -0
- package/.medusa/server/src/modules/paypal/utils/payment-session.d.ts +0 -5
- package/.medusa/server/src/modules/paypal/utils/payment-session.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/payment-session.js +37 -18
- package/.medusa/server/src/modules/paypal/utils/payment-session.js.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/secret-crypto.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/secret-crypto.js +30 -1
- package/.medusa/server/src/modules/paypal/utils/secret-crypto.js.map +1 -1
- package/.medusa/server/src/subscribers/paypal-webhook-process.d.ts +19 -0
- package/.medusa/server/src/subscribers/paypal-webhook-process.d.ts.map +1 -0
- package/.medusa/server/src/subscribers/paypal-webhook-process.js +107 -0
- package/.medusa/server/src/subscribers/paypal-webhook-process.js.map +1 -0
- package/CHANGELOG.md +73 -0
- package/package.json +4 -2
- package/src/api/admin/paypal/onboard-complete/route.ts +10 -2
- package/src/api/middlewares.ts +16 -1
- package/src/api/store/paypal/capture-order/route.ts +60 -22
- package/src/api/store/paypal/config/route.ts +8 -1
- package/src/api/store/paypal/onboard-return/route.ts +31 -6
- package/src/api/store/paypal/webhook/route.ts +24 -60
- package/src/api/utils/rate-limit.ts +105 -0
- package/src/jobs/paypal-webhook-retry.ts +132 -94
- package/src/modules/paypal/payment-provider/base-provider.ts +192 -0
- package/src/modules/paypal/payment-provider/card-service.ts +28 -196
- package/src/modules/paypal/payment-provider/service.ts +23 -164
- package/src/modules/paypal/utils/amounts.ts +10 -0
- package/src/modules/paypal/utils/credential-resolver.ts +32 -27
- package/src/modules/paypal/utils/partner.ts +8 -0
- package/src/modules/paypal/utils/payment-session.ts +44 -19
- package/src/modules/paypal/utils/secret-crypto.ts +36 -1
- package/src/subscribers/paypal-webhook-process.ts +127 -0
- package/.medusa/server/src/modules/paypal/clients/paypal-seller.client.d.ts +0 -15
- package/.medusa/server/src/modules/paypal/clients/paypal-seller.client.d.ts.map +0 -1
- package/.medusa/server/src/modules/paypal/clients/paypal-seller.client.js +0 -68
- package/.medusa/server/src/modules/paypal/clients/paypal-seller.client.js.map +0 -1
- package/src/modules/paypal/clients/paypal-seller.client.ts +0 -64
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { randomUUID } from "crypto"
|
|
1
|
+
import { MedusaError } from "@medusajs/framework/utils"
|
|
3
2
|
import type {
|
|
4
3
|
AuthorizePaymentInput,
|
|
5
4
|
AuthorizePaymentOutput,
|
|
@@ -7,10 +6,6 @@ import type {
|
|
|
7
6
|
CapturePaymentOutput,
|
|
8
7
|
CancelPaymentInput,
|
|
9
8
|
CancelPaymentOutput,
|
|
10
|
-
CreateAccountHolderInput,
|
|
11
|
-
CreateAccountHolderOutput,
|
|
12
|
-
DeletePaymentInput,
|
|
13
|
-
DeletePaymentOutput,
|
|
14
9
|
GetPaymentStatusInput,
|
|
15
10
|
GetPaymentStatusOutput,
|
|
16
11
|
InitiatePaymentInput,
|
|
@@ -21,134 +16,26 @@ import type {
|
|
|
21
16
|
RetrievePaymentOutput,
|
|
22
17
|
UpdatePaymentInput,
|
|
23
18
|
UpdatePaymentOutput,
|
|
24
|
-
ProviderWebhookPayload,
|
|
25
|
-
WebhookActionResult,
|
|
26
19
|
} from "@medusajs/framework/types"
|
|
27
20
|
import { formatAmountForPayPal, toAmountNumber } from "../utils/amounts"
|
|
28
21
|
import {
|
|
29
22
|
assertPayPalCurrencySupported,
|
|
30
23
|
normalizeCurrencyCode,
|
|
31
24
|
} from "../utils/currencies"
|
|
32
|
-
import {
|
|
33
|
-
import {
|
|
34
|
-
import { paypalFetch } from "../utils/paypal-fetch"
|
|
25
|
+
import { PAYPAL_PARTNER_ATTRIBUTION_ID } from "../utils/partner"
|
|
26
|
+
import { paypalFetch, paypalFetchWithRetry } from "../utils/paypal-fetch"
|
|
35
27
|
import {
|
|
36
28
|
extractCaptureStatus,
|
|
37
29
|
isCaptureCompleted,
|
|
38
30
|
isRefundFailureStatus,
|
|
39
|
-
mapPayPalCaptureStatus,
|
|
40
31
|
} from "./status-utils"
|
|
32
|
+
import { PayPalProviderBase } from "./base-provider"
|
|
41
33
|
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
const BN_CODE = "MBJTechnolabs_SI_SPB"
|
|
45
|
-
|
|
46
|
-
function generateSessionId() {
|
|
47
|
-
try {
|
|
48
|
-
return randomUUID()
|
|
49
|
-
} catch {
|
|
50
|
-
return `pp_${Date.now()}_${Math.random().toString(16).slice(2)}`
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
class PayPalPaymentProvider extends AbstractPaymentProvider<Options> {
|
|
34
|
+
class PayPalPaymentProvider extends PayPalProviderBase {
|
|
55
35
|
static identifier = "paypal"
|
|
56
36
|
|
|
57
|
-
protected readonly
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
constructor(cradle: Record<string, any>, options: Options) {
|
|
61
|
-
super(cradle, options)
|
|
62
|
-
this.options_ = options
|
|
63
|
-
const pg = PayPalPaymentProvider.resolvePgConnection(cradle)
|
|
64
|
-
this.paypal = new PayPalCredentialResolver(pg)
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
private static resolvePgConnection(cradle: Record<string, any>): any {
|
|
68
|
-
for (const key of ["__pg_connection__", "pgConnection", "pg_connection"]) {
|
|
69
|
-
try {
|
|
70
|
-
const val = cradle[key]
|
|
71
|
-
if (val) return val
|
|
72
|
-
} catch {}
|
|
73
|
-
}
|
|
74
|
-
throw new Error(
|
|
75
|
-
"Could not resolve pgConnection from the payment module container. " +
|
|
76
|
-
"Ensure the paypal module is registered in medusa-config and the database is accessible."
|
|
77
|
-
)
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
async resolveSettings() {
|
|
81
|
-
return this.paypal.getSettings()
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
private async resolveCurrencyOverride() {
|
|
85
|
-
const { apiDetails } = await this.resolveSettings()
|
|
86
|
-
if (typeof apiDetails.currency_code === "string" && (apiDetails.currency_code as string).trim()) {
|
|
87
|
-
return normalizeCurrencyCode(apiDetails.currency_code as string)
|
|
88
|
-
}
|
|
89
|
-
return normalizeCurrencyCode(process.env.PAYPAL_CURRENCY || "EUR")
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
private async getPayPalAccessToken() {
|
|
93
|
-
return this.paypal.getAccessToken()
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
private async getOrderDetails(orderId: string) {
|
|
97
|
-
const { accessToken, base } = await this.getPayPalAccessToken()
|
|
98
|
-
const resp = await paypalFetch(`${base}/v2/checkout/orders/${encodeURIComponent(orderId)}`, {
|
|
99
|
-
method: "GET",
|
|
100
|
-
headers: {
|
|
101
|
-
Authorization: `Bearer ${accessToken}`,
|
|
102
|
-
"Content-Type": "application/json",
|
|
103
|
-
"PayPal-Partner-Attribution-Id": BN_CODE,
|
|
104
|
-
},
|
|
105
|
-
})
|
|
106
|
-
|
|
107
|
-
const text = await resp.text()
|
|
108
|
-
if (!resp.ok) {
|
|
109
|
-
throw new Error(`PayPal get order error (${resp.status}): ${text}`)
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
return JSON.parse(text)
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
private getIdempotencyKey(
|
|
116
|
-
input: { context?: { idempotency_key?: string } },
|
|
117
|
-
suffix: string
|
|
118
|
-
) {
|
|
119
|
-
const key = input?.context?.idempotency_key?.trim()
|
|
120
|
-
if (key) {
|
|
121
|
-
return `${key}-${suffix}`
|
|
122
|
-
}
|
|
123
|
-
return `pp-${suffix}-${generateSessionId()}`
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
private async normalizePaymentData(input: { data?: Record<string, unknown> }) {
|
|
127
|
-
const data = (input.data || {}) as Record<string, any>
|
|
128
|
-
const amount = toAmountNumber(data.amount)
|
|
129
|
-
const currencyOverride = await this.resolveCurrencyOverride()
|
|
130
|
-
const currencyCode = normalizeCurrencyCode(
|
|
131
|
-
data.currency_code || currencyOverride || "EUR"
|
|
132
|
-
)
|
|
133
|
-
assertPayPalCurrencySupported({
|
|
134
|
-
currencyCode,
|
|
135
|
-
paypalCurrencyOverride: currencyOverride,
|
|
136
|
-
})
|
|
137
|
-
return { data, amount, currencyCode }
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
private mapCaptureStatus(status?: string) {
|
|
141
|
-
return mapPayPalCaptureStatus(status)
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
private mapAuthorizationStatus(status?: string) {
|
|
145
|
-
const normalized = String(status || "").toUpperCase()
|
|
146
|
-
if (!normalized) return null
|
|
147
|
-
if (["CREATED", "APPROVED", "PENDING"].includes(normalized)) return "authorized"
|
|
148
|
-
if (["VOIDED", "EXPIRED"].includes(normalized)) return "canceled"
|
|
149
|
-
if (["DENIED", "DECLINED", "FAILED"].includes(normalized)) return "error"
|
|
150
|
-
return null
|
|
151
|
-
}
|
|
37
|
+
protected readonly sessionPrefix = "pp"
|
|
38
|
+
protected readonly idempotencyPrefix = "pp"
|
|
152
39
|
|
|
153
40
|
private serializeError(error: unknown) {
|
|
154
41
|
if (error instanceof Error) {
|
|
@@ -167,17 +54,6 @@ class PayPalPaymentProvider extends AbstractPaymentProvider<Options> {
|
|
|
167
54
|
return { message: String(error) }
|
|
168
55
|
}
|
|
169
56
|
|
|
170
|
-
private mapOrderStatus(status?: string) {
|
|
171
|
-
const normalized = String(status || "").toUpperCase()
|
|
172
|
-
if (!normalized) return "pending"
|
|
173
|
-
if (normalized === "COMPLETED") return "captured"
|
|
174
|
-
if (normalized === "APPROVED") return "authorized"
|
|
175
|
-
if (["VOIDED", "CANCELLED"].includes(normalized)) return "canceled"
|
|
176
|
-
if (["CREATED", "SAVED", "PAYER_ACTION_REQUIRED"].includes(normalized)) return "pending"
|
|
177
|
-
if (["FAILED", "EXPIRED"].includes(normalized)) return "error"
|
|
178
|
-
return "pending"
|
|
179
|
-
}
|
|
180
|
-
|
|
181
57
|
private async recordFailure(eventType: string, metadata?: Record<string, unknown>) {
|
|
182
58
|
await this.paypal.recordAuditEvent(eventType, metadata)
|
|
183
59
|
await this.paypal.recordMetric(eventType, metadata)
|
|
@@ -191,20 +67,6 @@ class PayPalPaymentProvider extends AbstractPaymentProvider<Options> {
|
|
|
191
67
|
await this.paypal.recordAuditEvent(eventType, metadata)
|
|
192
68
|
}
|
|
193
69
|
|
|
194
|
-
async createAccountHolder(
|
|
195
|
-
input: CreateAccountHolderInput
|
|
196
|
-
): Promise<CreateAccountHolderOutput> {
|
|
197
|
-
const customerId = input.context?.customer?.id
|
|
198
|
-
const externalId = customerId ? `paypal_${customerId}` : `paypal_${generateSessionId()}`
|
|
199
|
-
return {
|
|
200
|
-
id: externalId,
|
|
201
|
-
data: {
|
|
202
|
-
email: input.context?.customer?.email || null,
|
|
203
|
-
customer_id: customerId || null,
|
|
204
|
-
},
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
|
|
208
70
|
async initiatePayment(input: InitiatePaymentInput): Promise<InitiatePaymentOutput> {
|
|
209
71
|
const providerId = (input.data as Record<string, any> | undefined)?.provider_id
|
|
210
72
|
try {
|
|
@@ -217,7 +79,7 @@ class PayPalPaymentProvider extends AbstractPaymentProvider<Options> {
|
|
|
217
79
|
paypalCurrencyOverride: currencyOverride,
|
|
218
80
|
})
|
|
219
81
|
return {
|
|
220
|
-
id: generateSessionId(),
|
|
82
|
+
id: this.generateSessionId(),
|
|
221
83
|
data: {
|
|
222
84
|
...(input.data || {}),
|
|
223
85
|
...(providerId ? { provider_id: providerId } : {}),
|
|
@@ -364,7 +226,7 @@ class PayPalPaymentProvider extends AbstractPaymentProvider<Options> {
|
|
|
364
226
|
Authorization: `Bearer ${accessToken}`,
|
|
365
227
|
"Content-Type": "application/json",
|
|
366
228
|
"PayPal-Request-Id": requestId,
|
|
367
|
-
"PayPal-Partner-Attribution-Id":
|
|
229
|
+
"PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
|
|
368
230
|
},
|
|
369
231
|
body: JSON.stringify(orderPayload),
|
|
370
232
|
})
|
|
@@ -401,7 +263,7 @@ class PayPalPaymentProvider extends AbstractPaymentProvider<Options> {
|
|
|
401
263
|
Authorization: `Bearer ${accessToken}`,
|
|
402
264
|
"Content-Type": "application/json",
|
|
403
265
|
"PayPal-Request-Id": `${requestId}-auth`,
|
|
404
|
-
"PayPal-Partner-Attribution-Id":
|
|
266
|
+
"PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
|
|
405
267
|
},
|
|
406
268
|
}
|
|
407
269
|
)
|
|
@@ -588,7 +450,7 @@ class PayPalPaymentProvider extends AbstractPaymentProvider<Options> {
|
|
|
588
450
|
Authorization: `Bearer ${accessToken}`,
|
|
589
451
|
"Content-Type": "application/json",
|
|
590
452
|
"PayPal-Request-Id": `${requestId}-auth`,
|
|
591
|
-
"PayPal-Partner-Attribution-Id":
|
|
453
|
+
"PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
|
|
592
454
|
},
|
|
593
455
|
}
|
|
594
456
|
)
|
|
@@ -644,13 +506,16 @@ class PayPalPaymentProvider extends AbstractPaymentProvider<Options> {
|
|
|
644
506
|
}
|
|
645
507
|
}
|
|
646
508
|
|
|
647
|
-
|
|
509
|
+
// Retry transient 5xx/429/timeout: the PayPal-Request-Id makes the
|
|
510
|
+
// capture idempotent, so a retry after a network blip re-uses the same
|
|
511
|
+
// capture instead of double-charging.
|
|
512
|
+
const ppResp = await paypalFetchWithRetry(captureUrl, {
|
|
648
513
|
method: "POST",
|
|
649
514
|
headers: {
|
|
650
515
|
Authorization: `Bearer ${accessToken}`,
|
|
651
516
|
"Content-Type": "application/json",
|
|
652
517
|
"PayPal-Request-Id": requestId,
|
|
653
|
-
"PayPal-Partner-Attribution-Id":
|
|
518
|
+
"PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
|
|
654
519
|
},
|
|
655
520
|
body: JSON.stringify(capturePayload),
|
|
656
521
|
})
|
|
@@ -787,13 +652,16 @@ class PayPalPaymentProvider extends AbstractPaymentProvider<Options> {
|
|
|
787
652
|
refundPayload.note_to_payer = refundReason.slice(0, 255)
|
|
788
653
|
}
|
|
789
654
|
|
|
790
|
-
|
|
655
|
+
// Retry transient 5xx/429/timeout: the PayPal-Request-Id (which includes
|
|
656
|
+
// the refund amount) makes the refund idempotent, so a retry after a
|
|
657
|
+
// network blip re-uses the same refund instead of double-refunding.
|
|
658
|
+
const ppResp = await paypalFetchWithRetry(`${base}/v2/payments/captures/${encodeURIComponent(captureId)}/refund`, {
|
|
791
659
|
method: "POST",
|
|
792
660
|
headers: {
|
|
793
661
|
Authorization: `Bearer ${accessToken}`,
|
|
794
662
|
"Content-Type": "application/json",
|
|
795
663
|
"PayPal-Request-Id": requestId,
|
|
796
|
-
"PayPal-Partner-Attribution-Id":
|
|
664
|
+
"PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
|
|
797
665
|
},
|
|
798
666
|
body: JSON.stringify(refundPayload),
|
|
799
667
|
})
|
|
@@ -903,7 +771,7 @@ class PayPalPaymentProvider extends AbstractPaymentProvider<Options> {
|
|
|
903
771
|
Authorization: `Bearer ${accessToken}`,
|
|
904
772
|
"Content-Type": "application/json",
|
|
905
773
|
"PayPal-Request-Id": requestId,
|
|
906
|
-
"PayPal-Partner-Attribution-Id":
|
|
774
|
+
"PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
|
|
907
775
|
},
|
|
908
776
|
}
|
|
909
777
|
)
|
|
@@ -933,7 +801,7 @@ class PayPalPaymentProvider extends AbstractPaymentProvider<Options> {
|
|
|
933
801
|
Authorization: `Bearer ${accessToken}`,
|
|
934
802
|
"Content-Type": "application/json",
|
|
935
803
|
"PayPal-Request-Id": requestId,
|
|
936
|
-
"PayPal-Partner-Attribution-Id":
|
|
804
|
+
"PayPal-Partner-Attribution-Id": PAYPAL_PARTNER_ATTRIBUTION_ID,
|
|
937
805
|
},
|
|
938
806
|
body: JSON.stringify({}),
|
|
939
807
|
})
|
|
@@ -999,15 +867,6 @@ class PayPalPaymentProvider extends AbstractPaymentProvider<Options> {
|
|
|
999
867
|
}
|
|
1000
868
|
}
|
|
1001
869
|
|
|
1002
|
-
async deletePayment(_input: DeletePaymentInput): Promise<DeletePaymentOutput> {
|
|
1003
|
-
return { data: {} }
|
|
1004
|
-
}
|
|
1005
|
-
|
|
1006
|
-
async getWebhookActionAndData(
|
|
1007
|
-
payload: ProviderWebhookPayload["payload"]
|
|
1008
|
-
): Promise<WebhookActionResult> {
|
|
1009
|
-
return getPayPalWebhookActionAndData(payload)
|
|
1010
|
-
}
|
|
1011
870
|
}
|
|
1012
871
|
|
|
1013
872
|
export default PayPalPaymentProvider
|
|
@@ -56,6 +56,12 @@ export function toAmountNumber(amount: unknown): number {
|
|
|
56
56
|
return amount
|
|
57
57
|
}
|
|
58
58
|
if (typeof amount === "string") {
|
|
59
|
+
// `Number("")` and `Number(" ")` both coerce to 0 — treat a blank string
|
|
60
|
+
// as invalid rather than let it silently become a zero amount (which would
|
|
61
|
+
// turn a partial refund/capture into a full one).
|
|
62
|
+
if (amount.trim() === "") {
|
|
63
|
+
throw new Error(`Invalid payment amount: unparseable string "${amount}"`)
|
|
64
|
+
}
|
|
59
65
|
const parsed = Number(amount)
|
|
60
66
|
if (!Number.isFinite(parsed)) {
|
|
61
67
|
throw new Error(`Invalid payment amount: unparseable string "${amount}"`)
|
|
@@ -70,6 +76,10 @@ export function toAmountNumber(amount: unknown): number {
|
|
|
70
76
|
}
|
|
71
77
|
// Serialized raw form: { value: "20", precision: 20 }.
|
|
72
78
|
if (obj.value !== undefined && obj.value !== null) {
|
|
79
|
+
// Guard the blank-string-coerces-to-0 case here too (see string branch).
|
|
80
|
+
if (typeof obj.value === "string" && obj.value.trim() === "") {
|
|
81
|
+
throw new Error(`Invalid payment amount: unparseable BigNumber value "${obj.value}"`)
|
|
82
|
+
}
|
|
73
83
|
const parsed = Number(obj.value)
|
|
74
84
|
if (!Number.isFinite(parsed)) {
|
|
75
85
|
throw new Error(`Invalid payment amount: unparseable BigNumber value "${obj.value}"`)
|
|
@@ -12,7 +12,7 @@ interface ActiveCredentials {
|
|
|
12
12
|
client_secret: string
|
|
13
13
|
}
|
|
14
14
|
|
|
15
|
-
interface AccessTokenResult {
|
|
15
|
+
export interface AccessTokenResult {
|
|
16
16
|
accessToken: string
|
|
17
17
|
base: string
|
|
18
18
|
}
|
|
@@ -224,32 +224,37 @@ export class PayPalCredentialResolver {
|
|
|
224
224
|
|
|
225
225
|
async recordMetric(name: string, metadata?: Record<string, unknown>) {
|
|
226
226
|
try {
|
|
227
|
-
const
|
|
228
|
-
.
|
|
229
|
-
.
|
|
230
|
-
|
|
231
|
-
const
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
227
|
+
const id = `ppmet_${Date.now().toString(36)}${Math.random()
|
|
228
|
+
.toString(36)
|
|
229
|
+
.slice(2, 8)}`
|
|
230
|
+
const nowIso = new Date().toISOString()
|
|
231
|
+
const metaJson = JSON.stringify(metadata || {})
|
|
232
|
+
|
|
233
|
+
// Atomic upsert so concurrent captures/refunds don't lose metric updates
|
|
234
|
+
// via a read-modify-write race. The `count` increment happens inside a
|
|
235
|
+
// single statement (not read in JS then written back), and the unique
|
|
236
|
+
// constraint on `name` drives the ON CONFLICT so there is no insert/update
|
|
237
|
+
// decision to race on either. Any provided metadata is merged first, then
|
|
238
|
+
// `count`/`last_recorded_at` are applied last so metadata can't clobber
|
|
239
|
+
// the running count.
|
|
240
|
+
await this.db.raw(
|
|
241
|
+
`INSERT INTO paypal_metric (id, name, data, created_at, updated_at)
|
|
242
|
+
VALUES (
|
|
243
|
+
?, ?,
|
|
244
|
+
(?::jsonb || jsonb_build_object('count', 1, 'last_recorded_at', ?::text)),
|
|
245
|
+
now(), now()
|
|
246
|
+
)
|
|
247
|
+
ON CONFLICT (name) DO UPDATE SET
|
|
248
|
+
data = paypal_metric.data
|
|
249
|
+
|| ?::jsonb
|
|
250
|
+
|| jsonb_build_object(
|
|
251
|
+
'count', COALESCE((paypal_metric.data->>'count')::bigint, 0) + 1,
|
|
252
|
+
'last_recorded_at', ?::text
|
|
253
|
+
),
|
|
254
|
+
deleted_at = NULL,
|
|
255
|
+
updated_at = now()`,
|
|
256
|
+
[id, name, metaJson, nowIso, metaJson, nowIso]
|
|
257
|
+
)
|
|
253
258
|
} catch {
|
|
254
259
|
// metrics must never break the payment flow
|
|
255
260
|
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PayPal Partner Attribution Id (BN code) for this integration.
|
|
3
|
+
*
|
|
4
|
+
* Centralized here so the value lives in exactly one place instead of being
|
|
5
|
+
* re-declared across the providers, credential resolver, and store routes.
|
|
6
|
+
* Sent as the `PayPal-Partner-Attribution-Id` header on outbound PayPal calls.
|
|
7
|
+
*/
|
|
8
|
+
export const PAYPAL_PARTNER_ATTRIBUTION_ID = "MBJTechnolabs_SI_SPB"
|
|
@@ -82,32 +82,57 @@ export function getStoredPayPalOrderId(
|
|
|
82
82
|
* Shallow-merge `extraData` into a payment session's `data`, preserving the
|
|
83
83
|
* session's amount/currency. Callers that update the nested `paypal` object are
|
|
84
84
|
* responsible for spreading its existing keys (see `getStoredPayPalOrderId`).
|
|
85
|
+
*
|
|
86
|
+
* The write is retried a few times before giving up: when this runs right after
|
|
87
|
+
* a successful PayPal capture, a transient DB blip that loses the write means
|
|
88
|
+
* the money is captured but Medusa never records it. A bounded retry closes the
|
|
89
|
+
* common transient-failure window; if every attempt fails the error is
|
|
90
|
+
* re-thrown (with a CRITICAL log for capture/order data) so the caller can react
|
|
91
|
+
* — the webhook and paypal-complete's live re-derivation remain the backstop.
|
|
85
92
|
*/
|
|
93
|
+
const SESSION_UPDATE_MAX_ATTEMPTS = 3
|
|
94
|
+
const SESSION_UPDATE_BASE_DELAY_MS = 200
|
|
95
|
+
|
|
86
96
|
export async function updatePayPalSessionData(
|
|
87
97
|
sessionId: string,
|
|
88
98
|
extraData: Record<string, any>,
|
|
89
99
|
scope: any
|
|
90
100
|
): Promise<void> {
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
id: sessionId,
|
|
97
|
-
data
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
101
|
+
const paymentModule = scope.resolve(Modules.PAYMENT) as IPaymentModuleService
|
|
102
|
+
let lastError: unknown
|
|
103
|
+
|
|
104
|
+
for (let attempt = 1; attempt <= SESSION_UPDATE_MAX_ATTEMPTS; attempt++) {
|
|
105
|
+
try {
|
|
106
|
+
const [existing] = await paymentModule.listPaymentSessions({ id: [sessionId] }, { take: 1 })
|
|
107
|
+
const mergedData = { ...(existing?.data || {}), ...extraData }
|
|
108
|
+
await (paymentModule as any).updatePaymentSession({
|
|
109
|
+
id: sessionId,
|
|
110
|
+
data: mergedData,
|
|
111
|
+
amount: existing?.amount,
|
|
112
|
+
currency_code: existing?.currency_code,
|
|
113
|
+
})
|
|
114
|
+
return
|
|
115
|
+
} catch (e: unknown) {
|
|
116
|
+
lastError = e
|
|
117
|
+
const msg = e instanceof Error ? e.message : String(e)
|
|
118
|
+
console.warn(
|
|
119
|
+
`[PayPal] updatePayPalSessionData attempt ${attempt}/${SESSION_UPDATE_MAX_ATTEMPTS} failed:`,
|
|
120
|
+
msg
|
|
109
121
|
)
|
|
122
|
+
if (attempt < SESSION_UPDATE_MAX_ATTEMPTS) {
|
|
123
|
+
await new Promise((r) => setTimeout(r, SESSION_UPDATE_BASE_DELAY_MS * attempt))
|
|
124
|
+
}
|
|
110
125
|
}
|
|
111
|
-
throw e
|
|
112
126
|
}
|
|
127
|
+
|
|
128
|
+
const msg = lastError instanceof Error ? lastError.message : String(lastError)
|
|
129
|
+
console.error("[PayPal] updatePayPalSessionData failed after retries:", msg)
|
|
130
|
+
const hasCaptureData = "capture_id" in extraData || "order_id" in extraData
|
|
131
|
+
if (hasCaptureData) {
|
|
132
|
+
console.error(
|
|
133
|
+
"[PayPal] CRITICAL: Payment data (capture/order) was NOT persisted to session.",
|
|
134
|
+
{ sessionId, keys: Object.keys(extraData) }
|
|
135
|
+
)
|
|
136
|
+
}
|
|
137
|
+
throw lastError
|
|
113
138
|
}
|
|
@@ -101,6 +101,35 @@ export function isEncrypted(value: unknown): boolean {
|
|
|
101
101
|
)
|
|
102
102
|
}
|
|
103
103
|
|
|
104
|
+
let warnedNoKey = false
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Surface (once) that secrets are being stored without encryption-at-rest. In a
|
|
108
|
+
* production environment this is a real exposure — client_secret / access_token
|
|
109
|
+
* land in the database as plaintext — so it is worth a loud warning. Set
|
|
110
|
+
* PAYPAL_ENCRYPTION_STRICT=true to make it a hard error instead (recommended for
|
|
111
|
+
* production once a key is provisioned), which fails the write rather than
|
|
112
|
+
* persisting a plaintext secret.
|
|
113
|
+
*/
|
|
114
|
+
function assertOrWarnNoEncryptionKey(): void {
|
|
115
|
+
const strict = String(process.env.PAYPAL_ENCRYPTION_STRICT || "").toLowerCase()
|
|
116
|
+
if (strict === "true" || strict === "1") {
|
|
117
|
+
throw new Error(
|
|
118
|
+
"PAYPAL_ENCRYPTION_STRICT is enabled but PAYPAL_ENCRYPTION_KEY is not set. " +
|
|
119
|
+
"Set PAYPAL_ENCRYPTION_KEY to encrypt PayPal secrets at rest, or disable strict mode."
|
|
120
|
+
)
|
|
121
|
+
}
|
|
122
|
+
if (!warnedNoKey) {
|
|
123
|
+
warnedNoKey = true
|
|
124
|
+
const inProd = process.env.NODE_ENV === "production"
|
|
125
|
+
console.warn(
|
|
126
|
+
`[PayPal]${inProd ? " WARNING (production):" : ""} PAYPAL_ENCRYPTION_KEY is not set — ` +
|
|
127
|
+
"PayPal secrets (client_secret, access_token) are stored UNENCRYPTED. " +
|
|
128
|
+
"Set PAYPAL_ENCRYPTION_KEY to enable AES-256-GCM encryption at rest."
|
|
129
|
+
)
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
104
133
|
/**
|
|
105
134
|
* Encrypt a secret for storage. Returns the input unchanged when no key is
|
|
106
135
|
* configured or when the value is empty/already encrypted. Always writes the
|
|
@@ -111,7 +140,13 @@ export function encryptSecret<T extends string | null | undefined>(value: T): T
|
|
|
111
140
|
return value
|
|
112
141
|
}
|
|
113
142
|
const raw = getRawKey()
|
|
114
|
-
if (!raw
|
|
143
|
+
if (!raw) {
|
|
144
|
+
if (!isEncrypted(value)) {
|
|
145
|
+
assertOrWarnNoEncryptionKey()
|
|
146
|
+
}
|
|
147
|
+
return value
|
|
148
|
+
}
|
|
149
|
+
if (isEncrypted(value)) {
|
|
115
150
|
return value
|
|
116
151
|
}
|
|
117
152
|
const salt = randomBytes(SALT_LEN)
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import type { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"
|
|
2
|
+
import type PayPalModuleService from "../modules/paypal/service"
|
|
3
|
+
import {
|
|
4
|
+
computeNextRetryAt,
|
|
5
|
+
isAllowedEventType,
|
|
6
|
+
isRetryableError,
|
|
7
|
+
processPayPalWebhookEvent,
|
|
8
|
+
} from "../modules/paypal/webhook-processor"
|
|
9
|
+
|
|
10
|
+
export const PAYPAL_WEBHOOK_RECEIVED_EVENT = "paypal.webhook.received"
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Asynchronous PayPal webhook processing.
|
|
14
|
+
*
|
|
15
|
+
* The webhook route verifies the signature, persists the event (status
|
|
16
|
+
* "processing"), emits `paypal.webhook.received`, and returns 200 immediately —
|
|
17
|
+
* so PayPal's ~15s delivery timeout can't be tripped by slow downstream work and
|
|
18
|
+
* the event is never lost. This subscriber does the actual processing off the
|
|
19
|
+
* request path, using its own framework-managed container (no request-scope
|
|
20
|
+
* disposal risk). If the event bus ever drops the message, the webhook retry
|
|
21
|
+
* cron recovers events left in "processing" past a staleness threshold, so
|
|
22
|
+
* delivery is guaranteed either way.
|
|
23
|
+
*/
|
|
24
|
+
export default async function paypalWebhookProcessHandler({
|
|
25
|
+
event,
|
|
26
|
+
container,
|
|
27
|
+
}: SubscriberArgs<{ id: string }>) {
|
|
28
|
+
const recordId = event?.data?.id
|
|
29
|
+
if (!recordId) return
|
|
30
|
+
|
|
31
|
+
const paypal = container.resolve<PayPalModuleService>("paypal_onboarding")
|
|
32
|
+
|
|
33
|
+
let record: any
|
|
34
|
+
try {
|
|
35
|
+
const rows = await paypal.listPayPalWebhookEvents({ id: [recordId] }, { take: 1 })
|
|
36
|
+
record = rows?.[0]
|
|
37
|
+
} catch (e: any) {
|
|
38
|
+
console.error("[PayPal] webhook subscriber: failed to load event", {
|
|
39
|
+
id: recordId,
|
|
40
|
+
error: e?.message,
|
|
41
|
+
})
|
|
42
|
+
return
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
if (!record) {
|
|
46
|
+
console.warn("[PayPal] webhook subscriber: event not found", { id: recordId })
|
|
47
|
+
return
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// Only process events still queued for the first attempt. Anything already
|
|
51
|
+
// processed/failed/ignored/dead-lettered is owned by the retry cron; skipping
|
|
52
|
+
// here keeps the subscriber idempotent if the bus delivers more than once.
|
|
53
|
+
if (String(record.status) !== "processing") {
|
|
54
|
+
return
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const eventType = String(record.event_type || "")
|
|
58
|
+
|
|
59
|
+
if (!isAllowedEventType(eventType)) {
|
|
60
|
+
await paypal
|
|
61
|
+
.updateWebhookEventRecord({ id: recordId, status: "ignored", processed_at: new Date() })
|
|
62
|
+
.catch(() => {})
|
|
63
|
+
return
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
try {
|
|
67
|
+
const payload = (record.payload || {}) as Record<string, any>
|
|
68
|
+
const processed = await processPayPalWebhookEvent(container, { eventType, payload })
|
|
69
|
+
|
|
70
|
+
await paypal
|
|
71
|
+
.updateWebhookEventRecord({
|
|
72
|
+
id: recordId,
|
|
73
|
+
status: "processed",
|
|
74
|
+
processed_at: new Date(),
|
|
75
|
+
resource_id:
|
|
76
|
+
processed.refundId || processed.captureId || processed.orderId || null,
|
|
77
|
+
})
|
|
78
|
+
.catch(() => {})
|
|
79
|
+
|
|
80
|
+
console.info("[PayPal] webhook: processed (async)", {
|
|
81
|
+
id: recordId,
|
|
82
|
+
event_type: eventType,
|
|
83
|
+
order_id: processed.orderId,
|
|
84
|
+
capture_id: processed.captureId,
|
|
85
|
+
refund_id: processed.refundId,
|
|
86
|
+
cart_id: processed.cartId,
|
|
87
|
+
session_updated: processed.sessionUpdated,
|
|
88
|
+
})
|
|
89
|
+
|
|
90
|
+
await paypal.recordMetric("webhook_success").catch(() => {})
|
|
91
|
+
} catch (e: any) {
|
|
92
|
+
const retryable = isRetryableError(e)
|
|
93
|
+
const nextStatus = retryable ? "failed" : "dead_letter"
|
|
94
|
+
|
|
95
|
+
await paypal
|
|
96
|
+
.updateWebhookEventRecord({
|
|
97
|
+
id: recordId,
|
|
98
|
+
status: nextStatus,
|
|
99
|
+
attempt_count: 1,
|
|
100
|
+
next_retry_at: retryable ? computeNextRetryAt(1) : null,
|
|
101
|
+
last_error: e?.message || String(e),
|
|
102
|
+
})
|
|
103
|
+
.catch(() => {})
|
|
104
|
+
|
|
105
|
+
await paypal
|
|
106
|
+
.recordAuditEvent("webhook_processing_failed", {
|
|
107
|
+
event_id: record.event_id,
|
|
108
|
+
event_type: eventType,
|
|
109
|
+
retryable,
|
|
110
|
+
message: e?.message || String(e),
|
|
111
|
+
})
|
|
112
|
+
.catch(() => {})
|
|
113
|
+
|
|
114
|
+
await paypal.recordMetric("webhook_failed").catch(() => {})
|
|
115
|
+
|
|
116
|
+
console.error("[PayPal] webhook: processing failed (async)", {
|
|
117
|
+
id: recordId,
|
|
118
|
+
event_type: eventType,
|
|
119
|
+
retryable,
|
|
120
|
+
error: e?.message,
|
|
121
|
+
})
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export const config: SubscriberConfig = {
|
|
126
|
+
event: PAYPAL_WEBHOOK_RECEIVED_EVENT,
|
|
127
|
+
}
|