Skip to content

Commit 91a3e9c

Browse files
authored
Update x402 docs (#293)
* update x402 docs * make pnpm default option in examples
1 parent 0dc3751 commit 91a3e9c

File tree

10 files changed

+428
-196
lines changed

10 files changed

+428
-196
lines changed

docs/docs.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@
136136
"pages": ["ledger/introduction"]
137137
},
138138
{
139-
"dropdown": "@sei-js/x402",
139+
"dropdown": "x402",
140140
"description": "HTTP micro payments",
141141
"icon": "credit-card",
142142
"pages": [

docs/x402/clients/fetch.mdx

Lines changed: 154 additions & 74 deletions
Original file line numberDiff line numberDiff line change
@@ -4,80 +4,160 @@ description: "Make paid HTTP requests with the native Fetch API and x402"
44
icon: "desktop"
55
---
66

7-
## Fetch Client Integration
7+
## Create Your First Fetch Client
88

99
Use x402 with the standard Fetch API to make paid HTTP requests. Perfect for both browser and Node.js environments.
1010

11-
## Installation
12-
13-
```bash
14-
npm install @sei-js/x402-fetch viem dotenv
15-
```
16-
17-
## Basic Usage
18-
19-
```typescript
20-
import { config } from "dotenv";
21-
import { Hex } from "viem";
22-
import { privateKeyToAccount } from "viem/accounts";
23-
import {
24-
wrapFetchWithPayment,
25-
decodeXPaymentResponse,
26-
} from "@sei-js/x402-fetch";
27-
28-
config();
29-
30-
const privateKey = process.env.PRIVATE_KEY as Hex;
31-
const baseURL = process.env.RESOURCE_SERVER_URL as string; // e.g. http://localhost:4021
32-
const endpointPath = process.env.ENDPOINT_PATH as string; // e.g. /weather
33-
const url = `${baseURL}${endpointPath}`;
34-
35-
if (!baseURL || !privateKey || !endpointPath) {
36-
console.error("Missing required environment variables");
37-
process.exit(1);
38-
}
39-
40-
// Create account from private key
41-
const account = privateKeyToAccount(privateKey);
42-
43-
// Wrap fetch with payment handling
44-
const fetchWithPayment = wrapFetchWithPayment(fetch, account);
45-
46-
// Make a paid request
47-
fetchWithPayment(url, {
48-
method: "GET",
49-
})
50-
.then(async (response) => {
51-
const body = await response.json();
52-
console.log("Response:", body);
53-
54-
// Decode the payment response
55-
const paymentResponse = decodeXPaymentResponse(
56-
response.headers.get("x-payment-response")!
57-
);
58-
console.log("Payment details:", paymentResponse);
59-
})
60-
.catch((error) => {
61-
console.error("Error:", error.response?.data?.error);
62-
});
63-
```
64-
65-
## Environment Setup
66-
67-
Create a `.env` file with the required configuration:
68-
69-
```env
70-
# Required: Your private key for making payments
71-
PRIVATE_KEY=0xYourPrivateKeyHere
72-
73-
# Required: The server URL hosting the paid API
74-
RESOURCE_SERVER_URL=http://localhost:4021
75-
76-
# Required: The endpoint path to access
77-
ENDPOINT_PATH=/weather
78-
```
79-
80-
<Warning>
81-
**Security Note**: Never commit private keys to version control. Use
82-
environment variables or secure key management services in production.
83-
</Warning>
11+
<Steps>
12+
<Step title="Install Dependencies">
13+
Create a new project and install the required packages:
14+
15+
<CodeGroup>
16+
```bash pnpm
17+
mkdir my-fetch-client && cd my-fetch-client
18+
pnpm init -y
19+
pnpm add x402-fetch @coinbase/x402 viem dotenv tsx
20+
```
21+
22+
```bash yarn
23+
mkdir my-fetch-client && cd my-fetch-client
24+
yarn init -y
25+
yarn add x402-fetch @coinbase/x402 viem dotenv tsx
26+
```
27+
28+
```bash npm
29+
mkdir my-fetch-client && cd my-fetch-client
30+
npm init -y
31+
npm install x402-fetch @coinbase/x402 viem dotenv tsx
32+
```
33+
</CodeGroup>
34+
35+
<Check>
36+
**Expected outcome:** Project directory created with x402 fetch client dependencies installed.
37+
</Check>
38+
</Step>
39+
40+
<Step title="Environment Configuration">
41+
Create a `.env` file in your project root:
42+
43+
```env
44+
# Required: Your private key for making payments
45+
PRIVATE_KEY=0xYourPrivateKeyHere
46+
47+
# Required: The server URL hosting the paid API
48+
RESOURCE_SERVER_URL=http://localhost:4021
49+
50+
# Required: The endpoint path to access
51+
ENDPOINT_PATH=/weather
52+
```
53+
54+
<Warning>
55+
**Security Note**: Never commit private keys to version control. Use environment variables or secure key management services in production. For testing, you can use a dummy private key.
56+
</Warning>
57+
58+
<Check>
59+
**Expected outcome:** Environment variables configured for your fetch client.
60+
</Check>
61+
</Step>
62+
63+
<Step title="Create the fetch client">
64+
Create `fetch-client.ts` with the payment-enabled fetch implementation:
65+
66+
```typescript
67+
import { config } from "dotenv";
68+
import { Hex } from "viem";
69+
import { privateKeyToAccount } from "viem/accounts";
70+
import {
71+
wrapFetchWithPayment,
72+
decodeXPaymentResponse,
73+
} from "x402-fetch";
74+
75+
config();
76+
77+
const privateKey = process.env.PRIVATE_KEY as Hex;
78+
const baseURL = process.env.RESOURCE_SERVER_URL as string;
79+
const endpointPath = process.env.ENDPOINT_PATH as string;
80+
const url = `${baseURL}${endpointPath}`;
81+
82+
if (!baseURL || !privateKey || !endpointPath) {
83+
console.error("Missing required environment variables");
84+
process.exit(1);
85+
}
86+
87+
// Create account from private key
88+
const account = privateKeyToAccount(privateKey);
89+
90+
// Wrap fetch with payment handling
91+
const fetchWithPayment = wrapFetchWithPayment(fetch, account);
92+
93+
// Make a paid request
94+
fetchWithPayment(url, {
95+
method: "GET",
96+
})
97+
.then(async (response) => {
98+
const body = await response.json();
99+
console.log("Response:", body);
100+
101+
// Decode the payment response
102+
const paymentResponse = decodeXPaymentResponse(
103+
response.headers.get("x-payment-response")!
104+
);
105+
console.log("Payment details:", paymentResponse);
106+
})
107+
.catch((error) => {
108+
console.error("Error:", error.message);
109+
});
110+
```
111+
112+
<Check>
113+
**Expected outcome:** Fetch client code created with automatic payment handling.
114+
</Check>
115+
</Step>
116+
117+
<Step title="Run your fetch client">
118+
Execute your fetch client to make paid requests:
119+
120+
<CodeGroup>
121+
```bash pnpm
122+
pnpx tsx fetch-client.ts
123+
```
124+
125+
```bash yarn
126+
yarn tsx fetch-client.ts
127+
```
128+
129+
```bash npm
130+
npx tsx fetch-client.ts
131+
```
132+
133+
```bash direct
134+
npx tsx fetch-client.ts
135+
```
136+
</CodeGroup>
137+
138+
<Check>
139+
**Expected outcome:** The client should automatically handle the 402 Payment Required response, make the payment, and receive the protected content.
140+
</Check>
141+
142+
<Info>
143+
Make sure your paid API server is running on the configured URL. The fetch client will automatically detect 402 responses, handle payment processing, and retry the request with payment proof.
144+
</Info>
145+
146+
Example successful output:
147+
```bash
148+
Response: {
149+
report: {
150+
weather: 'sunny',
151+
temperature: 70
152+
}
153+
}
154+
Payment details: {
155+
success: true,
156+
transaction: '0x1234567890abcdef...',
157+
network: 'sei-testnet',
158+
payer: '0xYourWalletAddress...'
159+
}
160+
```
161+
</Step>
162+
163+
</Steps>

0 commit comments

Comments
 (0)