X402 on Solana
The Complete Integration Guide
Building AI-Powered Payment Systems with X402, Solana Pay, Stripe, and Shopify

A comprehensive guide to implementing the X402 protocol on Solana with integrations for e-commerce platforms and AI agent orchestration
Introduction: The X402 Protocol on Solana
The X402 protocol represents a paradigm shift in blockchain payment infrastructure by implementing the dormant HTTP 402 "Payment Required" status code to create a seamless, machine-native payment experience. When implemented on Solana's high-performance blockchain, X402 enables a new generation of applications where AI agents can autonomously execute financial transactions with near-zero fees and sub-second finality.
This guide walks through implementing X402 on Solana, connecting it with Solana Pay, Stripe, and Shopify, while leveraging Helius Smart Transactions and our custom X402 Agent for autonomous payment orchestration.
Why X402 on Solana?
Solana provides the ideal foundation for X402 payments with:
400ms Transaction Finality: Near-instant payments (vs. days for traditional methods)
Negligible Fees: Transactions cost just $0.00025 (vs. 2-3% for credit cards)
Token Flexibility: Support for SOL, USDC, and all SPL tokens
High Throughput: Thousands of transactions per second
Rich Ecosystem: Integration with Solana Pay, Helius, and other tools
Architecture Overview
The X402 Solana implementation consists of several interlinked components:
┌─────────────────────────────────────────────────────────────────┐
│ X402 Payment Agent │
├─────────────┬─────────────┬────────────────┬───────────────────┤
│ HTTP 402 │ Multi-Chain │ E-Commerce │ Trusted Execution │
│ Protocol │ Payment │ Integrations │ Environment │
│ Handler │ Processor │ │ │
└─────┬───────┴─────┬───────┴────────┬───────┴────────┬──────────┘
│ │ │ │
▼ ▼ ▼ ▼
┌─────────────┐ ┌───────────────┐ ┌────────────┐ ┌──────────────┐
│ X402 API │ │ Blockchain │ │ Shopify/ │ │Cross-Chain │
│ Endpoint │ │ Connectors │ │ Stripe │ │Transaction │
└─────────────┘ └───────────────┘ └────────────┘ └──────────────┘
│
┌─────────────┼─────────────┐
▼ ▼ ▼
┌─────────────┐ ┌─────────────┐ ┌────────────┐
│ Solana │ │ Base │ │ Bitcoin │
│ Connector │ │ Connector │ │ Connector │
└─────────────┘ └─────────────┘ └────────────┘
Core Components:
X402 Protocol Handler: Implements the HTTP 402 status code response and payment verification
Solana Integration Layer: Connects to Solana for transaction processing using Helius Smart Transactions
E-commerce Connectors: Integrates with Shopify and Stripe
AI Agent Swarm: Orchestrates autonomous payment operations
Trusted Execution Environment: Ensures secure transaction handling
Setting Up X402 on Solana
1. X402 Server Implementation
First, create an Express.js server that handles X402 payment requests:
// Install required packages
// npm install express @solana/web3.js @helius-sdk/helius-sdk
const express = require('express');
const { Connection, PublicKey, Transaction } = require('@solana/web3.js');
const { Helius } = require('helius-sdk');
const app = express();
app.use(express.json());
// Initialize Helius client for Smart Transactions
const helius = new Helius('your-api-key');
// Configure your merchant wallet
const MERCHANT_WALLET = new PublicKey('Your_Solana_Wallet_Address');
const USDC_MINT = new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'); // Solana USDC mint
// X402 payment middleware
const x402PaymentRequired = (price, description = 'Resource access') => {
return (req, res, next) => {
// Check if payment token is in header
const paymentToken = req.headers['x-payment-token'];
if (paymentToken && verifyPayment(paymentToken)) {
// Payment verified, proceed to resource
return next();
}
// No valid payment, return 402 with payment details
res.status(402).json({
x402Version: 1,
accepts: [{
scheme: 'exact',
network: 'solana-mainnet',
maxAmountRequired: (price * 1000000).toString(), // Convert to USDC smallest unit
resource: req.originalUrl,
description: description,
mimeType: 'application/json',
payTo: MERCHANT_WALLET.toString(),
maxTimeoutSeconds: 30,
asset: USDC_MINT.toString(),
extra: null
}],
error: null
});
};
};
// Example protected endpoint
app.get('/api/premium-data', x402PaymentRequired(0.01, 'Premium financial data'), (req, res) => {
// This only executes if payment is verified
res.json({ data: 'Your premium financial data' });
});
// Payment verification endpoint
app.post('/api/verify-payment', async (req, res) => {
const { signature, publicKey } = req.body;
try {
// Verify transaction on Solana using Helius
const tx = await helius.rpc.getTransaction(signature);
if (tx && tx.meta && !tx.meta.err) {
// Store verified payment token
storeVerifiedPayment(signature, publicKey);
res.json({ success: true, token: signature });
} else {
res.status(400).json({ success: false, error: 'Invalid transaction' });
}
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
});
app.listen(3000, () => {
console.log('X402 Solana server running on port 3000');
});
2. Implementing Helius Smart Transactions
Optimize your Solana transactions with Helius Smart Transactions for maximum reliability:
// Process payment using Helius Smart Transactions
async function processPayment(amount, recipientPublicKey, payerKeypair) {
try {
// Create payment instruction
const instructions = [
// USDC transfer instruction would go here
// This is simplified; in production you'd create the appropriate SPL token transfer
];
// Use Helius Smart Transactions to optimize and send
const txid = await helius.rpc.sendSmartTransaction(
instructions,
[payerKeypair],
[], // Optional lookup tables
{ skipPreflight: true, maxRetries: 0 }
);
console.log('Payment sent with Smart Transaction:', txid);
return txid;
} catch (error) {
console.error('Payment failed:', error);
throw error;
}
}
Integrating with Solana Pay
Enhance your X402 implementation with Solana Pay for QR code-based payments:
// npm install @solana/pay
const { encodeURL, createQR } = require('@solana/pay');
// Create a Solana Pay payment URL
function createSolanaPayUrl(amount, reference, label = 'X402 Payment') {
const url = encodeURL({
recipient: MERCHANT_WALLET,
amount: amount,
reference: reference,
label: label,
message: 'Payment for premium content',
memo: 'X402 Protocol Payment'
});
return url;
}
// Generate QR code for payment
app.get('/api/payment-qr/:amount', (req, res) => {
const amount = parseFloat(req.params.amount);
const reference = new Uint8Array(32); // Would be a unique reference in production
const url = createSolanaPayUrl(amount, reference);
// Return URL for QR code generation on client
res.json({ paymentUrl: url.toString() });
});
Shopify Integration
Connect X402 with Shopify for e-commerce integration:
// Simplified Shopify integration endpoint
app.post('/api/shopify/create-checkout', async (req, res) => {
const { items, customerEmail } = req.body;
// Calculate total price
const totalPrice = items.reduce((sum, item) => sum + (item.price * item.quantity), 0);
// Create a unique payment ID
const paymentId = `x402-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
// Store checkout details for later verification
storeCheckoutDetails(paymentId, {
items,
totalPrice,
customerEmail,
status: 'pending'
});
// Generate payment URL with Solana Pay
const paymentUrl = createSolanaPayUrl(totalPrice, paymentId, 'Shopify Order');
res.json({
checkoutId: paymentId,
paymentUrl: paymentUrl.toString(),
totalPrice,
expiresAt: Date.now() + (30 * 60 * 1000) // 30 minutes expiry
});
});
// Webhook for Shopify payment confirmation
app.post('/api/shopify/payment-webhook', async (req, res) => {
const { signature, checkoutId } = req.body;
// Verify the transaction on Solana
const tx = await helius.rpc.getTransaction(signature);
if (tx && tx.meta && !tx.meta.err) {
// Update checkout status
updateCheckoutStatus(checkoutId, 'paid');
// Notify Shopify about successful payment
// This would integrate with Shopify's API in production
res.json({ success: true });
} else {
res.status(400).json({ success: false, error: 'Invalid transaction' });
}
});
Stripe as a Fallback Payment Option
Integrate Stripe as an alternative payment method for users without crypto:
// npm install stripe
const stripe = require('stripe')('your_stripe_secret_key');
// Create a Stripe payment intent
app.post('/api/create-stripe-payment', async (req, res) => {
const { amount, currency = 'usd' } = req.body;
try {
const paymentIntent = await stripe.paymentIntents.create({
amount: Math.round(amount * 100), // Stripe uses cents
currency: currency,
automatic_payment_methods: {
enabled: true,
},
metadata: {
x402_payment: 'true',
resource_url: req.body.resourceUrl
}
});
res.json({
clientSecret: paymentIntent.client_secret,
paymentId: paymentIntent.id
});
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Stripe webhook handler
app.post('/api/stripe-webhook', async (req, res) => {
const event = req.body;
// Handle successful payment
if (event.type === 'payment_intent.succeeded') {
const paymentIntent = event.data.object;
// Store payment confirmation for X402 verification
if (paymentIntent.metadata.x402_payment === 'true') {
storeVerifiedPayment(paymentIntent.id, null, 'stripe');
}
}
res.json({ received: true });
});
X402 AI Agent Implementation
Implement an AI-powered agent that can autonomously make payments using the X402 protocol:
// X402 Agent for autonomous payments
class X402Agent {
constructor(walletKeypair, connection, helius) {
this.wallet = walletKeypair;
this.connection = connection;
this.helius = helius;
this.spendingLimits = {
perTransaction: 1.0, // Maximum USDC per transaction
daily: 10.0 // Maximum USDC per day
};
this.dailySpent = 0;
}
// Create a fetch function that handles X402 payments automatically
createFetchWithPayment() {
const self = this;
return async function fetchWithPayment(url, options = {}) {
// First attempt without payment
const response = await fetch(url, options);
// If the response is 402 Payment Required, handle it
if (response.status === 402) {
const paymentDetails = await response.json();
const acceptedPayment = paymentDetails.accepts[0];
// Check if payment is within limits
const amount = parseFloat(acceptedPayment.maxAmountRequired) / 1000000; // Convert from USDC smallest unit
if (amount > self.spendingLimits.perTransaction) {
throw new Error(`Payment amount exceeds per-transaction limit of ${self.spendingLimits.perTransaction} USDC`);
}
if (self.dailySpent + amount > self.spendingLimits.daily) {
throw new Error(`Payment would exceed daily limit of ${self.spendingLimits.daily} USDC`);
}
// Process the payment using Helius Smart Transactions
const signature = await self._makePayment(
amount,
new PublicKey(acceptedPayment.payTo),
new PublicKey(acceptedPayment.asset)
);
// Update daily spent amount
self.dailySpent += amount;
// Retry the request with payment token
const newOptions = {
...options,
headers: {
...(options.headers || {}),
'X-Payment-Token': signature
}
};
return fetch(url, newOptions);
}
return response;
};
}
// Make a payment using Helius Smart Transactions
async _makePayment(amount, recipient, tokenMint) {
// Create the appropriate token transfer instruction
// This is simplified; in production, you'd create the proper SPL token transfer
const instructions = [
// USDC transfer instruction would go here
];
// Use Helius Smart Transactions
const signature = await this.helius.rpc.sendSmartTransaction(
instructions,
[this.wallet],
[], // Optional lookup tables
{ skipPreflight: true, maxRetries: 0 }
);
console.log(`Payment of ${amount} USDC sent to ${recipient.toString()}`);
return signature;
}
}
Demo Transaction: End-to-End X402 Payment Flow
Let's walk through a complete example of an X402 payment on Solana:
Step 1: Client requests a protected resource
// Client code
const X402Client = require('./x402-client');
const { Keypair } = require('@solana/web3.js');
const { Helius } = require('helius-sdk');
async function demoPremiumDataAccess() {
// Initialize Helius client
const helius = new Helius('your-api-key');
// Initialize wallet from private key (in a secure way)
const wallet = Keypair.fromSecretKey(/* your private key */);
// Create X402 agent
const agent = new X402Client(wallet, helius);
// Create fetch function with automatic X402 payment handling
const fetch = agent.createFetchWithPayment();
console.log("Requesting premium data...");
try {
// Request protected resource
const response = await fetch('https://api.example.com/api/premium-data');
if (response.ok) {
const data = await response.json();
console.log("Successfully accessed premium data:", data);
} else {
console.error("Failed to access data:", await response.text());
}
} catch (error) {
console.error("Error accessing premium data:", error);
}
}
demoPremiumDataAccess();
Step 2: Server responds with 402 Payment Required
The server sends a response with status code 402 and the payment details:
{
"x402Version": 1,
"accepts": [{
"scheme": "exact",
"network": "solana-mainnet",
"maxAmountRequired": "10000",
"resource": "/api/premium-data",
"description": "Premium financial data",
"mimeType": "application/json",
"payTo": "BWjTQEST9afw9UCoYL3jeanZZMpGjBwKoTJYNbFAhSrg",
"maxTimeoutSeconds": 30,
"asset": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"
}],
"error": null
}
Step 3: Client creates and sends a payment transaction
The X402 agent automatically:
Parses the payment details
Verifies the amount is within spending limits
Creates a USDC transfer transaction
Optimizes it with Helius Smart Transactions
Signs and sends the transaction
// This happens inside the X402Agent's _makePayment method
async function createOptimizedPayment(amount, recipient, tokenMint) {
// Create token transfer instruction
const transferInstruction = createTransferInstruction(
tokenMint,
amount,
this.wallet.publicKey,
recipient
);
// Use Helius Smart Transactions to optimize and send
const signature = await this.helius.rpc.sendSmartTransaction(
[transferInstruction],
[this.wallet],
[], // Optional lookup tables
{ skipPreflight: true, maxRetries: 0 }
);
// Wait for confirmation
await this.connection.confirmTransaction(signature);
return signature;
}
Step 4: Client retries the request with payment token
// This happens automatically in the fetchWithPayment function
const retryResponse = await fetch(url, {
...options,
headers: {
...(options.headers || {}),
'X-Payment-Token': signature
}
});
Step 5: Server verifies the payment and delivers the resource
// This happens in the x402PaymentRequired middleware
if (paymentToken && verifyPayment(paymentToken)) {
// Payment verified, proceed to resource
return next();
}
// Helper function to verify payment
async function verifyPayment(signature) {
try {
// Check if payment has been processed before
if (paymentCache.has(signature)) {
return true;
}
// Verify transaction on Solana
const tx = await helius.rpc.getTransaction(signature);
if (!tx || tx.meta.err) {
return false;
}
// Verify it's a payment to our wallet
// This is simplified; you'd need to parse the transaction to verify amounts, etc.
const isValidPayment = tx.transaction.message.accountKeys.some(key =>
key.toString() === MERCHANT_WALLET.toString()
);
if (isValidPayment) {
// Cache the valid payment
paymentCache.set(signature, true);
return true;
}
return false;
} catch (error) {
console.error('Payment verification error:', error);
return false;
}
}
E-commerce Integration Demo: Shopify + X402 + Solana Pay
Here's a complete example of integrating X402 with Shopify using Solana Pay:
// Setup environment for Shopify + X402 + Solana Pay integration
const express = require('express');
const { Connection, PublicKey } = require('@solana/web3.js');
const { encodeURL, findReference } = require('@solana/pay');
const { Helius } = require('helius-sdk');
const ShopifyAPI = require('@shopify/shopify-api');
const app = express();
app.use(express.json());
// Initialize Helius and Solana connection
const helius = new Helius('your-api-key');
const connection = new Connection('https://api.mainnet-beta.solana.com');
// Initialize Shopify API client
const shopify = ShopifyAPI.Shopify.Context.initialize({
API_KEY: 'your-shopify-api-key',
API_SECRET_KEY: 'your-shopify-api-secret',
SCOPES: ['read_products', 'write_orders'],
HOST_NAME: 'your-app-hostname.com',
API_VERSION: '2023-07'
});
// Configure merchant wallet for Solana Pay
const MERCHANT_WALLET = new PublicKey('Your_Solana_Wallet_Address');
// Create Shopify checkout with Solana Pay
app.post('/api/create-checkout', async (req, res) => {
try {
const { cartItems, email } = req.body;
// Create new order in Shopify
const shopifyOrder = await createShopifyOrder(cartItems, email);
// Generate unique reference for this order
const reference = new Uint8Array(32);
crypto.getRandomValues(reference);
// Store reference for later verification
storeOrderReference(shopifyOrder.id, reference);
// Calculate total price
const totalPrice = shopifyOrder.total_price;
// Create Solana Pay URL
const url = encodeURL({
recipient: MERCHANT_WALLET,
amount: parseFloat(totalPrice),
reference: reference,
label: `Order #${shopifyOrder.order_number}`,
message: 'Thanks for your purchase!',
memo: `Shopify Order #${shopifyOrder.order_number}`
});
res.json({
orderId: shopifyOrder.id,
orderNumber: shopifyOrder.order_number,
paymentUrl: url.toString(),
totalAmount: totalPrice
});
} catch (error) {
console.error('Error creating checkout:', error);
res.status(500).json({ error: error.message });
}
});
// Endpoint to check payment status
app.get('/api/check-payment/:orderId', async (req, res) => {
try {
const { orderId } = req.params;
// Get reference for this order
const reference = getOrderReference(orderId);
if (!reference) {
return res.status(404).json({ error: 'Order not found' });
}
// Check if there's a transaction with this reference
const signatureInfo = await findReference(connection, reference);
if (!signatureInfo) {
return res.json({ status: 'pending' });
}
// Verify the transaction
const txId = signatureInfo.signature;
const tx = await helius.rpc.getTransaction(txId);
if (tx && !tx.meta.err) {
// Update order status in Shopify
await updateShopifyOrderStatus(orderId, 'paid');
res.json({
status: 'paid',
signature: txId,
confirmationTime: new Date(tx.blockTime * 1000).toISOString()
});
} else {
res.json({ status: 'failed' });
}
} catch (error) {
console.error('Error checking payment:', error);
res.status(500).json({ error: error.message });
}
});
// Helper functions for Shopify API integration
async function createShopifyOrder(cartItems, email) {
// Implementation would use Shopify API to create order
// This is a placeholder for illustration
return {
id: '12345',
order_number: '1001',
total_price: '19.99',
customer: { email }
};
}
async function updateShopifyOrderStatus(orderId, status) {
// Implementation would update order status via Shopify API
console.log(`Updating order ${orderId} status to: ${status}`);
}
// Start server
app.listen(3000, () => {
console.log('X402 Shopify integration server running on port 3000');
});
AI Agent Autonomy: X402 Agent Swarm
For advanced users, implement an X402 Agent Swarm for coordinated autonomous operations:
// X402 Agent Swarm Implementation
class X402AgentSwarm {
constructor(config) {
this.connection = new Connection(config.rpcUrl);
this.helius = new Helius(config.heliusApiKey);
// Initialize various agent types
this.paymentAgents = [];
this.discoveryAgents = [];
this.policyAgents = [];
// Initialize swarm configuration
this.config = config;
// Set up event system for inter-agent communication
this.eventBus = new EventEmitter();
}
// Initialize agents in the swarm
async initializeSwarm() {
// Create payment agents
for (let i = 0; i < this.config.agentCounts.payment; i++) {
this.paymentAgents.push(new PaymentAgent(
this.eventBus,
this.connection,
this.helius,
this.config.wallets[i % this.config.wallets.length],
this.config.paymentAgentConfig
));
}
// Create discovery agents
for (let i = 0; i < this.config.agentCounts.discovery; i++) {
this.discoveryAgents.push(new DiscoveryAgent(
this.eventBus,
this.config.discoveryAgentConfig
));
}
// Create policy agents
for (let i = 0; i < this.config.agentCounts.policy; i++) {
this.policyAgents.push(new PolicyAgent(
this.eventBus,
this.config.policyAgentConfig
));
}
// Initialize all agents
await Promise.all([
...this.paymentAgents.map(agent => agent.initialize()),
...this.discoveryAgents.map(agent => agent.initialize()),
...this.policyAgents.map(agent => agent.initialize())
]);
console.log(`X402 Agent Swarm initialized with ${this.paymentAgents.length} payment agents`);
}
// Process a payment request autonomously
async processPaymentRequest(url, options = {}) {
// Select the most appropriate payment agent
const agent = this.selectPaymentAgent();
// Create fetch function with payment capabilities
const fetch = agent.createFetchWithPayment();
// Execute the request
return fetch(url, options);
}
// Select the most appropriate payment agent based on load balancing
selectPaymentAgent() {
// Simple round-robin selection for demonstration
const nextAgentIndex = this._currentAgentIndex % this.paymentAgents.length;
this._currentAgentIndex = (this._currentAgentIndex + 1) % this.paymentAgents.length;
return this.paymentAgents[nextAgentIndex];
}
}
// Agent implementations would include specialized behaviors for different roles
class PaymentAgent {
// Implementation for payment processing agent
}
class DiscoveryAgent {
// Implementation for API discovery agent
}
class PolicyAgent {
// Implementation for policy enforcement agent
}
Conclusion: The Future of AI-Driven Payments on Solana
The X402 protocol on Solana represents a fundamental evolution in how payments work on the internet. By combining Solana's speed and efficiency with the X402 protocol's HTTP-native approach, we've created a foundation for truly autonomous commerce between humans, applications, and AI agents.
Key advantages of this implementation include:
Seamless Integration: One-line integration with existing HTTP infrastructure
AI Agent Autonomy: Enables AI systems to make independent payment decisions
Near-Zero Fees: Fraction of a cent per transaction
Instant Settlement: 400ms transaction finality
Platform Flexibility: Works with Shopify, Stripe, and any HTTP service
As AI technology continues to advance, payment systems that enable financial autonomy will become essential infrastructure. X402 on Solana provides this infrastructure today, allowing developers to build the next generation of AI-powered applications that can participate directly in the digital economy.
Resources and Next Steps
Ready to start building? Clone our example repository and follow the setup instructions to implement X402 payments in your application today!
git clone https://github.com/your-org/x402-solana-starter
cd x402-solana-starter
npm install
npm run dev
This article was last updated on May 11, 2025.
Last updated