Add Checkout to Your LLM Agent in 10 Minutes

2026-08-18 · AgentPay VN

ai agentspython sdkvietqr paymentsmcp serverpayment integration

The Problem: Your AI Agent Can't Close the Sale

Imagine you've built a brilliant AI assistant—a course-selling chatbot, a café ordering agent, or a subscription management tool. Customers are engaged, asking questions, ready to buy. Then what? You hand them off to a payment gateway, they leave the conversation, friction explodes, and half your conversions vanish.

You need payments inside the agent conversation itself—instant, native, trustworthy. But integrating a payment system usually means weeks of security audits, bank compliance calls, and managing customer funds in escrow accounts. That's heavy infrastructure for a feature that should take hours, not months.

AgentPay VN solves this in a radically simpler way.

Why AgentPay VN Is Different

AgentPay VN is an open-source Python SDK (MIT license) + MCP server that lets AI agents create and collect VietQR payments in three lines of code. Here's the radical part: AgentPay never touches the money. The QR code points directly at your merchant bank account. When the customer pays, your bank confirms settlement instantly. You get the funds; we disappear.

This means:

Installing AgentPay VN in 60 Seconds

Open your terminal and run:

pip install agentpay-vn

That's it. You now have access to the full SDK. If you're using Claude or another agent via Model Context Protocol (MCP), also install the server:

pip install agentpay-mcp

Verify installation:

python -c "import agentpay_vn; print(agentpay_vn.__version__)"

Your First Payment Request: The Three-Line Flow

Here's what payment collection looks like in AgentPay:

from agentpay_vn import PaymentClient
import json

# Initialize the client (reads AGENTPAY_API_KEY from environment)
client = PaymentClient()

# Step 1: Create a payment request
payment = client.create_payment_request(
    amount=500000,  # VND (e.g., $20 USD)
    description="Premium Course Bundle",
    merchant_id="YOUR_MERCHANT_ID",
    order_id="order_12345"
)

print(f"Checkout URL: {payment.checkout_url}")
print(f"Payment ID: {payment.id}")

# Step 2: Send checkout_url to customer (in agent response)
agent_message = f"Click here to pay: {payment.checkout_url}"

# Step 3: Wait for settlement confirmation
settlement = client.await_settlement(
    payment_id=payment.id,
    timeout_seconds=300  # 5-minute timeout
)

if settlement.status == "CONFIRMED":
    print(f"✓ Payment confirmed! Amount: {settlement.amount} VND")
    print(f"Bank reference: {settlement.bank_ref}")
    # Your business logic here: grant access, create account, etc.
else:
    print(f"Payment status: {settlement.status}")

Line-by-Line Breakdown

Line 1-2: Import & initialize
The PaymentClient reads your API key from the AGENTPAY_API_KEY environment variable (set this in your .env file or deployment config).

Lines 5-12: Create payment request
You pass the amount in VND, a description, your merchant ID, and an order ID to track it. AgentPay returns a payment object with a QR-ready checkout_url.

Lines 14-15: Deliver to customer
Your agent sends this URL to the user. They scan the QR or click the link. Payment happens at their bank—not your infrastructure.

Lines 17-24: Await confirmation
This is non-blocking (you can async/await it in production). Your bank sends a webhook confirming settlement; AgentPay polls that confirmation and returns it when ready.

Integrating with Claude via MCP

If you're using Claude as your LLM agent, you can expose AgentPay as a tool via the Model Context Protocol.

Step 1: Configure MCP Server

Create a file .mcp_servers.json in your project:

{
  "agentpay": {
    "command": "python",
    "args": ["-m", "agentpay_mcp"],
    "env": {
      "AGENTPAY_API_KEY": "your_api_key_here",
      "AGENTPAY_MERCHANT_ID": "your_merchant_id"
    }
  }
}

Step 2: Use in Claude

When you instantiate the Claude client, pass this config:

from anthropic import Anthropic

client = Anthropic()
response = client.messages.create(
    model="claude-3-5-sonnet-20241022",
    max_tokens=1024,
    tools=[{
        "type": "mcp",
        "mcp_server_name": "agentpay"
    }],
    messages=[{
        "role": "user",
        "content": "I want to sell a course for 299,000 VND. Help me create a payment link."
    }]
)

Claude now has access to create_payment_request and await_settlement as native tools. It can call them directly without you writing custom wrappers.

Real-World Example: Course-Selling Bot

Let's build a complete example: an AI agent that sells online courses.

from agentpay_vn import PaymentClient
from anthropic import Anthropic
import os
import json

API_KEY = os.getenv("AGENTPAY_API_KEY")
MERCHANT_ID = os.getenv("AGENTPAY_MERCHANT_ID")

payment_client = PaymentClient(api_key=API_KEY)
llm_client = Anthropic()

courses = {
    "python-basics": {"name": "Python Basics", "price": 299000},
    "web-dev": {"name": "Web Development", "price": 599000},
    "ai-agents": {"name": "AI Agent Architecture", "price": 899000}
}

def handle_purchase(course_key: str) -> str:
    """User wants to buy a course. Create payment request."""
    course = courses.get(course_key)
    if not course:
        return f"Course '{course_key}' not found."

    payment = payment_client.create_payment_request(
        amount=course["price"],
        description=f"AgentPay VN Course: {course['name']}",
        merchant_id=MERCHANT_ID,
        order_id=f"course_{course_key}_{int(time.time())}"
    )

    return f"""Great choice! You're purchasing **{course['name']}** for {course['price']:,} VND.

Click here to pay: {payment.checkout_url}

After payment, you'll get instant access to all course materials."""

def main():
    conversation_history = []

    system_prompt = f"""You are a friendly course sales assistant. Help users:
1. Browse courses: Python Basics (299k VND), Web Dev (599k VND), AI Agents (899k VND)
2. Answer questions about course content
3. When they're ready, call handle_purchase(course_key) to create a payment link

Be conversational and helpful. Available courses: {json.dumps(courses, ensure_ascii=False)}"""

    print("🎓 Welcome to AgentPay Course Academy!")
    print("Ask me about courses or type 'quit' to exit.\n")

    while True:
        user_input = input("You: ").strip()
        if user_input.lower() == "quit":
            break

        conversation_history.append({
            "role": "user",
            "content": user_input
        })

        response = llm_client.messages.create(
            model="claude-3-5-sonnet-20241022",
            max_tokens=500,
            system=system_prompt,
            messages=conversation_history
        )

        assistant_message = response.content[0].text
        conversation_history.append({
            "role": "assistant",
            "content": assistant_message
        })

        print(f"\nAssistant: {assistant_message}\n")

if __name__ == "__main__":
    main()

This bot talks naturally with customers, describes courses, and generates secure payment links on demand. No payment infrastructure complexity—just pure conversation.

Do's & Don'ts

Do Don't
✓ Set AGENTPAY_API_KEY in production via secure secrets manager (AWS Secrets, Vercel Env, etc.) ✗ Hardcode API keys in source code or .env files in version control
✓ Use order IDs that are unique per request (timestamp, UUID, etc.) ✗ Reuse the same order ID—payment system will reject duplicates
✓ Handle await_settlement timeouts gracefully; tell user to try again ✗ Assume settlement will always succeed—confirm payment status in DB
✓ Test with small amounts first (10k VND = ~$0.40) ✗ Jump to large payments without testing
✓ Log payment IDs and bank references for reconciliation ✗ Ignore settlement data—you need it for accounting

Advanced: Async Settlement Polling

In production, don't block on await_settlement(). Use webhooks or background tasks:

import asyncio
from agentpay_vn import PaymentClient

async def check_payment_status(payment_id: str, callback):
    """Check payment status every 5 seconds (e.g., in background task)."""
    client = PaymentClient()

    for attempt in range(60):  # 5 minutes max
        try:
            settlement = await client.check_settlement(payment_id)
            if settlement.status == "CONFIRMED":
                callback(settlement)
                return
        except Exception as e:
            print(f"Status check failed: {e}")

        await asyncio.sleep(5)

    callback(None)  # Timeout

# Usage in FastAPI or async framework
@app.post("/checkout")
async def create_checkout(amount: int):
    payment = client.create_payment_request(
        amount=amount,
        merchant_id=MERCHANT_ID,
        order_id=generate_order_id()
    )

    # Fire background task (don't block)
    asyncio.create_task(check_payment_status(payment.id, on_payment_confirmed))

    return {"checkout_url": payment.checkout_url, "payment_id": payment.id}

def on_payment_confirmed(settlement):
    if settlement:
        print(f"✓ Payment confirmed: {settlement.bank_ref}")
        # Grant access, send email, update DB
    else:
        print("Payment timeout")

FAQ

Q: Does AgentPay hold my customer's money?
No. The QR code directs payment straight to your merchant bank account. AgentPay only confirms settlement via your bank's API—we never touch the funds.

Q: Can I use this with non-Vietnamese banks?
Currently, AgentPay VN is optimized for Vietnamese VietQR (Ngân hàng Nhà nước integration). International support is on the roadmap.

Q: What if a customer scans the QR but doesn't complete payment?
The await_settlement() call will timeout after the specified period. You can then prompt the user to try again, or offer alternative payment methods.

Q: How do I test before going live?
Use our sandbox environment. Set AGENTPAY_ENV=sandbox in your config. Sandbox payments confirm instantly without hitting real banks—perfect for testing bot flows.

Key Takeaways

Get Started Now

You've got everything you need to add checkout to your AI agent in under 10 minutes:

  1. Install: pip install agentpay-vn
  2. Set credentials: Export AGENTPAY_API_KEY and AGENTPAY_MERCHANT_ID
  3. Copy the three-line example above and adapt it to your bot
  4. Test: Start with sandbox mode and small amounts
  5. Deploy: Your agent can now collect payments natively

Resources: - 📖 Full Docs: https://agentpay.servicesai.vn/v1/docs - 🔗 GitHub: https://github.com/phuocdu/agentpay-vn - 💬 Questions? Open an issue on GitHub or ping us on the docs site

Your AI agent is ready to make money. Let's build.

Get started →

← All posts