Skip to Content
DocsQuickstartsJavaScript Quickstart (@fx402/r402)

JavaScript Quickstart (@fx402/r402)

COMING SOON

This guide shows how to integrate FX402 in any JavaScript or TypeScript app using the official @fx402/r402 SDK.
It handles the full payment flow: detect 402 → choose tier → pay → verify → retry → unlock.


⚙️ 1. Installation

npm install @fx402/r402 # or pnpm add @fx402/r402

🧩 2. Basic Setup

import { r402Fetch, attachWallet } from "@fx402/r402"; import { getPhantomWallet } from "@fx402/wallets"; // 1. Attach wallet adapter (Phantom, Backpack, or custom) attachWallet({ chain: "solana", async payUSDC({ to, amount, memo }) { const wallet = await getPhantomWallet(); return wallet.transferUSDC(to, amount, memo); }, }); // 2. Perform a request to a protected resource const res = await r402Fetch("https://fx402.xyz/api/memes/rare-001.png", { async on402(requirements) { // Called when 402 Payment Required is received console.log("Payment required:", requirements); // Example: auto-select 7-day tier const tier = requirements.usage.tiers.find(t => t.id === "7d"); return { tier_id: tier.id, // Optional: show pricing UI here before confirming }; }, }); // 3. Read unlocked content or receipt const blob = await res.blob(); console.log("Resource unlocked:", blob);

🧠 3. Understanding r402Fetch

The r402Fetch() helper wraps around fetch() with x402 support:

StepDescription
1️⃣Sends normal request
2️⃣Intercepts 402 Payment Required
3️⃣Calls on402() callback so you can pick a tier
4️⃣Handles payment automatically via attached wallet
5️⃣Retries request with payment proof
6️⃣Returns unlocked response and cached receipt

🧾 4. Verifying Receipts

When a receipt JWT is included in the response headers or JSON:

const receipt = await res.json(); console.log(receipt.receipt.jwt); // signed proof

You can validate it manually:

import { verifyReceipt } from "@fx402/r402"; const isValid = await verifyReceipt(receipt.receipt.jwt); if (isValid) console.log("Receipt verified!");

🔐 5. Configuration Options

r402Fetch(url, { on402, // required callback for payment flow headers, // custom headers autoRetry: true, // auto retry after payment storeReceipt: true // persist receipts in localStorage });

🧰 6. Advanced Usage

Handling Multiple Wallets

import { attachWallet } from "@fx402/r402"; attachWallet({ chain: "base", async payETH({ to, amount }) { // implement custom wallet logic here }, });

Custom Facilitator Verification

import { setFacilitator } from "@fx402/r402"; setFacilitator("https://facilitator.fx402.xyz/settle");

✅ Summary

FunctionPurpose
attachWallet()Binds your payment function or wallet adapter
r402Fetch()Replaces normal fetch and handles 402 logic
verifyReceipt()Validates a signed receipt or JWT
setFacilitator()Optional override for verification endpoint

📚 Next Steps

Last updated on