Provider SDK Quickstart
Protect your API endpoints with x402 payments in under 10 minutes. This guide will help you add payment requirements to your existing API.
Prerequisites
-
An existing API in one of these frameworks:
- Express (Node.js)
- FastAPI (Python)
- Django (Python)
- Gin (Go)
- Axum (Rust)
-
A Preimage Research Provider Account (sign up at preimage-research.ai (opens in a new tab))
-
Provider ID from the Preimage Research Console
Don't have a provider account yet? You can test with mock mode first, which doesn't require registration or blockchain transactions.
Choose Your Framework
Express Quickstart
Step 1: Install
npm install @preimage/expressStep 2: Add Middleware
import express from 'express';
import { createX402Middleware } from '@preimage/express';
const app = express();
app.use(express.json());
// Protect all /api/* routes
app.use('/api', createX402Middleware({
gatewayUrl: 'https://gateway.preimage.io',
providerId: process.env.PREIMAGE_PROVIDER_ID!,
pricing: {
usdcPerUnit: 0.001, // $0.001 per request
minUsdc: 0.002 // $0.002 minimum
}
}));
// Your protected endpoint
app.post('/api/summarize', (req, res) => {
const { text } = req.body;
res.json({ summary: `Summary of ${text}...` });
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});Step 3: Test It
# Without payment - returns 402
curl http://localhost:3000/api/summarize -d '{"text":"hello"}'
# With @preimage/client - automatically pays
npm install @preimage/clientTesting with Mock Mode
Before connecting to the real Gateway, test with mock mode:
createX402Middleware({
gatewayUrl: 'http://localhost:8080', // Won't be called in mock mode
providerId: 'test-provider',
mockPayments: true // Enable mock mode
})Mock mode bypasses all payment verification! Only use it for local testing, never in production.
How It Works
When you add the middleware, here's what happens:
1. First Request (No Payment)
curl http://localhost:3000/api/summarize -d '{"text":"hello"}'Response: 402 Payment Required
{
"x402Version": 1,
"accepts": [
{
"scheme": "exact",
"network": "base",
"maxAmountRequired": "980",
"description": "Provider payment",
"payTo": "0xYOUR_WALLET",
"asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
},
{
"scheme": "exact",
"network": "base",
"maxAmountRequired": "20",
"description": "Platform fee",
"payTo": "0xPLATFORM_WALLET",
"asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
}
],
"macaroon": "AgETd2FsbGV0...",
"providerId": "your-provider-id",
"endpointId": "ep_summarize",
"requestId": "req_abc123"
}2. Client Signs & Pays
The client (using @preimage/client):
- Signs two USDC payments (provider + platform)
- Submits to facilitator for on-chain verification
- Retries request with authorization proof
3. Second Request (With Payment)
curl http://localhost:3000/api/summarize \
-H "Authorization: x402 <macaroon>:<payment1>:<payment2>" \
-d '{"text":"hello"}'Response: 200 OK
{
"summary": "Summary of hello..."
}Headers:
Preimage-Receipt: eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9...✅ Payment verified! Your API handler is called, and a signed receipt is returned by Preimage Research.
Accessing Payment Info
All SDKs expose payment information in the request:
app.post('/api/data', (req: X402Request, res) => {
console.log('Receipt:', req.x402?.receipt);
console.log('Payment ID:', req.x402?.paymentId);
res.json({ data: '...' });
});Per-Route Pricing
Charge different amounts for different endpoints:
// Cheap endpoint - $0.001
app.get('/api/cheap',
protect({ pricing: { usdcPerUnit: 0.001 }}),
(req, res) => res.json({ data: '...' })
);
// Expensive endpoint - $0.01
app.post('/api/expensive',
protect({ pricing: { usdcPerUnit: 0.01 }}),
(req, res) => res.json({ data: '...' })
);Environment Variables
Create a .env file:
PREIMAGE_GATEWAY_URL=https://gateway.preimage.io
PREIMAGE_PROVIDER_ID=your-provider-id
MOCK_PAYMENTS=false # Set to true for testingProduction Checklist
Before going live:
- Register as a provider at preimage-research.ai (opens in a new tab)
- Add your payment wallet (where you'll receive USDC)
- Configure pricing for each endpoint
- Test with testnet (Base Sepolia) first
- Disable mock mode (
mockPayments: false) - Switch to mainnet Gateway URL
- Store receipts for accounting/reconciliation
- Monitor payments in the Preimage Research Console
That's it! Your API is now protected with x402 payments via Preimage Research. Every request requires USDC payment, and you get verifiable receipts for every transaction.
Next Steps
Explore Provider SDKs
Deep dive into your framework's SDK documentation
Testing Guide
Learn how to test your payment-gated API
Troubleshooting
"Gateway connection failed"
- Check that
PREIMAGE_GATEWAY_URLis correct - Ensure you have internet connectivity
- Try enabling mock mode for local testing
"Invalid provider ID"
- Verify
PREIMAGE_PROVIDER_IDfrom your console - Make sure you've registered as a provider
- Check for typos in the environment variable
"Payment verification failed"
- Ensure the client is using the correct network
- Check that your provider wallet is configured
- Verify pricing configuration matches between SDK and Gateway