Skip to content

Commit abcef68

Browse files
committed
adds x402 starter material
1 parent cfa9c08 commit abcef68

File tree

4 files changed

+302
-0
lines changed

4 files changed

+302
-0
lines changed

docs/pos/payments/x402/overview.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# x402 on Polygon
2+
3+
x402 is an open payment protocol that brings blockchain payments
4+
into a familiar web standard. By re-using the HTTP `402 Payment Required`
5+
status code, it lets developers handle on-chain and agentic payments with
6+
the same tools they already use for APIs and web services.
7+
8+
Instead of building complex wallet integrations or subscription systems,
9+
**developers can simply treat payments like another part of the HTTP request/response
10+
cycle.** This lowers the barrier for web2 developers experimenting with crypto,
11+
while also giving web3 builders a lightweight way to support pay-per-use APIs,
12+
agent-to-agent transactions, and micropayments.
13+
14+
[Read more about the x402 architecture and concepts here.](https://x402.gitbook.io/x402)
15+
16+
## Access on Polygon
17+
18+
Polygon currently supports x402 on Mainnet and Amoy through the following facilitators:
19+
20+
1. [x402.rs Facilitator Endpoint](https://facilitator.x402.rs/)
21+
2. [ThirdWeb](https://playground.thirdweb.com/payments/x402)
22+
3. Polygon Self-Hosted Facilitator (Contact for access)
23+
24+
The following guides will show how to use x402 on Polygon. The x402 community also has
25+
created [multiple examples](https://github.com/coinbase/x402/tree/main/examples/typescript)
26+
which can be easily adapted.
27+
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
# Quickstart for Buyers
2+
3+
This guide will walk you how to use x402 on Polygon
4+
to interact with services that require payment.
5+
6+
By the end of this guide, you will be able to programmatically discover
7+
payment requirements, complete a payment, and access a paid resource.
8+
9+
## Prerequisites
10+
Before you begin, ensure you have:
11+
12+
* Metamask, Rabby or any wallet that support Polygon with USDC
13+
14+
* [Node.js](https://nodejs.org/en) and npm
15+
16+
## 1. Install Dependencies
17+
18+
**HTTP Clients**
19+
20+
Install [x402-axios](https://www.npmjs.com/package/x402-axios) or [x402-fetch](https://www.npmjs.com/package/x402-fetch):
21+
22+
```bash
23+
npm install x402-axios
24+
# or
25+
npm install x402-fetch
26+
```
27+
28+
## 2. Create a Wallet Client
29+
30+
Create a wallet client using a tool like [viem](https://viem.sh/):
31+
32+
33+
```bash
34+
npm install viem
35+
```
36+
37+
Then, instantiate the wallet account:
38+
39+
```typescript
40+
import { createWalletClient, http } from "viem";
41+
import { privateKeyToAccount } from "viem/accounts";
42+
import { polygonAmoy } from "viem/chains";
43+
44+
// Create a wallet client (using your private key)
45+
const account = privateKeyToAccount("0xYourPrivateKey"); // we recommend using an environment variable for this
46+
```
47+
48+
## 3. Make Paid Requests Automatically
49+
50+
You can use either `x402-fetch` or `x402-axios` to automatically handle 402 Payment Required responses and complete payment flows.
51+
52+
!!! info x402-fetch
53+
**x402-fetch** extends the native `fetch` API to handle 402 responses and payment headers for you. [Full example from Coinbase here](https://github.com/coinbase/x402/tree/main/examples/typescript/clients/fetch)
54+
55+
```typescript
56+
import { wrapFetchWithPayment, decodeXPaymentResponse } from "x402-fetch";
57+
// other imports...
58+
59+
// wallet creation logic...
60+
61+
const fetchWithPayment = wrapFetchWithPayment(fetch, account);
62+
63+
fetchWithPayment(url, { //url should be something like https://api.example.com/paid-endpoint
64+
method: "GET",
65+
})
66+
.then(async response => {
67+
const body = await response.json();
68+
console.log(body);
69+
70+
const paymentResponse = decodeXPaymentResponse(response.headers.get("x-payment-response")!);
71+
console.log(paymentResponse);
72+
})
73+
.catch(error => {
74+
console.error(error.response?.data?.error);
75+
});
76+
```
77+
78+
## 4. Error Handling
79+
Clients will throw errors if:
80+
81+
* The request configuration is missing
82+
83+
* A payment has already been attempted for the request
84+
85+
* There is an error creating the payment header
86+
87+
## Summary
88+
* Install an x402 client package
89+
90+
* Create a wallet client
91+
92+
* Use the provided wrapper/interceptor to make paid API requests
93+
94+
* Payment flows are handled automatically for you
95+
96+
## References:
97+
98+
* [x402-fetch npm docs](https://www.npmjs.com/package/x402-fetch)
99+
100+
* [x402-axios npm docs](https://www.npmjs.com/package/x402-axios)
Lines changed: 171 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,171 @@
1+
# Quickstart for Sellers
2+
3+
This guide walks you through integrating with x402
4+
to enable payments for your API or service. By the end,
5+
your API will be able to charge buyers and AI agents for access.
6+
7+
## Prerequisites
8+
9+
Before you begin, ensure you have:
10+
11+
* A crypto wallet to receive funds (any EVM-compatible wallet)
12+
* [Node.js](https://nodejs.org/en) and npm (or Python and pip) installed
13+
* An existing API or server
14+
15+
**Note**\
16+
There are pre-configured examples available in the Coinbase repo for both
17+
[Node.js](https://github.com/coinbase/x402/tree/main/examples/typescript/servers). We also have an [advanced example](https://github.com/coinbase/x402/tree/main/examples/typescript/servers/advanced)
18+
that shows how to use the x402 SDKs to build a more complex payment flow.
19+
The following example shows how to adapt these for Polygon.
20+
21+
## 1. Install Dependencies
22+
23+
Install the [x402 Express middleware package](https://www.npmjs.com/package/x402-express).
24+
25+
```bash
26+
npm install x402-express
27+
npm install @coinbase/x402 # for the mainnet facilitator
28+
```
29+
30+
Install the [x402 Next.js middleware package](https://www.npmjs.com/package/x402-next).
31+
32+
```bash
33+
npm install x402-next
34+
```
35+
36+
Install the [x402 Hono middleware package](https://www.npmjs.com/package/x402-hono).
37+
38+
```bash
39+
npm install x402-hono
40+
```
41+
42+
This [community package](https://github.com/ethanniser/x402-mcp) showcases how you can use MCP (Model Context Protocol) with x402. We're working on enshrining an official MCP spec in x402 soon.
43+
44+
```bash
45+
npm install x402-mcp
46+
```
47+
48+
Full example in the repo [here](https://github.com/ethanniser/x402-mcp/tree/main/apps/example).
49+
50+
51+
### 2. Add Payment Middleware
52+
53+
Integrate the payment middleware into your application. You will need
54+
to provide:
55+
56+
* The Facilitator URL or facilitator object. For testing,
57+
use `https://x402.org/facilitator` which works on Base Sepolia.
58+
* For more information on running in production on mainnet, check
59+
out [CDP's Quickstart for Sellers](https://docs.cdp.coinbase.com/x402/docs/
60+
quickstart-sellers)
61+
* The routes you want to protect.
62+
* Your receiving wallet address.
63+
64+
65+
Full example in the repo [here](https://github.com/coinbase/x402/tree/main/examples/typescript/servers/express).
66+
Please adapt for Polygon.
67+
68+
69+
```javascript
70+
import express from "express";
71+
import { paymentMiddleware, Network } from "x402-express";
72+
73+
const app = express();
74+
75+
app.use(paymentMiddleware(
76+
"0xYourAddress", // your receiving wallet address
77+
{ // Route configurations for protected endpoints
78+
"GET /weather": {
79+
// USDC amount in dollars
80+
price: "$0.001",
81+
network: "polygon-amoy",
82+
},
83+
},
84+
{
85+
url: "https://facilitator.x402.rs/", // Facilitator URL for Polygon Amoy testnet.
86+
}
87+
));
88+
89+
// Implement your route
90+
app.get("/weather", (req, res) => {
91+
res.send({
92+
report: {
93+
weather: "sunny",
94+
temperature: 70,
95+
},
96+
});
97+
});
98+
99+
app.listen(4021, () => {
100+
console.log(`Server listening at http://localhost:4021`);
101+
});
102+
```
103+
104+
Full example in the repo [here](https://github.com/coinbase/x402/tree/main/examples/typescript/fullstack/next).
105+
Since this is a fullstack example, we recommend using the example to build
106+
this yourself, and treat the code snippet below as a reference to adapt for
107+
Polygon.
108+
109+
```javascript
110+
import { paymentMiddleware, Network } from 'x402-next';
111+
112+
// Configure the payment middleware
113+
export const middleware = paymentMiddleware(
114+
"0xYourAddress", // your receiving wallet address
115+
{ // Route configurations for protected endpoints
116+
'/protected': {
117+
price: '$0.01',
118+
network: "base-sepolia",
119+
config: {
120+
description: 'Access to protected content'
121+
}
122+
},
123+
}
124+
{
125+
url: "https://facilitator.x402.rs/", // Facilitator URL for Polygon testnet and mainnet
126+
}
127+
);
128+
129+
// Configure which paths the middleware should run on
130+
export const config = {
131+
matcher: [
132+
'/protected/:path*',
133+
]
134+
};
135+
```
136+
137+
Full example in the repo [here](https://github.com/coinbase/x402/tree/main/examples/typescript/servers/express).
138+
139+
```javascript
140+
import { Hono } from "hono";
141+
import { paymentMiddleware, Network } from "x402-hono";
142+
143+
const app = new Hono();
144+
145+
// Configure the payment middleware
146+
app.use(paymentMiddleware(
147+
"0xYourAddress",
148+
{
149+
"/protected-route": {
150+
price: "$0.01",
151+
network: "polygon-amoy",
152+
config: {
153+
description: "Access to premium content",
154+
}
155+
}
156+
},
157+
{
158+
url: 'https://facilitator.x402.rs' // 👈 Facilitator URL
159+
}
160+
));
161+
162+
// Implement your route
163+
app.get("/protected-route", (c) => {
164+
return c.json({ message: "This content is behind a paywall" });
165+
});
166+
167+
serve({
168+
fetch: app.fetch,
169+
port: 3000
170+
});
171+
```

mkdocs.yml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,10 @@ nav:
6767
- Stripe: pos/payments/onramps/onramps-stripe.md
6868
- Transfers:
6969
- USDC: pos/transfers/transfer-usdc.md
70+
- x402:
71+
- Overview: pos/payments/x402/overview.md
72+
- Quickstart for Buyers: pos/payments/x402/buyers.md
73+
- Quickstart for Sellers: pos/payments/x402/sellers.md
7074
- Node how-tos:
7175
- Prerequisites: pos/how-to/prerequisites.md
7276
- Sync node using snapshots: pos/how-to/snapshots.md

0 commit comments

Comments
 (0)