Skip to main content

Whop x402 Payment Gateway Adapter for AI Agents

Project description

whop-x402

An open-source, framework-agnostic x402-compatible adapter that allows Python-based AI agents to accept payments via Whop (subscriptions, memberships, digital goods) and automatically route native revenue into BNB Chain PancakeSwap on-chain buybacks.

Features

  • x402 protocol support: Emits challenge payloads compatible with the x402 agent-to-agent protocol.
  • On-chain routing: Executes native BNB swaps for utility tokens on PancakeSwap V2 (BSC).
  • Price Oracle: Automatic CoinGecko USD-to-BNB price tracking.
  • Webhook validation: Secure HMAC-SHA256 signature verification of Whop payments.
  • Event hooks: Typed async callbacks for custom triggers.

Installation

pip install whop-x402

Quick Start (FastAPI Webhook Example)

Here is how to set up the adapter with a FastAPI server to monetize your AI agent:

import os
from fastapi import FastAPI, Request, HTTPException
from whop_x402 import WhopX402Adapter, WhopConfig, ChainConfig

app = FastAPI()

# 1. Initialize Adapter
whop_config = WhopConfig(
    apiKey=os.getenv("WHOP_API_KEY"),
    webhookSecret=os.getenv("WHOP_WEBHOOK_SECRET")
)

chain_config = ChainConfig(
    rpcUrl=os.getenv("BSC_RPC_URL", "https://bsc-dataseed.binance.org/"),
    chainId=56, # 56 for Mainnet, 97 for Testnet
    walletPrivateKey=os.getenv("WALLET_PRIVATE_KEY"),
    tokenAddress=os.getenv("BUYBACK_TOKEN_ADDRESS"), # Target agent utility token
    buybackPercentage=100.0, # Swap 100% of revenue to token
    slippagePercentage=0.5
)

adapter = WhopX402Adapter(whop_config, chain_config)

# 2. Register Event Hooks
@adapter.on("payment_received")
async def on_payment(event):
    print(f"💰 Payment of {event.amountCents} cents received from {event.payer}")

@adapter.on("buyback_executed")
async def on_buyback(event):
    print(f"🔄 Buyback Executed: Swapped {event.amountBNB} BNB. Tx Hash: {event.txHash}")

@adapter.on("buyback_failed")
async def on_failed(event):
    print(f"❌ Buyback Failed: {event.error}")

# 3. Define Webhook Ingestion Route
@app.post("/whop-webhook")
async def whop_webhook(request: Request):
    # Fetch raw body for signature verification
    body = await request.body()
    signature = request.headers.get("X-Whop-Signature")
    
    if not signature:
        raise HTTPException(status_code=400, detail="Missing X-Whop-Signature header")

    result = await adapter.handle_payment_webhook(body.decode('utf-8'), signature)
    
    if not result["success"]:
        raise HTTPException(status_code=400, detail=result.get("error"))
        
    return {"status": "ok", "txHash": result.get("txHash")}

Fetch.ai & Agentverse (ASI:One Chat Protocol)

examples/agentverse_chat_agent.py is a complete, production-grade uAgent that is discoverable on ASI:One / Agentverse. It runs two components in one process:

  1. A uAgent using the official ASI:One Chat Protocol (uagents_core.contrib.protocols.chat). When a user asks for premium access, it returns a Whop checkout link (the x402 payment challenge); ask it for "proof" to get the latest on-chain buyback tx hash.
  2. A FastAPI webhook server (/status, /whop-webhook) that HMAC-verifies incoming Whop payment.succeeded events and triggers the PancakeSwap buyback.
pip install uagents==0.23.6 uagents-core==0.4.0 fastapi uvicorn python-dotenv whop-x402
python3 examples/agentverse_chat_agent.py

Enable the mailbox (already set with mailbox=True), then register the agent on Agentverse and expose the webhook publicly (e.g. cloudflared tunnel --url http://localhost:8080) as your Whop webhook destination. See the ASI:One chat protocol guide.

License

MIT License.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

whop_x402-1.0.0.tar.gz (14.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

whop_x402-1.0.0-py3-none-any.whl (14.0 kB view details)

Uploaded Python 3

File details

Details for the file whop_x402-1.0.0.tar.gz.

File metadata

  • Download URL: whop_x402-1.0.0.tar.gz
  • Upload date:
  • Size: 14.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.5

File hashes

Hashes for whop_x402-1.0.0.tar.gz
Algorithm Hash digest
SHA256 acd28e6a68d2c274e67e2e29ae637af1706b2fc422a5d136b2fdab7046d96d0f
MD5 fd916f08167a20a46441bab32f631da9
BLAKE2b-256 3be947905acc27441fd9035454c10a45cd997749b49ae30a39c2f194905d5883

See more details on using hashes here.

File details

Details for the file whop_x402-1.0.0-py3-none-any.whl.

File metadata

  • Download URL: whop_x402-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 14.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.5

File hashes

Hashes for whop_x402-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 7af2a0f2fd91c1075f280dfd4f365cb5966a0db883993b96df59815e60b7a10e
MD5 471becabb7c71d2168573afff42bb897
BLAKE2b-256 cf1e09abd4dec970c9cacf6c05f03c63f147c9b554be1739e0fe4b1be9f2fc86

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page