@okxweb3/x402-hono
v0.1.0
Published
x402 Payment Protocol
Downloads
136
Keywords
Readme
@okxweb3/x402-hono
Hono middleware for the x402 Payment Protocol. Adds x402 payment requirements to Hono applications.
Installation
npm install @okxweb3/x402-honoQuick Start
import { Hono } from "hono";
import { serve } from "@hono/node-server";
import { paymentMiddleware, x402ResourceServer } from "@okxweb3/x402-hono";
import { ExactEvmScheme } from "@okxweb3/x402-evm/exact/server";
import { OKXFacilitatorClient } from "@okxweb3/x402-core/server";
const app = new Hono();
const facilitatorClient = new OKXFacilitatorClient();
const resourceServer = new x402ResourceServer(facilitatorClient)
.register("eip155:196", new ExactEvmScheme());
app.use(
paymentMiddleware(
{
"GET /protected-route": {
accepts: {
scheme: "exact",
price: "$0.10",
network: "eip155:196",
payTo: "0xYourAddress",
},
description: "Access to premium content",
},
},
resourceServer,
),
);
app.get("/protected-route", (c) => {
return c.json({ message: "Premium content" });
});
serve({ fetch: app.fetch, port: 3000 });API Reference
paymentMiddleware
function paymentMiddleware(
routes: RoutesConfig,
server: x402ResourceServer,
syncFacilitatorOnStart?: boolean,
): MiddlewareHandler;Creates Hono middleware that:
- Checks if the incoming request matches a protected route
- Validates payment headers if required
- Returns payment instructions (402 status) if payment is missing or invalid
- Processes the request if payment is valid
- Handles settlement after successful response
Parameters
| Parameter | Required | Description |
|-----------|----------|-------------|
| routes | Yes | Route configurations for protected endpoints |
| server | Yes | Pre-configured x402ResourceServer instance |
| syncFacilitatorOnStart | No | Whether to sync with facilitator on startup (default: true) |
Route Configuration
const routes: RoutesConfig = {
"GET /api/protected": {
accepts: {
scheme: "exact",
price: "$0.10",
network: "eip155:196",
payTo: "0xYourAddress",
maxTimeoutSeconds: 60,
},
description: "Premium API access",
},
};
app.use(paymentMiddleware(routes, resourceServer));Multiple Protected Routes
app.use(
paymentMiddleware(
{
"GET /api/premium/*": {
accepts: {
scheme: "exact",
price: "$1.00",
network: "eip155:196",
payTo: "0xYourAddress",
},
description: "Premium API access",
},
"GET /api/data": {
accepts: {
scheme: "exact",
price: "$0.50",
network: "eip155:196",
payTo: "0xYourAddress",
maxTimeoutSeconds: 120,
},
description: "Data endpoint access",
},
},
resourceServer,
),
);