Integration Examples
Complete examples for integrating with the x402 Gateway using the official x402 client libraries.
TypeScript / JavaScript
Use the @x402/fetch package, which wraps the standard fetch API with automatic payment handling.
npm install @x402/fetch @x402/evm viemimport { wrapFetch } from "@x402/fetch";
import { ExactEvmScheme } from "@x402/evm/exact/client";
import { createWalletClient, http } from "viem";
import { privateKeyToAccount } from "viem/accounts";
// Create wallet client
const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);
const walletClient = createWalletClient({
account,
chain: {
id: 10744,
name: "OpenGradient",
nativeCurrency: { name: "OG", symbol: "OG", decimals: 18 },
rpcUrls: { default: { http: ["https://rpc.opengradient.ai"] } },
},
transport: http(),
});
// Wrap fetch with x402 payment handling
const x402Fetch = wrapFetch(fetch, {
schemes: [
{ network: "eip155:10744", client: new ExactEvmScheme(walletClient) },
],
});
// Use like normal fetch - payments handled automatically
const response = await x402Fetch(
"https://llmogevm.opengradient.ai/v1/chat/completions",
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
model: "openai/gpt-4o",
messages: [{ role: "user", content: "What is quantum computing?" }],
max_tokens: 200,
}),
}
);
const result = await response.json();
console.log(result.choices[0].message.content);For other HTTP clients, see @x402/axios or @x402/core for lower-level control.
Python
Use the OpenGradient SDK which handles x402 payments automatically:
pip install opengradientimport opengradient as og
import os
client = og.Client(
private_key=os.environ.get("OG_PRIVATE_KEY"),
)
result = client.llm.chat(
model=og.TEE_LLM.GPT_4O,
messages=[
{"role": "user", "content": "What is quantum computing?"}
],
max_tokens=200
)
print(result.chat_output["content"])
print(f"Payment hash: {result.payment_hash}")See the SDK documentation for more examples including tool calling and TEE inference.
Go
Use the official x402 Go client library for automatic payment handling.
go get github.com/coinbase/x402/gopackage main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
x402 "github.com/coinbase/x402/go"
x402http "github.com/coinbase/x402/go/http"
evm "github.com/coinbase/x402/go/mechanisms/evm/exact/client"
evmsigners "github.com/coinbase/x402/go/signers/evm"
)
type Message struct {
Role string `json:"role"`
Content string `json:"content"`
}
type ChatRequest struct {
Model string `json:"model"`
Messages []Message `json:"messages"`
MaxTokens int `json:"max_tokens"`
}
func main() {
// Create signer from private key
signer, err := evmsigners.NewClientSignerFromPrivateKey(os.Getenv("PRIVATE_KEY"))
if err != nil {
fmt.Println("Error creating signer:", err)
return
}
// Create x402 client and register OpenGradient network
client := x402.Newx402Client().
Register("eip155:10744", evm.NewExactEvmScheme(signer))
// Wrap HTTP client with automatic payment handling
httpClient := x402http.WrapHTTPClientWithPayment(
http.DefaultClient,
x402http.Newx402HTTPClient(client),
)
// Prepare request body
body, _ := json.Marshal(ChatRequest{
Model: "openai/gpt-4o",
Messages: []Message{
{Role: "user", Content: "What is quantum computing?"},
},
MaxTokens: 200,
})
// Make request - payments handled automatically
resp, err := httpClient.Post(
"https://llmogevm.opengradient.ai/v1/chat/completions",
"application/json",
bytes.NewReader(body),
)
if err != nil {
fmt.Println("Error:", err)
return
}
defer resp.Body.Close()
// Parse response
respBody, _ := io.ReadAll(resp.Body)
var result map[string]interface{}
json.Unmarshal(respBody, &result)
choices := result["choices"].([]interface{})
message := choices[0].(map[string]interface{})["message"].(map[string]interface{})
fmt.Println(message["content"])
}See the x402 Go documentation for more details.
curl (Testing)
For testing and debugging, you can use curl to inspect the payment flow:
# Step 1: Get payment requirements
curl -X POST https://llmogevm.opengradient.ai/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "openai/gpt-4o",
"messages": [{"role": "user", "content": "Hello!"}],
"max_tokens": 100
}' \
-i
# The response will include X-PAYMENT-REQUIRED header
# Decode it with: echo "<base64>" | base64 -d | jqNOTE
The payment signing step requires cryptographic operations that can't be done in pure bash. Use one of the language examples above for the signing step.
With Settlement Mode
To use a specific settlement mode, add the X-SETTLE header:
// TypeScript example with metadata settlement
const response = await x402Fetch(
"https://llmogevm.opengradient.ai/v1/chat/completions",
{
method: "POST",
headers: {
"Content-Type": "application/json",
"X-SETTLE": "SETTLE_INDIVIDUAL_WITH_METADATA", // Full prompt/response on-chain
},
body: JSON.stringify({
model: "openai/gpt-4o",
messages: [{ role: "user", content: "Hello!" }],
max_tokens: 100,
}),
}
);# Python SDK example with metadata settlement
result = client.llm.chat(
model=og.TEE_LLM.GPT_4_1_2025_04_14,
messages=messages,
x402_settlement_mode=og.x402SettlementMode.SETTLE_METADATA
)x402 Client Libraries
The official x402 libraries handle all payment complexity for you:
| Package | Description |
|---|---|
| @x402/core | Core x402 client/server implementation |
| @x402/evm | EVM chain support (Ethereum, Base, OpenGradient) |
| @x402/fetch | Fetch API wrapper |
| @x402/axios | Axios interceptor |
See the x402 GitHub repository for more examples and documentation.
Next Steps
- API Reference - Complete endpoint documentation
- Python SDK - Simplified Python integration
- LLM Execution - How x402 works under the hood
