@mixrpay/merchant-sdk 0.1.1 → 0.3.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/dist/index.mjs CHANGED
@@ -1,217 +1,3 @@
1
- // src/verify.ts
2
- import { recoverTypedDataAddress } from "viem";
3
-
4
- // src/utils.ts
5
- var USDC_CONTRACTS = {
6
- 8453: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
7
- // Base Mainnet
8
- 84532: "0x036CbD53842c5426634e7929541eC2318f3dCF7e"
9
- // Base Sepolia
10
- };
11
- var DEFAULT_FACILITATOR = "https://x402.org/facilitator";
12
- function getUSDCDomain(chainId) {
13
- const verifyingContract = USDC_CONTRACTS[chainId];
14
- if (!verifyingContract) {
15
- throw new Error(`Unsupported chain ID: ${chainId}. Supported: ${Object.keys(USDC_CONTRACTS).join(", ")}`);
16
- }
17
- return {
18
- name: "USD Coin",
19
- version: "2",
20
- chainId,
21
- verifyingContract
22
- };
23
- }
24
- var TRANSFER_WITH_AUTHORIZATION_TYPES = {
25
- TransferWithAuthorization: [
26
- { name: "from", type: "address" },
27
- { name: "to", type: "address" },
28
- { name: "value", type: "uint256" },
29
- { name: "validAfter", type: "uint256" },
30
- { name: "validBefore", type: "uint256" },
31
- { name: "nonce", type: "bytes32" }
32
- ]
33
- };
34
- function usdToMinor(usd) {
35
- return BigInt(Math.round(usd * 1e6));
36
- }
37
- function minorToUsd(minor) {
38
- return Number(minor) / 1e6;
39
- }
40
- function generateNonce() {
41
- const bytes = new Uint8Array(32);
42
- crypto.getRandomValues(bytes);
43
- return `0x${Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("")}`;
44
- }
45
- function isValidAddress(address) {
46
- return /^0x[a-fA-F0-9]{40}$/.test(address);
47
- }
48
- function normalizeAddress(address) {
49
- if (!isValidAddress(address)) {
50
- throw new Error(`Invalid address: ${address}`);
51
- }
52
- return address.toLowerCase();
53
- }
54
- function base64Decode(str) {
55
- if (typeof Buffer !== "undefined") {
56
- return Buffer.from(str, "base64").toString("utf-8");
57
- }
58
- return atob(str);
59
- }
60
-
61
- // src/verify.ts
62
- async function verifyX402Payment(paymentHeader, options) {
63
- try {
64
- let decoded;
65
- try {
66
- const jsonStr = base64Decode(paymentHeader);
67
- decoded = JSON.parse(jsonStr);
68
- } catch (e) {
69
- return { valid: false, error: "Invalid payment header encoding" };
70
- }
71
- if (!decoded.payload?.authorization || !decoded.payload?.signature) {
72
- return { valid: false, error: "Missing authorization or signature in payment" };
73
- }
74
- const { authorization, signature } = decoded.payload;
75
- const chainId = options.chainId || 8453;
76
- const message = {
77
- from: authorization.from,
78
- to: authorization.to,
79
- value: BigInt(authorization.value),
80
- validAfter: BigInt(authorization.validAfter),
81
- validBefore: BigInt(authorization.validBefore),
82
- nonce: authorization.nonce
83
- };
84
- const domain = getUSDCDomain(chainId);
85
- let signerAddress;
86
- try {
87
- signerAddress = await recoverTypedDataAddress({
88
- domain,
89
- types: TRANSFER_WITH_AUTHORIZATION_TYPES,
90
- primaryType: "TransferWithAuthorization",
91
- message,
92
- signature
93
- });
94
- } catch (e) {
95
- return { valid: false, error: "Failed to recover signer from signature" };
96
- }
97
- if (signerAddress.toLowerCase() !== authorization.from.toLowerCase()) {
98
- return {
99
- valid: false,
100
- error: `Signature mismatch: expected ${authorization.from}, got ${signerAddress}`
101
- };
102
- }
103
- const paymentAmount = BigInt(authorization.value);
104
- if (paymentAmount < options.expectedAmount) {
105
- return {
106
- valid: false,
107
- error: `Insufficient payment: expected ${options.expectedAmount}, got ${paymentAmount}`
108
- };
109
- }
110
- if (authorization.to.toLowerCase() !== options.expectedRecipient.toLowerCase()) {
111
- return {
112
- valid: false,
113
- error: `Wrong recipient: expected ${options.expectedRecipient}, got ${authorization.to}`
114
- };
115
- }
116
- const now = Math.floor(Date.now() / 1e3);
117
- if (Number(authorization.validBefore) < now) {
118
- return { valid: false, error: "Payment authorization has expired" };
119
- }
120
- if (Number(authorization.validAfter) > now) {
121
- return { valid: false, error: "Payment authorization is not yet valid" };
122
- }
123
- let txHash;
124
- let settledAt;
125
- if (!options.skipSettlement) {
126
- const facilitatorUrl = options.facilitator || DEFAULT_FACILITATOR;
127
- try {
128
- const settlementResponse = await fetch(`${facilitatorUrl}/settle`, {
129
- method: "POST",
130
- headers: { "Content-Type": "application/json" },
131
- body: JSON.stringify({
132
- authorization,
133
- signature,
134
- chainId
135
- })
136
- });
137
- if (!settlementResponse.ok) {
138
- const errorBody = await settlementResponse.text();
139
- let errorMessage = "Settlement failed";
140
- try {
141
- const errorJson = JSON.parse(errorBody);
142
- errorMessage = errorJson.message || errorJson.error || errorMessage;
143
- } catch {
144
- errorMessage = errorBody || errorMessage;
145
- }
146
- return { valid: false, error: `Settlement failed: ${errorMessage}` };
147
- }
148
- const settlement = await settlementResponse.json();
149
- txHash = settlement.txHash || settlement.tx_hash;
150
- settledAt = /* @__PURE__ */ new Date();
151
- } catch (e) {
152
- return {
153
- valid: false,
154
- error: `Settlement request failed: ${e.message}`
155
- };
156
- }
157
- }
158
- return {
159
- valid: true,
160
- payer: authorization.from,
161
- amount: minorToUsd(paymentAmount),
162
- amountMinor: paymentAmount,
163
- txHash,
164
- settledAt: settledAt || /* @__PURE__ */ new Date(),
165
- nonce: authorization.nonce
166
- };
167
- } catch (error) {
168
- return {
169
- valid: false,
170
- error: `Verification error: ${error.message}`
171
- };
172
- }
173
- }
174
- async function parseX402Payment(paymentHeader, chainId = 8453) {
175
- try {
176
- const jsonStr = base64Decode(paymentHeader);
177
- const decoded = JSON.parse(jsonStr);
178
- if (!decoded.payload?.authorization) {
179
- return { valid: false, error: "Missing authorization in payment" };
180
- }
181
- const { authorization, signature } = decoded.payload;
182
- const domain = getUSDCDomain(chainId);
183
- const message = {
184
- from: authorization.from,
185
- to: authorization.to,
186
- value: BigInt(authorization.value),
187
- validAfter: BigInt(authorization.validAfter),
188
- validBefore: BigInt(authorization.validBefore),
189
- nonce: authorization.nonce
190
- };
191
- const signerAddress = await recoverTypedDataAddress({
192
- domain,
193
- types: TRANSFER_WITH_AUTHORIZATION_TYPES,
194
- primaryType: "TransferWithAuthorization",
195
- message,
196
- signature
197
- });
198
- if (signerAddress.toLowerCase() !== authorization.from.toLowerCase()) {
199
- return { valid: false, error: "Signature mismatch" };
200
- }
201
- const amountMinor = BigInt(authorization.value);
202
- return {
203
- valid: true,
204
- payer: authorization.from,
205
- recipient: authorization.to,
206
- amount: minorToUsd(amountMinor),
207
- amountMinor,
208
- expiresAt: new Date(Number(authorization.validBefore) * 1e3)
209
- };
210
- } catch (error) {
211
- return { valid: false, error: `Parse error: ${error.message}` };
212
- }
213
- }
214
-
215
1
  // src/receipt.ts
216
2
  import * as jose from "jose";
217
3
  var DEFAULT_JWKS_URL = process.env.MIXRPAY_JWKS_URL || "https://mixrpay.com/.well-known/jwks";
@@ -280,564 +66,18 @@ async function verifyPaymentReceipt(receipt, options) {
280
66
  throw error;
281
67
  }
282
68
  }
283
- function parsePaymentReceipt(receipt) {
284
- const decoded = jose.decodeJwt(receipt);
285
- return {
286
- paymentId: decoded.paymentId,
287
- amount: decoded.amount,
288
- amountUsd: decoded.amountUsd,
289
- payer: decoded.payer,
290
- recipient: decoded.recipient,
291
- chainId: decoded.chainId,
292
- txHash: decoded.txHash,
293
- settledAt: decoded.settledAt,
294
- issuedAt: decoded.iat ? new Date(decoded.iat * 1e3) : void 0,
295
- expiresAt: decoded.exp ? new Date(decoded.exp * 1e3) : void 0
296
- };
297
- }
298
- function isReceiptExpired(receipt) {
299
- const parsed = typeof receipt === "string" ? parsePaymentReceipt(receipt) : receipt;
300
- if (!parsed.expiresAt) {
301
- return false;
302
- }
303
- return parsed.expiresAt.getTime() < Date.now();
304
- }
305
- function clearJWKSCache() {
306
- jwksCache.clear();
307
- }
308
- function getDefaultJWKSUrl() {
309
- return DEFAULT_JWKS_URL;
310
- }
311
69
 
312
70
  // src/charges.ts
313
- import crypto2 from "crypto";
314
- var ChargesClient = class {
315
- constructor(options) {
316
- this.apiKey = options.apiKey;
317
- this.baseUrl = options.baseUrl || process.env.MIXRPAY_BASE_URL || "https://mixrpay.com";
318
- }
319
- /**
320
- * Create a new charge.
321
- *
322
- * @example
323
- * ```typescript
324
- * const result = await charges.create({
325
- * sessionId: 'sk_xxx',
326
- * amountUsd: 0.05,
327
- * reference: 'image_gen_123',
328
- * metadata: { feature: 'image_generation' }
329
- * });
330
- *
331
- * if (result.success) {
332
- * console.log(`Charged ${result.charge.amountUsdc}`);
333
- * console.log(`TX: ${result.charge.explorerUrl}`);
334
- * }
335
- * ```
336
- */
337
- async create(params) {
338
- const response = await fetch(`${this.baseUrl}/api/v1/charges`, {
339
- method: "POST",
340
- headers: {
341
- "Content-Type": "application/json",
342
- "Authorization": `Bearer ${this.apiKey}`
343
- },
344
- body: JSON.stringify({
345
- session_id: params.sessionId,
346
- amount_usd: params.amountUsd,
347
- reference: params.reference,
348
- metadata: params.metadata
349
- })
350
- });
351
- const data = await response.json();
352
- if (!response.ok) {
353
- return {
354
- success: false,
355
- error: data.error,
356
- details: data.details
357
- };
358
- }
359
- return {
360
- success: data.success,
361
- charge: data.charge_id ? {
362
- id: data.charge_id,
363
- status: data.status,
364
- amountUsd: data.amount_usd ?? 0,
365
- amountUsdc: data.amount_usdc ?? "0",
366
- txHash: data.tx_hash,
367
- explorerUrl: data.explorer_url,
368
- fromAddress: "",
369
- toAddress: "",
370
- reference: params.reference,
371
- createdAt: (/* @__PURE__ */ new Date()).toISOString()
372
- } : void 0,
373
- idempotentReplay: data.idempotent_replay,
374
- error: data.error
375
- };
376
- }
377
- /**
378
- * Get a charge by ID.
379
- *
380
- * @example
381
- * ```typescript
382
- * const charge = await charges.get('chg_xxx');
383
- * console.log(charge.status); // 'confirmed'
384
- * ```
385
- */
386
- async get(chargeId) {
387
- const response = await fetch(`${this.baseUrl}/api/v1/charges?id=${chargeId}`, {
388
- headers: {
389
- "Authorization": `Bearer ${this.apiKey}`
390
- }
391
- });
392
- if (!response.ok) {
393
- if (response.status === 404) {
394
- return null;
395
- }
396
- throw new Error(`Failed to get charge: ${response.statusText}`);
397
- }
398
- const data = await response.json();
399
- return {
400
- id: data.id,
401
- status: data.status,
402
- amountUsd: data.amount_usd,
403
- amountUsdc: data.amount_usdc,
404
- txHash: data.tx_hash,
405
- explorerUrl: data.explorer_url,
406
- fromAddress: data.from_address,
407
- toAddress: data.to_address,
408
- reference: data.reference,
409
- createdAt: data.created_at,
410
- confirmedAt: data.confirmed_at,
411
- sessionName: data.session_name,
412
- userWallet: data.user_wallet
413
- };
414
- }
415
- /**
416
- * Get a charge by transaction hash.
417
- */
418
- async getByTxHash(txHash) {
419
- const response = await fetch(`${this.baseUrl}/api/v1/charges?tx_hash=${txHash}`, {
420
- headers: {
421
- "Authorization": `Bearer ${this.apiKey}`
422
- }
423
- });
424
- if (!response.ok) {
425
- if (response.status === 404) {
426
- return null;
427
- }
428
- throw new Error(`Failed to get charge: ${response.statusText}`);
429
- }
430
- const data = await response.json();
431
- return {
432
- id: data.id,
433
- status: data.status,
434
- amountUsd: data.amount_usd,
435
- amountUsdc: data.amount_usdc,
436
- txHash: data.tx_hash,
437
- explorerUrl: data.explorer_url,
438
- fromAddress: data.from_address,
439
- toAddress: data.to_address,
440
- reference: data.reference,
441
- createdAt: data.created_at,
442
- confirmedAt: data.confirmed_at,
443
- sessionName: data.session_name,
444
- userWallet: data.user_wallet
445
- };
446
- }
447
- };
71
+ import crypto from "crypto";
448
72
  function verifySessionWebhook(payload, signature, secret) {
449
- const expectedSignature = crypto2.createHmac("sha256", secret).update(payload).digest("hex");
450
- return crypto2.timingSafeEqual(
73
+ const expectedSignature = crypto.createHmac("sha256", secret).update(payload).digest("hex");
74
+ return crypto.timingSafeEqual(
451
75
  Buffer.from(signature),
452
76
  Buffer.from(expectedSignature)
453
77
  );
454
78
  }
455
- function parseSessionGrant(payload) {
456
- if (payload.event !== "session.granted") {
457
- throw new Error(`Unexpected event type: ${payload.event}`);
458
- }
459
- return {
460
- sessionId: payload.session_id,
461
- userWallet: payload.user_wallet,
462
- merchantWallet: payload.merchant_wallet,
463
- limits: {
464
- maxTotalUsd: payload.limits.max_total_usd,
465
- maxPerTxUsd: payload.limits.max_per_tx_usd,
466
- expiresAt: payload.limits.expires_at
467
- },
468
- grantedAt: payload.granted_at
469
- };
470
- }
471
-
472
- // src/receipt-fetcher.ts
473
- var DEFAULT_MIXRPAY_API_URL = process.env.MIXRPAY_BASE_URL || "https://mixrpay.com";
474
- async function fetchPaymentReceipt(params) {
475
- const apiUrl = params.apiUrl || DEFAULT_MIXRPAY_API_URL;
476
- const endpoint = `${apiUrl}/api/v1/receipts`;
477
- try {
478
- const response = await fetch(endpoint, {
479
- method: "POST",
480
- headers: {
481
- "Content-Type": "application/json"
482
- },
483
- body: JSON.stringify({
484
- tx_hash: params.txHash,
485
- payer: params.payer,
486
- recipient: params.recipient,
487
- amount: params.amount.toString(),
488
- chain_id: params.chainId
489
- })
490
- });
491
- if (!response.ok) {
492
- console.warn(`[x402] Receipt fetch failed: ${response.status} ${response.statusText}`);
493
- return null;
494
- }
495
- const data = await response.json();
496
- return data.receipt || null;
497
- } catch (error) {
498
- console.warn("[x402] Receipt fetch error:", error.message);
499
- return null;
500
- }
501
- }
502
-
503
- // src/middleware/express.ts
504
- function x402(options) {
505
- return async (req, res, next) => {
506
- try {
507
- const context = {
508
- path: req.path,
509
- method: req.method,
510
- headers: req.headers,
511
- body: req.body
512
- };
513
- if (options.skip) {
514
- const shouldSkip = await options.skip(context);
515
- if (shouldSkip) {
516
- return next();
517
- }
518
- }
519
- const recipient = options.recipient || process.env.MIXRPAY_MERCHANT_ADDRESS;
520
- if (!recipient) {
521
- console.error("[x402] No recipient address configured. Set MIXRPAY_MERCHANT_ADDRESS env var or pass recipient option.");
522
- return res.status(500).json({
523
- error: "Payment configuration error",
524
- message: "Merchant wallet address not configured"
525
- });
526
- }
527
- const price = options.getPrice ? await options.getPrice(context) : options.price;
528
- const priceMinor = usdToMinor(price);
529
- const chainId = options.chainId || 8453;
530
- const facilitator = options.facilitator || DEFAULT_FACILITATOR;
531
- const paymentHeader = req.headers["x-payment"];
532
- if (!paymentHeader) {
533
- const nonce = generateNonce();
534
- const expiresAt = Math.floor(Date.now() / 1e3) + 300;
535
- const paymentRequired = {
536
- recipient,
537
- amount: priceMinor.toString(),
538
- currency: "USDC",
539
- chainId,
540
- facilitator,
541
- nonce,
542
- expiresAt,
543
- description: options.description
544
- };
545
- res.setHeader("X-Payment-Required", JSON.stringify(paymentRequired));
546
- res.setHeader("WWW-Authenticate", `X-402 ${Buffer.from(JSON.stringify(paymentRequired)).toString("base64")}`);
547
- return res.status(402).json({
548
- error: "Payment required",
549
- payment: paymentRequired
550
- });
551
- }
552
- const result = await verifyX402Payment(paymentHeader, {
553
- expectedAmount: priceMinor,
554
- expectedRecipient: recipient,
555
- chainId,
556
- facilitator,
557
- skipSettlement: options.testMode
558
- });
559
- if (!result.valid) {
560
- return res.status(402).json({
561
- error: "Invalid payment",
562
- reason: result.error
563
- });
564
- }
565
- req.x402Payment = result;
566
- if (result.txHash) {
567
- res.setHeader("X-Payment-TxHash", result.txHash);
568
- }
569
- const receiptMode = options.receiptMode || "webhook";
570
- if ((receiptMode === "jwt" || receiptMode === "both") && result.txHash && result.payer) {
571
- try {
572
- const receipt = await fetchPaymentReceipt({
573
- txHash: result.txHash,
574
- payer: result.payer,
575
- recipient,
576
- amount: priceMinor,
577
- chainId,
578
- apiUrl: options.mixrpayApiUrl
579
- });
580
- if (receipt) {
581
- result.receipt = receipt;
582
- res.setHeader("X-Payment-Receipt", receipt);
583
- }
584
- } catch (receiptError) {
585
- console.warn("[x402] Failed to fetch JWT receipt:", receiptError);
586
- }
587
- }
588
- if (options.onPayment) {
589
- await options.onPayment(result);
590
- }
591
- next();
592
- } catch (error) {
593
- console.error("[x402] Middleware error:", error);
594
- return res.status(500).json({
595
- error: "Payment processing error",
596
- message: error.message
597
- });
598
- }
599
- };
600
- }
601
-
602
- // src/middleware/nextjs.ts
603
- import { NextResponse } from "next/server";
604
- function withX402(config, handler) {
605
- return async (req) => {
606
- try {
607
- const recipient = config.recipient || process.env.MIXRPAY_MERCHANT_ADDRESS;
608
- if (!recipient) {
609
- console.error("[x402] No recipient address configured");
610
- return NextResponse.json(
611
- { error: "Payment configuration error" },
612
- { status: 500 }
613
- );
614
- }
615
- const price = config.getPrice ? await config.getPrice(req) : config.price;
616
- const priceMinor = usdToMinor(price);
617
- const chainId = config.chainId || 8453;
618
- const facilitator = config.facilitator || DEFAULT_FACILITATOR;
619
- const paymentHeader = req.headers.get("x-payment");
620
- if (!paymentHeader) {
621
- const nonce = generateNonce();
622
- const expiresAt = Math.floor(Date.now() / 1e3) + 300;
623
- const paymentRequired = {
624
- recipient,
625
- amount: priceMinor.toString(),
626
- currency: "USDC",
627
- chainId,
628
- facilitator,
629
- nonce,
630
- expiresAt,
631
- description: config.description
632
- };
633
- return NextResponse.json(
634
- { error: "Payment required", payment: paymentRequired },
635
- {
636
- status: 402,
637
- headers: {
638
- "X-Payment-Required": JSON.stringify(paymentRequired),
639
- "WWW-Authenticate": `X-402 ${Buffer.from(JSON.stringify(paymentRequired)).toString("base64")}`
640
- }
641
- }
642
- );
643
- }
644
- const result = await verifyX402Payment(paymentHeader, {
645
- expectedAmount: priceMinor,
646
- expectedRecipient: recipient,
647
- chainId,
648
- facilitator,
649
- skipSettlement: config.testMode
650
- });
651
- if (!result.valid) {
652
- return NextResponse.json(
653
- { error: "Invalid payment", reason: result.error },
654
- { status: 402 }
655
- );
656
- }
657
- const receiptMode = config.receiptMode || "webhook";
658
- if ((receiptMode === "jwt" || receiptMode === "both") && result.txHash && result.payer) {
659
- try {
660
- const receipt = await fetchPaymentReceipt({
661
- txHash: result.txHash,
662
- payer: result.payer,
663
- recipient,
664
- amount: priceMinor,
665
- chainId,
666
- apiUrl: config.mixrpayApiUrl
667
- });
668
- if (receipt) {
669
- result.receipt = receipt;
670
- }
671
- } catch (receiptError) {
672
- console.warn("[x402] Failed to fetch JWT receipt:", receiptError);
673
- }
674
- }
675
- if (config.onPayment) {
676
- await config.onPayment(result, req);
677
- }
678
- const response = await handler(req, result);
679
- if (result.txHash) {
680
- response.headers.set("X-Payment-TxHash", result.txHash);
681
- }
682
- if (result.receipt) {
683
- response.headers.set("X-Payment-Receipt", result.receipt);
684
- }
685
- return response;
686
- } catch (error) {
687
- console.error("[x402] Handler error:", error);
688
- return NextResponse.json(
689
- { error: "Payment processing error" },
690
- { status: 500 }
691
- );
692
- }
693
- };
694
- }
695
- function createPaymentRequired(options) {
696
- const priceMinor = usdToMinor(options.amount);
697
- const nonce = generateNonce();
698
- const expiresAt = Math.floor(Date.now() / 1e3) + 300;
699
- const paymentRequired = {
700
- recipient: options.recipient,
701
- amount: priceMinor.toString(),
702
- currency: "USDC",
703
- chainId: options.chainId || 8453,
704
- facilitator: options.facilitator || DEFAULT_FACILITATOR,
705
- nonce,
706
- expiresAt,
707
- description: options.description
708
- };
709
- return NextResponse.json(
710
- { error: "Payment required", payment: paymentRequired },
711
- {
712
- status: 402,
713
- headers: {
714
- "X-Payment-Required": JSON.stringify(paymentRequired)
715
- }
716
- }
717
- );
718
- }
719
-
720
- // src/middleware/fastify.ts
721
- var x402Plugin = (fastify, options, done) => {
722
- fastify.decorateRequest("x402Payment", null);
723
- fastify.decorate("x402Defaults", {
724
- recipient: options.recipient || process.env.MIXRPAY_MERCHANT_ADDRESS,
725
- chainId: options.chainId || 8453,
726
- facilitator: options.facilitator || DEFAULT_FACILITATOR
727
- });
728
- done();
729
- };
730
- function x4022(options) {
731
- return async (request, reply) => {
732
- const context = {
733
- path: request.url,
734
- method: request.method,
735
- headers: request.headers,
736
- body: request.body
737
- };
738
- if (options.skip) {
739
- const shouldSkip = await options.skip(context);
740
- if (shouldSkip) {
741
- return;
742
- }
743
- }
744
- const defaults = request.server.x402Defaults || {};
745
- const recipient = options.recipient || defaults.recipient || process.env.MIXRPAY_MERCHANT_ADDRESS;
746
- if (!recipient) {
747
- request.log.error("[x402] No recipient address configured");
748
- return reply.status(500).send({
749
- error: "Payment configuration error",
750
- message: "Merchant wallet address not configured"
751
- });
752
- }
753
- const price = options.getPrice ? await options.getPrice(context) : options.price;
754
- const priceMinor = usdToMinor(price);
755
- const chainId = options.chainId || defaults.chainId || 8453;
756
- const facilitator = options.facilitator || defaults.facilitator || DEFAULT_FACILITATOR;
757
- const paymentHeader = request.headers["x-payment"];
758
- if (!paymentHeader) {
759
- const nonce = generateNonce();
760
- const expiresAt = Math.floor(Date.now() / 1e3) + 300;
761
- const paymentRequired = {
762
- recipient,
763
- amount: priceMinor.toString(),
764
- currency: "USDC",
765
- chainId,
766
- facilitator,
767
- nonce,
768
- expiresAt,
769
- description: options.description
770
- };
771
- reply.header("X-Payment-Required", JSON.stringify(paymentRequired));
772
- reply.header("WWW-Authenticate", `X-402 ${Buffer.from(JSON.stringify(paymentRequired)).toString("base64")}`);
773
- return reply.status(402).send({
774
- error: "Payment required",
775
- payment: paymentRequired
776
- });
777
- }
778
- const result = await verifyX402Payment(paymentHeader, {
779
- expectedAmount: priceMinor,
780
- expectedRecipient: recipient,
781
- chainId,
782
- facilitator,
783
- skipSettlement: options.testMode
784
- });
785
- if (!result.valid) {
786
- return reply.status(402).send({
787
- error: "Invalid payment",
788
- reason: result.error
789
- });
790
- }
791
- request.x402Payment = result;
792
- if (result.txHash) {
793
- reply.header("X-Payment-TxHash", result.txHash);
794
- }
795
- const receiptMode = options.receiptMode || "webhook";
796
- if ((receiptMode === "jwt" || receiptMode === "both") && result.txHash && result.payer) {
797
- try {
798
- const receipt = await fetchPaymentReceipt({
799
- txHash: result.txHash,
800
- payer: result.payer,
801
- recipient,
802
- amount: priceMinor,
803
- chainId,
804
- apiUrl: options.mixrpayApiUrl
805
- });
806
- if (receipt) {
807
- result.receipt = receipt;
808
- reply.header("X-Payment-Receipt", receipt);
809
- }
810
- } catch (receiptError) {
811
- request.log.warn({ err: receiptError }, "[x402] Failed to fetch JWT receipt");
812
- }
813
- }
814
- if (options.onPayment) {
815
- await options.onPayment(result);
816
- }
817
- };
818
- }
819
79
  export {
820
- ChargesClient,
821
- DEFAULT_FACILITATOR,
822
- USDC_CONTRACTS,
823
- clearJWKSCache,
824
- createPaymentRequired,
825
- x402 as expressX402,
826
- x4022 as fastifyX402,
827
- generateNonce,
828
- getDefaultJWKSUrl,
829
- isReceiptExpired,
830
- isValidAddress,
831
- minorToUsd,
832
- normalizeAddress,
833
- parsePaymentReceipt,
834
- parseSessionGrant,
835
- parseX402Payment,
836
- usdToMinor,
837
80
  verifyPaymentReceipt,
838
- verifySessionWebhook,
839
- verifyX402Payment,
840
- withX402,
841
- x402Plugin
81
+ verifySessionWebhook
842
82
  };
843
83
  //# sourceMappingURL=index.mjs.map