Skip to main content
CREWAI INTEGRATION

CrewAI payment integration.

Add USDC payments to any CrewAI crew. One tool, one billing agent, one line of orchestration.

SHORT ANSWER

Blockchain0x provides a drop-in PaymentRequestTool for CrewAI agents. Install blockchain0x-crewai, instantiate the tool, assign it to a dedicated billing agent in your crew, and chain a research task that depends on the bill task. The crew handles payment requests and work delivery as separate roles, with USDC settling on Base.

WHY A DEDICATED BILLING ROLE

CrewAI's strength is role separation. Use it for billing too.

Other frameworks put every tool on a single agent. CrewAI's design encourages role separation: a researcher does research, a writer writes, a reviewer reviews. The clean way to integrate payments is to follow that pattern - a dedicated billing role with the payment tool, executing before the work agents. The work agents focus on their core job; the billing agent focuses on commerce.

This shape also makes audit trails clearer. When a payment goes through, you know which agent requested it (the biller) and which work agents the payment unlocked (the downstream tasks). Single-agent integrations conflate the two and make per-flow billing analytics harder.

INSTALLATION

One pip install. Three environment variables.

The package targets Python 3.10+ (CrewAI's minimum) and works with both poetry and pip. No additional dependencies beyond what CrewAI already requires.

INSTALL
pip install blockchain0x-crewai
ENVIRONMENT VARIABLES
export BLOCKCHAIN0X_API_KEY=sk_live_...
export BLOCKCHAIN0X_AGENT_ID=agt_abc123
export BLOCKCHAIN0X_SIGNING_SECRET=whsec_...

BLOCKCHAIN0X_API_KEY and BLOCKCHAIN0X_AGENT_ID come from the agent's settings page after you create the agent. BLOCKCHAIN0X_SIGNING_SECRET is the per-agent webhook signing secret; you only need it if your webhook handler runs in the same Python process.

FULL CREW EXAMPLE

A working two-agent crew with billing + research roles.

Below is a complete CrewAI crew where a billing agent requests USDC payment first, and a researcher agent produces the analysis only after payment confirms. This is the canonical pattern for paid CrewAI work.

CREW.PY
from crewai import Agent, Task, Crew
from blockchain0x.crewai import PaymentRequestTool

# Tool that any crew member can call to request a USDC payment
payment_tool = PaymentRequestTool()

# Researcher (does the work)
researcher = Agent(
    role="Senior Market Analyst",
    goal="Produce a thorough Q4 LLM market analysis",
    backstory="A specialist analyst with 10 years in tech-market research.",
    tools=[],
    allow_delegation=False,
)

# Billing agent (handles payment requests)
biller = Agent(
    role="Billing Coordinator",
    goal="Request USDC payment from the client before research begins",
    backstory="Handles all client billing for the research crew.",
    tools=[payment_tool],
    allow_delegation=False,
)

bill_task = Task(
    description={t("Request $5 USDC payment from the client for the market analysis.")},
    expected_output="A hosted payment URL for the client to follow.",
    agent=biller,
)

research_task = Task(
    description={t("Once payment confirms, produce the Q4 LLM market analysis.")},
    expected_output="A 1,500-word market analysis PDF.",
    agent=researcher,
    context=[bill_task],
)

crew = Crew(agents=[biller, researcher], tasks=[bill_task, research_task])
result = crew.kickoff()

When you call crew.kickoff(), the bill_task runs first: the billing agent calls PaymentRequestTool, which creates a hosted_url. The hosted URL is the bill_task's output. The research_task is next in the sequence but should not run until payment confirms - the standard pattern is to surface the hosted_url to the user, end the kickoff() call there, and start a separate research-only crew when the payment.confirmed webhook fires.

WEBHOOK HANDLING

Triggering the research crew when payment lands.

Your webhook URL receives a signed POST when the chain confirms the payment. The handler verifies the signature, then triggers whatever crew or task should now run. Flask example below; same pattern in FastAPI or any Python web framework.

WEBHOOK_HANDLER.PY
from flask import Flask, request, abort
from blockchain0x.crewai import verify_webhook
import os

app = Flask(__name__)
SIGNING_SECRET = os.environ["BLOCKCHAIN0X_SIGNING_SECRET"]

@app.post("/webhooks/payment")
def receive():
    signature = request.headers.get("X-Blockchain0x-Signature", "")
    if not verify_webhook(request.get_data(), signature, SIGNING_SECRET):
        abort(401)
    event = request.get_json()
    if event["type"] == "payment.confirmed":
        # Kick off the research crew, or release a pending task
        run_research_for(event["data"]["payment_request_id"])
    return "ok", 200

The verify_webhook helper does HMAC-SHA256 in constant time. Read the raw body (request.get_data()), not request.get_json() then re-serializing, because parsing then re-serializing breaks the signature. The recommended architecture is to have the webhook handler enqueue a job (Redis, Celery, RQ) that triggers the actual CrewAI run; running crew.kickoff() inside the webhook handler can take minutes and times out HTTP requests.

STARTER REPOSITORY

Working example with classic Crew + CrewAI Flow patterns.

A complete CrewAI repository at the GitHub link below. Includes the two-agent example above, a CrewAI Flow variant (newer graph-based execution), the webhook handler with Redis queue, and Docker Compose to run all three services together.

github.com/blockchain0x/agent-wallet-crewai

The repository structure: crew.py (the work agents), webhook.py (Flask handler), redis-config.yml (queue), docker-compose.yml (full local stack), README walking through the full lifecycle from kickoff to payment confirmation to research delivery.

COMMON PITFALLS

Five things to watch when wiring billing into a crew.

CrewAI's role-based design is what makes payment integration cleaner than other frameworks. It also has its own footguns. Knowing these in advance saves time.

PITFALL 1

Putting the payment tool on the wrong agent

CrewAI agents have roles; assigning the payment tool to the researcher (who should be doing research, not billing) confuses the LLM and leads to the researcher trying to charge the client mid-analysis. The clean pattern: a dedicated billing agent with the payment tool, executed before the work-doing agents. The example above follows this shape; copy it.

PITFALL 2

Sequential vs hierarchical processes

CrewAI supports sequential (default) and hierarchical execution. With hierarchical, a manager agent orchestrates the crew. If your manager is allowed to delegate the payment tool, it can do so to any subordinate, which usually breaks the billing flow. Either keep the payment tool on a single dedicated agent and use sequential, or carefully restrict the manager's delegation rules.

PITFALL 3

Task context coupling

If the research task lists the bill task in its context (correct, so the researcher sees the payment was requested), but the LLM tries to read the payment status from that context (incorrect, since payment confirms asynchronously via webhook), you get confused output. The fix: research task should wait on a webhook-triggered signal, not on bill-task context. Reference the starter repo for the right pattern using CrewAI's built-in task callbacks.

PITFALL 4

Floating-point amounts

Same pitfall as every other framework: pass amounts as decimal strings ("5.00") not floats. CrewAI passes tool inputs as-is to the underlying tool function, so a Python float will arrive as a float. The SDK validates and raises before HTTPing, but the error message looks like a CrewAI tool error rather than a payment error, which confuses first integrators.

PITFALL 5

Webhook handler outside the crew process

Your webhook handler is typically a separate Flask/FastAPI process, not part of the crew's runtime. The crew finishes its kickoff() and returns; the webhook arrives minutes later when payment confirms. You need a way to bridge the two - the recommended pattern is a Redis queue or a database row that the webhook updates and the crew (in its next run) reads. Do not try to keep the crew alive waiting for the webhook; CrewAI runs are short-lived by design.

FREQUENTLY ASKED

Three CrewAI-specific questions.

Does this work with CrewAI Flows (the newer graph-based execution)?

Yes. PaymentRequestTool is a standard CrewAI tool (inheriting from BaseTool), so it works equally well in classic Crew + Task structures and in CrewAI Flow's @start/@listen patterns. In Flow specifically, the recommended pattern is to put the payment request in a dedicated step before the work steps; the work steps listen on a Flow event that fires when the webhook handler updates the shared state. The starter repo includes both a classic and a Flow example.

Can the same Crew handle multiple paid sessions concurrently?

Yes, with the standard idempotency-key pattern. Each kickoff() invocation should pass a unique Idempotency-Key in the PaymentRequestTool's request (the tool accepts it as a constructor arg or a per-call kwarg). Without this, two concurrent kickoffs to the same crew with the same prompt could collide on identical request bodies. Pass a UUID generated at the start of each session and the API deduplicates correctly.

How do I refund a CrewAI client mid-execution if something goes wrong?

The PaymentRequestTool also exposes a refund_payment() helper that takes a payment_request_id and a reason. Call it from a CrewAI task whose agent has the tool. The refund sends USDC back to the original payer address from your agent's connected wallet (so your wallet needs the USDC balance to refund from); the refund is logged in the audit log with the reason. Best practice: have a dedicated 'refund agent' role for this so refund logic does not get tangled with billing logic.

Add a billing role to your crew.

Five minutes from pip install to your first paid crew kickoff. Pro at $9/agent/month.