Quickstart

Integrate via SDK#

Call the Onchain OS Payment SDK directly. The SDK has the 402 protocol response handling and on-chain transaction verification built in — no custom API implementation required.


Prerequisites#


Install the SDK#

bash
npm install express @okxweb3/x402-express @okxweb3/x402-core @okxweb3/x402-evm
npm install -D typescript tsx @types/express @types/node

Integrate the service#

typescript
import express from "express";
import {
  paymentMiddleware,
  x402ResourceServer,
} from "@okxweb3/x402-express";
import { ExactEvmScheme } from "@okxweb3/x402-evm/exact/server";
import { OKXFacilitatorClient } from "@okxweb3/x402-core";

const app = express();
const NETWORK = "eip155:196";
const PAY_TO = process.env.PAY_TO_ADDRESS || "0xYourWalletAddress";

const facilitatorClient = new OKXFacilitatorClient({
  apiKey: "OKX_API_KEY",
  secretKey: "OKX_SECRET_KEY",
  passphrase: "OKX_PASSPHRASE",
});

const resourceServer = new x402ResourceServer(facilitatorClient);
resourceServer.register(NETWORK, new ExactEvmScheme());

app.use(
  paymentMiddleware(
    {
      "GET /generateImg": {
        accepts: [{
          scheme: "exact",
          network: NETWORK,
          payTo: PAY_TO,
          price: "$0.01",
        }],
        description: "AI Image Generation Service",
        mimeType: "application/json",
      },
    },
    resourceServer,
  ),
);

app.get("/generateImg", (_req, res) => {
  res.json({
    success: true,
    imageUrl: "https://placehold.co/512x512/png?text=AI+Generated",
    prompt: "a sunset over mountains",
    timestamp: new Date().toISOString(),
  });
});

app.listen(4000, () => {
  console.log("[Seller] Image generation service listening at http://localhost:4000");
});

Test the service#

  1. 1
    Hit the service port via Onchain OS
  2. 2
    Server returns HTTP 402 with the PAYMENT-REQUIRED header
  3. 3
    Use Agentic Wallet to complete payment
  4. 4
    Wallet auto-retries the request
  5. 5
    Server verifies the payment with the Broker and returns the resource