@easypayment/medusa-payment-paypal 1.1.1 → 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.
- package/.medusa/server/src/admin/index.js +7 -7
- package/.medusa/server/src/admin/index.mjs +7 -7
- package/.medusa/server/src/api/hooks/paypal/onboard-return/route.d.ts +16 -0
- package/.medusa/server/src/api/hooks/paypal/onboard-return/route.d.ts.map +1 -0
- package/.medusa/server/src/api/hooks/paypal/onboard-return/route.js +20 -0
- package/.medusa/server/src/api/hooks/paypal/onboard-return/route.js.map +1 -0
- package/.medusa/server/src/api/hooks/paypal/webhook/route.d.ts +18 -0
- package/.medusa/server/src/api/hooks/paypal/webhook/route.d.ts.map +1 -0
- package/.medusa/server/src/api/hooks/paypal/webhook/route.js +22 -0
- package/.medusa/server/src/api/hooks/paypal/webhook/route.js.map +1 -0
- package/.medusa/server/src/api/middlewares.d.ts.map +1 -1
- package/.medusa/server/src/api/middlewares.js +24 -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 +66 -13
- 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 +8 -0
- package/.medusa/server/src/api/store/paypal/config/route.js.map +1 -1
- package/.medusa/server/src/api/store/paypal/create-order/route.d.ts.map +1 -1
- package/.medusa/server/src/api/store/paypal/create-order/route.js +63 -9
- package/.medusa/server/src/api/store/paypal/create-order/route.js.map +1 -1
- package/.medusa/server/src/api/store/paypal-complete/route.js +1 -1
- package/.medusa/server/src/api/store/paypal-complete/route.js.map +1 -1
- package/.medusa/server/src/api/utils/rate-limit.d.ts +13 -1
- package/.medusa/server/src/api/utils/rate-limit.d.ts.map +1 -1
- package/.medusa/server/src/api/utils/rate-limit.js +18 -7
- package/.medusa/server/src/api/utils/rate-limit.js.map +1 -1
- package/.medusa/server/src/jobs/paypal-webhook-retry.d.ts.map +1 -1
- package/.medusa/server/src/jobs/paypal-webhook-retry.js +4 -0
- package/.medusa/server/src/jobs/paypal-webhook-retry.js.map +1 -1
- package/.medusa/server/src/modules/paypal/payment-provider/base-provider.d.ts +47 -3
- package/.medusa/server/src/modules/paypal/payment-provider/base-provider.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/payment-provider/base-provider.js +73 -0
- package/.medusa/server/src/modules/paypal/payment-provider/base-provider.js.map +1 -1
- 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 +415 -285
- 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 +0 -4
- package/.medusa/server/src/modules/paypal/payment-provider/service.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/payment-provider/service.js +140 -151
- package/.medusa/server/src/modules/paypal/payment-provider/service.js.map +1 -1
- package/.medusa/server/src/modules/paypal/service.d.ts +7 -0
- package/.medusa/server/src/modules/paypal/service.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/service.js +135 -13
- package/.medusa/server/src/modules/paypal/service.js.map +1 -1
- package/.medusa/server/src/modules/paypal/types/config.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/types/config.js +13 -0
- package/.medusa/server/src/modules/paypal/types/config.js.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/amounts.d.ts +1 -1
- package/.medusa/server/src/modules/paypal/utils/credential-resolver.d.ts +10 -0
- package/.medusa/server/src/modules/paypal/utils/credential-resolver.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/credential-resolver.js +49 -34
- package/.medusa/server/src/modules/paypal/utils/credential-resolver.js.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/metrics.d.ts +18 -0
- package/.medusa/server/src/modules/paypal/utils/metrics.d.ts.map +1 -0
- package/.medusa/server/src/modules/paypal/utils/metrics.js +45 -0
- package/.medusa/server/src/modules/paypal/utils/metrics.js.map +1 -0
- package/.medusa/server/src/modules/paypal/utils/paypal-fetch.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/paypal-fetch.js +45 -28
- package/.medusa/server/src/modules/paypal/utils/paypal-fetch.js.map +1 -1
- package/.medusa/server/src/modules/paypal/webhook-processor.d.ts +27 -0
- package/.medusa/server/src/modules/paypal/webhook-processor.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/webhook-processor.js +170 -9
- package/.medusa/server/src/modules/paypal/webhook-processor.js.map +1 -1
- package/.medusa/server/src/subscribers/paypal-webhook-process.d.ts.map +1 -1
- package/.medusa/server/src/subscribers/paypal-webhook-process.js +4 -0
- package/.medusa/server/src/subscribers/paypal-webhook-process.js.map +1 -1
- package/CHANGELOG.md +208 -73
- package/README.md +175 -184
- package/package.json +91 -90
- package/src/api/hooks/paypal/onboard-return/route.ts +15 -0
- package/src/api/hooks/paypal/webhook/route.ts +17 -0
- package/src/api/middlewares.ts +24 -1
- package/src/api/store/paypal/capture-order/route.ts +83 -12
- package/src/api/store/paypal/config/route.ts +8 -0
- package/src/api/store/paypal/create-order/route.ts +73 -9
- package/src/api/store/paypal-complete/route.ts +1 -1
- package/src/api/utils/rate-limit.ts +31 -7
- package/src/jobs/paypal-webhook-retry.ts +4 -0
- package/src/modules/paypal/payment-provider/base-provider.ts +83 -0
- package/src/modules/paypal/payment-provider/card-service.ts +277 -136
- package/src/modules/paypal/payment-provider/service.ts +149 -186
- package/src/modules/paypal/service.ts +1703 -1554
- package/src/modules/paypal/types/config.ts +16 -0
- package/src/modules/paypal/utils/credential-resolver.ts +45 -36
- package/src/modules/paypal/utils/metrics.ts +48 -0
- package/src/modules/paypal/utils/paypal-fetch.ts +58 -29
- package/src/modules/paypal/webhook-processor.ts +195 -10
- package/src/subscribers/paypal-webhook-process.ts +4 -0
|
@@ -22,7 +22,23 @@ const STATIC_CFG: PayPalModuleConfig = {
|
|
|
22
22
|
alertWebhookUrls: [],
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
+
let warnedGeneratedNonce = false
|
|
26
|
+
|
|
25
27
|
function generateSellerNonce(): string {
|
|
28
|
+
// The nonce doubles as the OAuth code_verifier for the onboarding exchange,
|
|
29
|
+
// so every instance must agree on it. It is persisted into settings on first
|
|
30
|
+
// boot, but two instances booting simultaneously can race to persist
|
|
31
|
+
// different generated values — an onboarding link minted against the losing
|
|
32
|
+
// nonce then fails its token exchange with an opaque invalid_grant. Pinning
|
|
33
|
+
// PAYPAL_SELLER_NONCE removes the race entirely.
|
|
34
|
+
if (!warnedGeneratedNonce) {
|
|
35
|
+
warnedGeneratedNonce = true
|
|
36
|
+
console.warn(
|
|
37
|
+
"[PayPal] PAYPAL_SELLER_NONCE is not set — generating a random seller nonce. " +
|
|
38
|
+
"For multi-instance deployments, set PAYPAL_SELLER_NONCE to a fixed random string " +
|
|
39
|
+
"so all instances share the same onboarding code_verifier."
|
|
40
|
+
)
|
|
41
|
+
}
|
|
26
42
|
return randomBytes(32).toString("hex")
|
|
27
43
|
}
|
|
28
44
|
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
+
import { recordMetricAtomic } from "./metrics"
|
|
2
|
+
import { PAYPAL_PARTNER_ATTRIBUTION_ID as BN_CODE } from "./partner"
|
|
1
3
|
import { paypalFetch } from "./paypal-fetch"
|
|
2
4
|
import { decryptSecret, encryptSecret } from "./secret-crypto"
|
|
3
5
|
|
|
4
|
-
const BN_CODE = "MBJTechnolabs_SI_SPB"
|
|
5
6
|
const TOKEN_MARGIN_MS = 2 * 60 * 1000
|
|
6
7
|
|
|
7
8
|
type Environment = "sandbox" | "live"
|
|
@@ -44,14 +45,49 @@ export class PayPalCredentialResolver {
|
|
|
44
45
|
}
|
|
45
46
|
|
|
46
47
|
private async getConnectionRow(): Promise<any | null> {
|
|
48
|
+
// Match the module service's soft-delete semantics: this raw knex read
|
|
49
|
+
// bypasses MikroORM's automatic deleted_at filter, so apply it explicitly
|
|
50
|
+
// or a soft-deleted connection's credentials would keep being used.
|
|
47
51
|
const rows = await this.db("paypal_connection")
|
|
48
52
|
.select("*")
|
|
53
|
+
.whereNull("deleted_at")
|
|
49
54
|
.orderBy("created_at", "desc")
|
|
50
55
|
.limit(1)
|
|
51
56
|
|
|
52
57
|
return rows?.[0] ?? null
|
|
53
58
|
}
|
|
54
59
|
|
|
60
|
+
/**
|
|
61
|
+
* Resolve the amount an admin actually requested for a capture.
|
|
62
|
+
*
|
|
63
|
+
* Medusa does NOT pass the requested capture amount to the provider — only
|
|
64
|
+
* `context.idempotency_key`, which is the Medusa `capture` row id. Without
|
|
65
|
+
* this lookup the provider can only capture the full session amount, which
|
|
66
|
+
* over-charges the buyer on partial captures. Returns null when the id
|
|
67
|
+
* doesn't resolve (caller falls back to the session amount).
|
|
68
|
+
*/
|
|
69
|
+
async getRequestedCaptureAmount(captureRowId: string): Promise<number | null> {
|
|
70
|
+
try {
|
|
71
|
+
if (!captureRowId || typeof captureRowId !== "string") return null
|
|
72
|
+
const rows = await this.db("capture")
|
|
73
|
+
.select("amount", "raw_amount")
|
|
74
|
+
.where("id", captureRowId)
|
|
75
|
+
.whereNull("deleted_at")
|
|
76
|
+
.limit(1)
|
|
77
|
+
const row = rows?.[0]
|
|
78
|
+
if (!row) return null
|
|
79
|
+
const raw = row.raw_amount
|
|
80
|
+
if (raw && typeof raw === "object" && raw.value !== undefined) {
|
|
81
|
+
const v = Number(raw.value)
|
|
82
|
+
if (Number.isFinite(v) && v > 0) return v
|
|
83
|
+
}
|
|
84
|
+
const v = Number(row.amount)
|
|
85
|
+
return Number.isFinite(v) && v > 0 ? v : null
|
|
86
|
+
} catch {
|
|
87
|
+
return null
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
55
91
|
private getEnvCreds(
|
|
56
92
|
row: any,
|
|
57
93
|
env: Environment
|
|
@@ -179,8 +215,13 @@ export class PayPalCredentialResolver {
|
|
|
179
215
|
|
|
180
216
|
async getSettings(): Promise<ResolvedSettings> {
|
|
181
217
|
try {
|
|
218
|
+
// Deterministic singleton read (oldest row wins) — must match the module
|
|
219
|
+
// service's getSettings ordering so both containers agree on the same
|
|
220
|
+
// row even if a first-boot race ever created a duplicate.
|
|
182
221
|
const rows = await this.db("paypal_settings")
|
|
183
222
|
.select("data")
|
|
223
|
+
.whereNull("deleted_at")
|
|
224
|
+
.orderBy("created_at", "asc")
|
|
184
225
|
.limit(1)
|
|
185
226
|
|
|
186
227
|
const data = (rows?.[0]?.data || {}) as Record<string, any>
|
|
@@ -223,40 +264,8 @@ export class PayPalCredentialResolver {
|
|
|
223
264
|
}
|
|
224
265
|
|
|
225
266
|
async recordMetric(name: string, metadata?: Record<string, unknown>) {
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
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
|
-
)
|
|
258
|
-
} catch {
|
|
259
|
-
// metrics must never break the payment flow
|
|
260
|
-
}
|
|
267
|
+
// Atomic upsert (single INSERT ... ON CONFLICT statement) so concurrent
|
|
268
|
+
// captures/refunds don't lose metric updates via a read-modify-write race.
|
|
269
|
+
await recordMetricAtomic(this.db, name, metadata)
|
|
261
270
|
}
|
|
262
271
|
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Atomic metric upsert shared by the credential resolver (payment-module
|
|
3
|
+
* container) and the PayPal module service (application container).
|
|
4
|
+
*
|
|
5
|
+
* The `count` increment happens inside a single SQL statement (not read in JS
|
|
6
|
+
* then written back), and the unique constraint on `name` drives the ON
|
|
7
|
+
* CONFLICT — so concurrent captures/refunds/webhooks can never lose metric
|
|
8
|
+
* updates to a read-modify-write race. Any provided metadata is merged first,
|
|
9
|
+
* then `count`/`last_recorded_at` are applied last so metadata can't clobber
|
|
10
|
+
* the running count.
|
|
11
|
+
*
|
|
12
|
+
* Never throws: metrics must not break the payment flow. `db` is a knex
|
|
13
|
+
* connection (Medusa's `__pg_connection__`).
|
|
14
|
+
*/
|
|
15
|
+
export async function recordMetricAtomic(
|
|
16
|
+
db: { raw: (sql: string, bindings: unknown[]) => Promise<unknown> },
|
|
17
|
+
name: string,
|
|
18
|
+
metadata?: Record<string, unknown>
|
|
19
|
+
): Promise<void> {
|
|
20
|
+
try {
|
|
21
|
+
const id = `ppmet_${Date.now().toString(36)}${Math.random()
|
|
22
|
+
.toString(36)
|
|
23
|
+
.slice(2, 8)}`
|
|
24
|
+
const nowIso = new Date().toISOString()
|
|
25
|
+
const metaJson = JSON.stringify(metadata || {})
|
|
26
|
+
|
|
27
|
+
await db.raw(
|
|
28
|
+
`INSERT INTO paypal_metric (id, name, data, created_at, updated_at)
|
|
29
|
+
VALUES (
|
|
30
|
+
?, ?,
|
|
31
|
+
(?::jsonb || jsonb_build_object('count', 1, 'last_recorded_at', ?::text)),
|
|
32
|
+
now(), now()
|
|
33
|
+
)
|
|
34
|
+
ON CONFLICT (name) DO UPDATE SET
|
|
35
|
+
data = paypal_metric.data
|
|
36
|
+
|| ?::jsonb
|
|
37
|
+
|| jsonb_build_object(
|
|
38
|
+
'count', COALESCE((paypal_metric.data->>'count')::bigint, 0) + 1,
|
|
39
|
+
'last_recorded_at', ?::text
|
|
40
|
+
),
|
|
41
|
+
deleted_at = NULL,
|
|
42
|
+
updated_at = now()`,
|
|
43
|
+
[id, name, metaJson, nowIso, metaJson, nowIso]
|
|
44
|
+
)
|
|
45
|
+
} catch {
|
|
46
|
+
// metrics must never break the payment flow
|
|
47
|
+
}
|
|
48
|
+
}
|
|
@@ -18,44 +18,72 @@ const CB_HALF_OPEN_MS = 60_000
|
|
|
18
18
|
|
|
19
19
|
type CBState = "closed" | "open" | "half-open"
|
|
20
20
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
21
|
+
// One breaker per target host: `paypalFetch` is also used for non-PayPal hosts
|
|
22
|
+
// (onboarding service, alert webhooks). A shared breaker would let five
|
|
23
|
+
// failures of a side-channel host block live captures/refunds against a
|
|
24
|
+
// perfectly healthy PayPal API.
|
|
25
|
+
type Breaker = {
|
|
26
|
+
state: CBState
|
|
27
|
+
failures: number[]
|
|
28
|
+
openedAt: number
|
|
29
|
+
halfOpenProbeInFlight: boolean
|
|
30
30
|
}
|
|
31
31
|
|
|
32
|
-
|
|
33
|
-
|
|
32
|
+
const breakers = new Map<string, Breaker>()
|
|
33
|
+
|
|
34
|
+
function cbHostKey(input: string | URL): string {
|
|
35
|
+
try {
|
|
36
|
+
return new URL(String(input)).host || "default"
|
|
37
|
+
} catch {
|
|
38
|
+
return "default"
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function getBreaker(host: string): Breaker {
|
|
43
|
+
let b = breakers.get(host)
|
|
44
|
+
if (!b) {
|
|
45
|
+
b = { state: "closed", failures: [], openedAt: 0, halfOpenProbeInFlight: false }
|
|
46
|
+
breakers.set(host, b)
|
|
47
|
+
}
|
|
48
|
+
return b
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function cbRecordSuccess(host: string) {
|
|
52
|
+
const b = getBreaker(host)
|
|
53
|
+
b.state = "closed"
|
|
54
|
+
b.failures = []
|
|
55
|
+
b.halfOpenProbeInFlight = false
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function cbRecordFailure(host: string) {
|
|
59
|
+
const b = getBreaker(host)
|
|
60
|
+
b.halfOpenProbeInFlight = false
|
|
34
61
|
const now = Date.now()
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
if (
|
|
38
|
-
|
|
39
|
-
|
|
62
|
+
b.failures = b.failures.filter((t) => now - t < CB_WINDOW_MS)
|
|
63
|
+
b.failures.push(now)
|
|
64
|
+
if (b.failures.length >= CB_FAILURE_THRESHOLD) {
|
|
65
|
+
b.state = "open"
|
|
66
|
+
b.openedAt = now
|
|
40
67
|
console.warn(
|
|
41
|
-
`[PayPal] circuit breaker OPEN after ${CB_FAILURE_THRESHOLD} failures in ${CB_WINDOW_MS / 1000}s`
|
|
68
|
+
`[PayPal] circuit breaker OPEN for ${host} after ${CB_FAILURE_THRESHOLD} failures in ${CB_WINDOW_MS / 1000}s`
|
|
42
69
|
)
|
|
43
70
|
}
|
|
44
71
|
}
|
|
45
72
|
|
|
46
|
-
function cbAllowRequest(): boolean {
|
|
47
|
-
|
|
48
|
-
if (
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
73
|
+
function cbAllowRequest(host: string): boolean {
|
|
74
|
+
const b = getBreaker(host)
|
|
75
|
+
if (b.state === "closed") return true
|
|
76
|
+
if (b.state === "open") {
|
|
77
|
+
if (Date.now() - b.openedAt >= CB_HALF_OPEN_MS) {
|
|
78
|
+
b.state = "half-open"
|
|
79
|
+
b.halfOpenProbeInFlight = true
|
|
52
80
|
return true
|
|
53
81
|
}
|
|
54
82
|
return false
|
|
55
83
|
}
|
|
56
84
|
// half-open: allow only one probe at a time
|
|
57
|
-
if (
|
|
58
|
-
|
|
85
|
+
if (b.halfOpenProbeInFlight) return false
|
|
86
|
+
b.halfOpenProbeInFlight = true
|
|
59
87
|
return true
|
|
60
88
|
}
|
|
61
89
|
|
|
@@ -76,7 +104,8 @@ export function paypalFetch(
|
|
|
76
104
|
input: string | URL,
|
|
77
105
|
init: RequestInit = {}
|
|
78
106
|
): Promise<Response> {
|
|
79
|
-
|
|
107
|
+
const host = cbHostKey(input)
|
|
108
|
+
if (!cbAllowRequest(host)) {
|
|
80
109
|
return Promise.reject(new CircuitOpenError())
|
|
81
110
|
}
|
|
82
111
|
|
|
@@ -90,14 +119,14 @@ export function paypalFetch(
|
|
|
90
119
|
return fetchPromise.then(
|
|
91
120
|
(res) => {
|
|
92
121
|
if (res.status >= 500) {
|
|
93
|
-
cbRecordFailure()
|
|
122
|
+
cbRecordFailure(host)
|
|
94
123
|
} else {
|
|
95
|
-
cbRecordSuccess()
|
|
124
|
+
cbRecordSuccess(host)
|
|
96
125
|
}
|
|
97
126
|
return res
|
|
98
127
|
},
|
|
99
128
|
(err) => {
|
|
100
|
-
cbRecordFailure()
|
|
129
|
+
cbRecordFailure(host)
|
|
101
130
|
throw err
|
|
102
131
|
}
|
|
103
132
|
)
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { MedusaContainer } from "@medusajs/framework/types"
|
|
2
2
|
import { Modules } from "@medusajs/framework/utils"
|
|
3
|
+
import { runCoreWorkflow } from "./utils/core-workflow"
|
|
3
4
|
import { isPayPalProviderId, PAYPAL_PROVIDER_IDS } from "./utils/provider-ids"
|
|
4
5
|
|
|
5
6
|
|
|
@@ -100,6 +101,19 @@ export function normalizeEventVersion(payload: Record<string, any>): string | nu
|
|
|
100
101
|
}
|
|
101
102
|
|
|
102
103
|
|
|
104
|
+
/** Pull the capture id out of a refund resource's "up" HATEOAS link. */
|
|
105
|
+
export function extractCaptureIdFromLinks(
|
|
106
|
+
resource: Record<string, any>
|
|
107
|
+
): string | null {
|
|
108
|
+
const links = Array.isArray(resource?.links) ? resource.links : []
|
|
109
|
+
for (const link of links) {
|
|
110
|
+
const href = String(link?.href || "")
|
|
111
|
+
const match = href.match(/\/captures\/([A-Za-z0-9-]+)/)
|
|
112
|
+
if (match) return match[1]
|
|
113
|
+
}
|
|
114
|
+
return null
|
|
115
|
+
}
|
|
116
|
+
|
|
103
117
|
export interface ExtractedIdentifiers {
|
|
104
118
|
orderId: string | null
|
|
105
119
|
captureId: string | null
|
|
@@ -133,7 +147,21 @@ export function extractIdentifiers(
|
|
|
133
147
|
resource?.purchase_units?.[0]?.payments?.captures?.[0]?.id || ""
|
|
134
148
|
).trim() || null
|
|
135
149
|
} else if (isCapture) {
|
|
136
|
-
|
|
150
|
+
// PAYMENT.CAPTURE.REFUNDED / REVERSED carry a *refund* resource (its `id`
|
|
151
|
+
// is the refund id, with an "up" link to the capture) — treating that id
|
|
152
|
+
// as the capture id would corrupt the session's stored capture_id.
|
|
153
|
+
const isRefundShaped =
|
|
154
|
+
eventType === "PAYMENT.CAPTURE.REFUNDED" ||
|
|
155
|
+
eventType === "PAYMENT.CAPTURE.REVERSED"
|
|
156
|
+
if (isRefundShaped) {
|
|
157
|
+
refundId = String(resource?.id || "").trim() || null
|
|
158
|
+
captureId =
|
|
159
|
+
String(related?.capture_id || "").trim() ||
|
|
160
|
+
extractCaptureIdFromLinks(resource) ||
|
|
161
|
+
null
|
|
162
|
+
} else {
|
|
163
|
+
captureId = String(resource?.id || "").trim() || null
|
|
164
|
+
}
|
|
137
165
|
orderId = String(related?.order_id || "").trim() || null
|
|
138
166
|
cartId = String(resource?.custom_id || "").trim() || null
|
|
139
167
|
} else if (isAuthorization) {
|
|
@@ -223,12 +251,14 @@ function mergeRefunds(existing: any[], incoming: any[]): any[] {
|
|
|
223
251
|
async function applyStatusToSession(
|
|
224
252
|
container: MedusaContainer,
|
|
225
253
|
resolved: ResolvedSession,
|
|
226
|
-
status: string,
|
|
254
|
+
status: string | null,
|
|
227
255
|
patch: Record<string, unknown>
|
|
228
256
|
): Promise<void> {
|
|
229
257
|
const paymentModule = container.resolve(Modules.PAYMENT) as any
|
|
230
258
|
|
|
231
|
-
|
|
259
|
+
// A null status means "record the data but keep the current session status"
|
|
260
|
+
// (e.g. a partial refund must not cancel a captured session).
|
|
261
|
+
if (status !== null && !isTransitionAllowed(resolved.sessionStatus, status)) {
|
|
232
262
|
console.info(
|
|
233
263
|
`[PayPal] webhook: skipping disallowed transition ${resolved.sessionStatus} → ${status} for session ${resolved.sessionId}`
|
|
234
264
|
)
|
|
@@ -246,14 +276,22 @@ async function applyStatusToSession(
|
|
|
246
276
|
? mergeRefunds(existingRefunds, incomingRefunds)
|
|
247
277
|
: existingRefunds
|
|
248
278
|
|
|
279
|
+
// Drop undefined/null values from the patch so a webhook that lacks an
|
|
280
|
+
// identifier (e.g. a capture event with no related_ids) can never clobber
|
|
281
|
+
// stored fields like `order_id` with null.
|
|
282
|
+
const cleanPatch: Record<string, unknown> = {}
|
|
283
|
+
for (const [k, v] of Object.entries(patch)) {
|
|
284
|
+
if (v !== undefined && v !== null) cleanPatch[k] = v
|
|
285
|
+
}
|
|
286
|
+
|
|
249
287
|
await paymentModule.updatePaymentSession({
|
|
250
288
|
id: resolved.sessionId,
|
|
251
|
-
status,
|
|
289
|
+
status: status === null ? resolved.sessionStatus : status,
|
|
252
290
|
data: {
|
|
253
291
|
...resolved.sessionData,
|
|
254
292
|
paypal: {
|
|
255
293
|
...existingPaypal,
|
|
256
|
-
...
|
|
294
|
+
...cleanPatch,
|
|
257
295
|
refunds: nextRefunds,
|
|
258
296
|
},
|
|
259
297
|
},
|
|
@@ -261,12 +299,113 @@ async function applyStatusToSession(
|
|
|
261
299
|
}
|
|
262
300
|
|
|
263
301
|
|
|
302
|
+
/**
|
|
303
|
+
* True when a refund resource demonstrably covers less than the captured
|
|
304
|
+
* amount. Uses the refund's cumulative `total_refunded_amount` (falling back
|
|
305
|
+
* to the single refund amount) against the capture amount stored on the
|
|
306
|
+
* session (falling back to the session total). Returns false — i.e. treat as
|
|
307
|
+
* a full refund, matching the previous behavior — whenever the amounts can't
|
|
308
|
+
* be determined.
|
|
309
|
+
*/
|
|
310
|
+
export function isPartialRefund(
|
|
311
|
+
resource: Record<string, any>,
|
|
312
|
+
sessionData: Record<string, any>
|
|
313
|
+
): boolean {
|
|
314
|
+
const refundedRaw =
|
|
315
|
+
resource?.seller_payable_breakdown?.total_refunded_amount?.value ??
|
|
316
|
+
resource?.amount?.value
|
|
317
|
+
const refunded = Number(refundedRaw)
|
|
318
|
+
if (!Number.isFinite(refunded) || refunded <= 0) return false
|
|
319
|
+
|
|
320
|
+
const paypal = (sessionData?.paypal || {}) as Record<string, any>
|
|
321
|
+
const capturedRaw =
|
|
322
|
+
paypal?.capture?.amount?.value ??
|
|
323
|
+
paypal?.capture?.seller_receivable_breakdown?.gross_amount?.value ??
|
|
324
|
+
sessionData?.amount
|
|
325
|
+
const captured = Number(capturedRaw)
|
|
326
|
+
if (!Number.isFinite(captured) || captured <= 0) return false
|
|
327
|
+
|
|
328
|
+
// Tolerance for floating-point noise; amounts are decimal strings from
|
|
329
|
+
// PayPal or the session's stored major-unit amount.
|
|
330
|
+
return refunded + 0.005 < captured
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/**
|
|
334
|
+
* Whether the webhook processor may complete a paid-but-unfinalized cart.
|
|
335
|
+
*
|
|
336
|
+
* The storefront's `/store/paypal-complete` call is the primary completion
|
|
337
|
+
* path, but it only runs in the buyer's browser. If the tab closes, crashes,
|
|
338
|
+
* or reloads between the capture and that call, the money is captured and no
|
|
339
|
+
* Medusa order is ever created. The PAYMENT.CAPTURE.COMPLETED webhook is the
|
|
340
|
+
* server-side safety net for exactly that gap.
|
|
341
|
+
*
|
|
342
|
+
* Enabled by default (completing a cart whose payment settled is the correct
|
|
343
|
+
* outcome); set PAYPAL_WEBHOOK_COMPLETE_CART=false to disable.
|
|
344
|
+
*/
|
|
345
|
+
export function isWebhookCartCompletionEnabled(
|
|
346
|
+
envValue: string | undefined = process.env.PAYPAL_WEBHOOK_COMPLETE_CART
|
|
347
|
+
): boolean {
|
|
348
|
+
const v = String(envValue ?? "").trim().toLowerCase()
|
|
349
|
+
return !(v === "false" || v === "0" || v === "off" || v === "no")
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/** Events that prove settled funds and may therefore complete the cart. */
|
|
353
|
+
export function isCartCompletingEventType(eventType: string): boolean {
|
|
354
|
+
return eventType === "PAYMENT.CAPTURE.COMPLETED"
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/**
|
|
358
|
+
* Complete the cart if (and only if) it is still incomplete. Returns true when
|
|
359
|
+
* this call completed it. Racing the storefront's own completion is expected
|
|
360
|
+
* and safe: on a workflow error the cart is re-checked, and "someone else
|
|
361
|
+
* completed it first" counts as success. A genuine failure is re-thrown so the
|
|
362
|
+
* webhook retry schedule (and ultimately the dead-letter queue) keeps the
|
|
363
|
+
* paid-but-unfinalized cart visible instead of silently dropping it.
|
|
364
|
+
*/
|
|
365
|
+
async function completeCartIfPending(
|
|
366
|
+
container: MedusaContainer,
|
|
367
|
+
cartId: string,
|
|
368
|
+
eventType: string
|
|
369
|
+
): Promise<boolean> {
|
|
370
|
+
const query = container.resolve("query") as any
|
|
371
|
+
const { data } = await query.graph({
|
|
372
|
+
entity: "cart",
|
|
373
|
+
fields: ["id", "completed_at"],
|
|
374
|
+
filters: { id: cartId },
|
|
375
|
+
})
|
|
376
|
+
const cart = data?.[0]
|
|
377
|
+
if (!cart || cart.completed_at) return false
|
|
378
|
+
|
|
379
|
+
try {
|
|
380
|
+
const { result } = await runCoreWorkflow<{ id: string }, { id?: string }>(
|
|
381
|
+
container,
|
|
382
|
+
"complete-cart",
|
|
383
|
+
{ id: cartId }
|
|
384
|
+
)
|
|
385
|
+
console.info(
|
|
386
|
+
`[PayPal] webhook: completed cart ${cartId} from ${eventType} (order_id=${result?.id ?? "n/a"})`
|
|
387
|
+
)
|
|
388
|
+
return true
|
|
389
|
+
} catch (e: unknown) {
|
|
390
|
+
const recheck = await query
|
|
391
|
+
.graph({ entity: "cart", fields: ["id", "completed_at"], filters: { id: cartId } })
|
|
392
|
+
.catch(() => ({ data: [] as any[] }))
|
|
393
|
+
if (recheck?.data?.[0]?.completed_at) {
|
|
394
|
+
// The storefront (or a concurrent webhook) won the race — that's success.
|
|
395
|
+
return false
|
|
396
|
+
}
|
|
397
|
+
const msg = e instanceof Error ? e.message : String(e)
|
|
398
|
+
throw new Error(`webhook cart completion failed for ${cartId}: ${msg}`)
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
|
|
264
402
|
export interface ProcessResult {
|
|
265
403
|
orderId: string | null
|
|
266
404
|
captureId: string | null
|
|
267
405
|
refundId: string | null
|
|
268
406
|
cartId: string | null
|
|
269
407
|
sessionUpdated: boolean
|
|
408
|
+
cartCompleted: boolean
|
|
270
409
|
}
|
|
271
410
|
|
|
272
411
|
export async function processPayPalWebhookEvent(
|
|
@@ -292,7 +431,14 @@ export async function processPayPalWebhookEvent(
|
|
|
292
431
|
|
|
293
432
|
const targetStatus = EVENT_STATUS_MAP[input.eventType]
|
|
294
433
|
if (!targetStatus) {
|
|
295
|
-
return {
|
|
434
|
+
return {
|
|
435
|
+
orderId,
|
|
436
|
+
captureId,
|
|
437
|
+
refundId,
|
|
438
|
+
cartId: rawCartId,
|
|
439
|
+
sessionUpdated: false,
|
|
440
|
+
cartCompleted: false,
|
|
441
|
+
}
|
|
296
442
|
}
|
|
297
443
|
|
|
298
444
|
let cartId = rawCartId
|
|
@@ -347,10 +493,17 @@ export async function processPayPalWebhookEvent(
|
|
|
347
493
|
}
|
|
348
494
|
|
|
349
495
|
let sessionUpdated = false
|
|
496
|
+
let cartCompleted = false
|
|
497
|
+
let sessionEligibleForCompletion = false
|
|
350
498
|
|
|
351
499
|
if (cartId) {
|
|
352
500
|
const resolved = await findPayPalSession(container, cartId)
|
|
353
501
|
if (resolved) {
|
|
502
|
+
// A canceled session must never complete a cart; anything that is (or
|
|
503
|
+
// may legally become) captured can.
|
|
504
|
+
sessionEligibleForCompletion =
|
|
505
|
+
resolved.sessionStatus === "captured" ||
|
|
506
|
+
isTransitionAllowed(resolved.sessionStatus, "captured")
|
|
354
507
|
const refundEntry = refundId
|
|
355
508
|
? [
|
|
356
509
|
{
|
|
@@ -364,10 +517,28 @@ export async function processPayPalWebhookEvent(
|
|
|
364
517
|
]
|
|
365
518
|
: null
|
|
366
519
|
|
|
367
|
-
|
|
368
|
-
|
|
520
|
+
// A PARTIAL refund must not cancel the session: PayPal fires
|
|
521
|
+
// PAYMENT.CAPTURE.REFUNDED / PAYMENT.REFUND.COMPLETED for partial
|
|
522
|
+
// refunds too, and flipping a substantially-paid session to "canceled"
|
|
523
|
+
// misrepresents the payment. Record the refund but keep the status
|
|
524
|
+
// unless the cumulative refunded total covers the captured amount (or
|
|
525
|
+
// the amounts can't be determined, preserving the old full-refund
|
|
526
|
+
// behavior).
|
|
527
|
+
let effectiveStatus: string | null = targetStatus
|
|
528
|
+
const isRefundEvent =
|
|
529
|
+
input.eventType === "PAYMENT.CAPTURE.REFUNDED" ||
|
|
530
|
+
input.eventType === "PAYMENT.CAPTURE.REVERSED" ||
|
|
531
|
+
input.eventType === "PAYMENT.REFUND.COMPLETED"
|
|
532
|
+
if (isRefundEvent && targetStatus === "canceled") {
|
|
533
|
+
if (isPartialRefund(resource, resolved.sessionData)) {
|
|
534
|
+
effectiveStatus = null
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
await applyStatusToSession(container, resolved, effectiveStatus, {
|
|
539
|
+
order_id: orderId ?? undefined,
|
|
369
540
|
capture_id: captureId ?? resolved.sessionData.paypal?.capture_id ?? undefined,
|
|
370
|
-
refund_id: refundId,
|
|
541
|
+
refund_id: refundId ?? undefined,
|
|
371
542
|
refund_status: refundId ? resource?.status : undefined,
|
|
372
543
|
refund_reason: refundReason,
|
|
373
544
|
refund_reason_code: refundReasonCode,
|
|
@@ -384,5 +555,19 @@ export async function processPayPalWebhookEvent(
|
|
|
384
555
|
)
|
|
385
556
|
}
|
|
386
557
|
|
|
387
|
-
|
|
558
|
+
// Server-side safety net: the funds settled but the buyer's browser may
|
|
559
|
+
// never call /store/paypal-complete (closed tab, crash, mobile redirect
|
|
560
|
+
// loss). Complete the cart here so a captured payment always produces an
|
|
561
|
+
// order. Runs after the session update so authorizePayment sees the capture.
|
|
562
|
+
if (
|
|
563
|
+
cartId &&
|
|
564
|
+
sessionUpdated &&
|
|
565
|
+
sessionEligibleForCompletion &&
|
|
566
|
+
isCartCompletingEventType(input.eventType) &&
|
|
567
|
+
isWebhookCartCompletionEnabled()
|
|
568
|
+
) {
|
|
569
|
+
cartCompleted = await completeCartIfPending(container, cartId, input.eventType)
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
return { orderId, captureId, refundId, cartId, sessionUpdated, cartCompleted }
|
|
388
573
|
}
|
|
@@ -85,8 +85,12 @@ export default async function paypalWebhookProcessHandler({
|
|
|
85
85
|
refund_id: processed.refundId,
|
|
86
86
|
cart_id: processed.cartId,
|
|
87
87
|
session_updated: processed.sessionUpdated,
|
|
88
|
+
cart_completed: processed.cartCompleted,
|
|
88
89
|
})
|
|
89
90
|
|
|
91
|
+
if (processed.cartCompleted) {
|
|
92
|
+
await paypal.recordMetric("webhook_cart_completed").catch(() => {})
|
|
93
|
+
}
|
|
90
94
|
await paypal.recordMetric("webhook_success").catch(() => {})
|
|
91
95
|
} catch (e: any) {
|
|
92
96
|
const retryable = isRetryableError(e)
|