// Usage in Express middleware
import express from "express";
import { settlePayment, facilitator } from "thirdweb/x402";
import { createThirdwebClient } from "thirdweb";
import { arbitrumSepolia } from "thirdweb/chains";
const client = createThirdwebClient({
secretKey: process.env.THIRDWEB_SECRET_KEY,
});
const thirdwebFacilitator = facilitator({
client,
serverWalletAddress: "0x1234567890123456789012345678901234567890",
});
const app = express();
async function paymentMiddleware(req, res, next) {
// verify and process the payment
const result = await settlePayment({
resourceUrl: `${req.protocol}://${req.get("host")}${req.originalUrl}`,
method: req.method,
paymentData: req.headers["x-payment"],
payTo: "0x1234567890123456789012345678901234567890",
network: arbitrumSepolia, // or any other chain
price: "$0.05",
waitUntil: "submitted",
facilitator: thirdwebFacilitator,
});
if (result.status === 200) {
// Set payment receipt headers and continue
Object.entries(result.responseHeaders).forEach(([key, value]) => {
res.setHeader(key, value);
});
next();
} else {
// Return payment required response
res
.status(result.status)
.set(result.responseHeaders)
.json(result.responseBody);
}
}
app.get("/api/premium", paymentMiddleware, (req, res) => {
res.json({ message: "This is premium content!" });
});