@easypayment/medusa-payment-paypal 1.1.2 → 1.2.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 +73 -73
- package/.medusa/server/src/admin/index.mjs +73 -73
- package/.medusa/server/src/api/middlewares.d.ts.map +1 -1
- package/.medusa/server/src/api/middlewares.js +16 -2
- 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/create-order/route.d.ts.map +1 -1
- package/.medusa/server/src/api/store/paypal/create-order/route.js +11 -6
- package/.medusa/server/src/api/store/paypal/create-order/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 +7 -5
- 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 +15 -0
- 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 +26 -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 +244 -169
- 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 +8 -25
- package/.medusa/server/src/modules/paypal/payment-provider/service.js.map +1 -1
- package/.medusa/server/src/modules/paypal/service.d.ts +2 -0
- package/.medusa/server/src/modules/paypal/service.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/service.js +54 -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.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/credential-resolver.js +10 -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/webhook-processor.d.ts +16 -0
- package/.medusa/server/src/modules/paypal/webhook-processor.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/webhook-processor.js +85 -2
- 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 -146
- package/README.md +175 -184
- package/package.json +91 -88
- package/src/api/middlewares.ts +16 -2
- package/src/api/store/paypal/capture-order/route.ts +83 -12
- package/src/api/store/paypal/create-order/route.ts +11 -7
- package/src/api/utils/rate-limit.ts +20 -5
- package/src/jobs/paypal-webhook-retry.ts +4 -0
- package/src/modules/paypal/payment-provider/base-provider.ts +31 -0
- package/src/modules/paypal/payment-provider/card-service.ts +84 -0
- package/src/modules/paypal/payment-provider/service.ts +12 -30
- package/src/modules/paypal/service.ts +1703 -1651
- package/src/modules/paypal/types/config.ts +16 -0
- package/src/modules/paypal/utils/credential-resolver.ts +9 -36
- package/src/modules/paypal/utils/metrics.ts +48 -0
- package/src/modules/paypal/webhook-processor.ts +101 -2
- 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"
|
|
@@ -214,9 +215,13 @@ export class PayPalCredentialResolver {
|
|
|
214
215
|
|
|
215
216
|
async getSettings(): Promise<ResolvedSettings> {
|
|
216
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.
|
|
217
221
|
const rows = await this.db("paypal_settings")
|
|
218
222
|
.select("data")
|
|
219
223
|
.whereNull("deleted_at")
|
|
224
|
+
.orderBy("created_at", "asc")
|
|
220
225
|
.limit(1)
|
|
221
226
|
|
|
222
227
|
const data = (rows?.[0]?.data || {}) as Record<string, any>
|
|
@@ -259,40 +264,8 @@ export class PayPalCredentialResolver {
|
|
|
259
264
|
}
|
|
260
265
|
|
|
261
266
|
async recordMetric(name: string, metadata?: Record<string, unknown>) {
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
.slice(2, 8)}`
|
|
266
|
-
const nowIso = new Date().toISOString()
|
|
267
|
-
const metaJson = JSON.stringify(metadata || {})
|
|
268
|
-
|
|
269
|
-
// Atomic upsert so concurrent captures/refunds don't lose metric updates
|
|
270
|
-
// via a read-modify-write race. The `count` increment happens inside a
|
|
271
|
-
// single statement (not read in JS then written back), and the unique
|
|
272
|
-
// constraint on `name` drives the ON CONFLICT so there is no insert/update
|
|
273
|
-
// decision to race on either. Any provided metadata is merged first, then
|
|
274
|
-
// `count`/`last_recorded_at` are applied last so metadata can't clobber
|
|
275
|
-
// the running count.
|
|
276
|
-
await this.db.raw(
|
|
277
|
-
`INSERT INTO paypal_metric (id, name, data, created_at, updated_at)
|
|
278
|
-
VALUES (
|
|
279
|
-
?, ?,
|
|
280
|
-
(?::jsonb || jsonb_build_object('count', 1, 'last_recorded_at', ?::text)),
|
|
281
|
-
now(), now()
|
|
282
|
-
)
|
|
283
|
-
ON CONFLICT (name) DO UPDATE SET
|
|
284
|
-
data = paypal_metric.data
|
|
285
|
-
|| ?::jsonb
|
|
286
|
-
|| jsonb_build_object(
|
|
287
|
-
'count', COALESCE((paypal_metric.data->>'count')::bigint, 0) + 1,
|
|
288
|
-
'last_recorded_at', ?::text
|
|
289
|
-
),
|
|
290
|
-
deleted_at = NULL,
|
|
291
|
-
updated_at = now()`,
|
|
292
|
-
[id, name, metaJson, nowIso, metaJson, nowIso]
|
|
293
|
-
)
|
|
294
|
-
} catch {
|
|
295
|
-
// metrics must never break the payment flow
|
|
296
|
-
}
|
|
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)
|
|
297
270
|
}
|
|
298
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
|
+
}
|
|
@@ -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
|
|
|
@@ -329,12 +330,82 @@ export function isPartialRefund(
|
|
|
329
330
|
return refunded + 0.005 < captured
|
|
330
331
|
}
|
|
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
|
+
|
|
332
402
|
export interface ProcessResult {
|
|
333
403
|
orderId: string | null
|
|
334
404
|
captureId: string | null
|
|
335
405
|
refundId: string | null
|
|
336
406
|
cartId: string | null
|
|
337
407
|
sessionUpdated: boolean
|
|
408
|
+
cartCompleted: boolean
|
|
338
409
|
}
|
|
339
410
|
|
|
340
411
|
export async function processPayPalWebhookEvent(
|
|
@@ -360,7 +431,14 @@ export async function processPayPalWebhookEvent(
|
|
|
360
431
|
|
|
361
432
|
const targetStatus = EVENT_STATUS_MAP[input.eventType]
|
|
362
433
|
if (!targetStatus) {
|
|
363
|
-
return {
|
|
434
|
+
return {
|
|
435
|
+
orderId,
|
|
436
|
+
captureId,
|
|
437
|
+
refundId,
|
|
438
|
+
cartId: rawCartId,
|
|
439
|
+
sessionUpdated: false,
|
|
440
|
+
cartCompleted: false,
|
|
441
|
+
}
|
|
364
442
|
}
|
|
365
443
|
|
|
366
444
|
let cartId = rawCartId
|
|
@@ -415,10 +493,17 @@ export async function processPayPalWebhookEvent(
|
|
|
415
493
|
}
|
|
416
494
|
|
|
417
495
|
let sessionUpdated = false
|
|
496
|
+
let cartCompleted = false
|
|
497
|
+
let sessionEligibleForCompletion = false
|
|
418
498
|
|
|
419
499
|
if (cartId) {
|
|
420
500
|
const resolved = await findPayPalSession(container, cartId)
|
|
421
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")
|
|
422
507
|
const refundEntry = refundId
|
|
423
508
|
? [
|
|
424
509
|
{
|
|
@@ -470,5 +555,19 @@ export async function processPayPalWebhookEvent(
|
|
|
470
555
|
)
|
|
471
556
|
}
|
|
472
557
|
|
|
473
|
-
|
|
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 }
|
|
474
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)
|