Add a Checkout Tool to Your LLM Agent in 10 Minutes

2026-07-21 · AgentPay VN

ai-agentsvietqr-paymentspython-sdkmcp-serverllm-integration

The Problem: Your AI Agent Can Talk, But Can't Collect Money

Imagine this: You've built a smart chatbot that helps customers buy your online courses. It answers questions, builds trust, and guides prospects toward purchase. Then comes the critical moment—the customer says "I'm ready to pay." And your bot... goes silent. It can't process payments. It can't generate a checkout link. It can't confirm settlement. You've just lost a sale because your AI agent lacks a crucial nervous system: the ability to actually collect money.

This is a real pain point for founders building AI-powered businesses. Payment integration has traditionally required:

But if you're in Vietnam—or serving Vietnamese customers—there's a dramatically simpler path: VietQR. And AgentPay VN makes it trivial to wire this into your LLM agent.

Why VietQR + AgentPay VN Changes the Game

VietQR is Vietnam's nationwide open QR standard backed by the State Bank. It's ubiquitous—every Vietnamese phone has a banking app that scans QR codes. Your customers already know how to use it.

AgentPay VN is an open-source Python SDK + MCP server that lets your AI agent:

  1. Create payment requests in one line
  2. Generate a checkout QR code instantly
  3. Wait for settlement confirmation directly from your bank feed
  4. Never touch the money—it flows straight to your account

No Stripe middleman. No payment gateway delays. No holding balances. Just: customer scans QR → money hits your bank → your agent confirms → conversation continues.

The best part? You can wire this up in under 10 minutes.

What You Need Before Starting

To complete this tutorial, you'll need:

That's it. No complex onboarding. No approval process.

Step 1: Install AgentPay VN (1 minute)

Open your terminal and run:

pip install agentpay-vn

Verify the install:

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

You should see a version number. You're live.

Step 2: Create Your First Payment Request (3 minutes)

Here's the core workflow in 12 lines of Python:

from agentpay_vn import PaymentClient, PaymentRequest

# Initialize the payment client with your bank details
client = PaymentClient(
    account_number="0123456789",  # Your Vietnamese bank account
    account_name="Phuoc's Online Course",  # Display name
    bank_code="970436",  # Techcombank's code (see docs for others)
    api_key="your-agentpay-api-key"  # Get from https://agentpay.servicesai.vn/v1/docs
)

# Create a payment request
payment = client.create_payment_request(
    amount_vnd=500000,  # 500,000 VND (roughly $20)
    description="Advanced Python Course - Module 3",
    customer_id="user_12345",  # Tie it to your customer
    order_id="order_abc123"  # Your internal order reference
)

# Get the checkout URL (send this to your customer)
checkout_url = payment.checkout_url
print(f"Share this link: {checkout_url}")
print(f"Or scan the QR code at: {payment.qr_code_url}")

Line-by-line breakdown:

That's the create phase. Now for the await phase.

Step 3: Listen for Settlement Confirmation (2 minutes)

Once your customer pays, you need to know when the money hits your account. AgentPay VN taps into your bank's feed:

import asyncio
from agentpay_vn import await_settlement

async def wait_for_payment(order_id, timeout_seconds=120):
    """
    Block until the bank confirms the payment landed.
    Times out after 2 minutes if no settlement is detected.
    """
    try:
        settlement = await await_settlement(
            order_id=order_id,
            timeout=timeout_seconds,
            client=client
        )
        print(f"✓ Payment confirmed! Transaction ID: {settlement.transaction_id}")
        print(f"  Amount: {settlement.amount_vnd} VND")
        print(f"  Timestamp: {settlement.settled_at}")
        return settlement
    except TimeoutError:
        print("✗ No payment received within 2 minutes.")
        return None

# In your agent's conversation loop:
settlement = asyncio.run(wait_for_payment("order_abc123"))
if settlement:
    # Unlock the course, send the download link, etc.
    print("Granting access to the course...")
else:
    # Remind customer to pay
    print("Still waiting for payment. Did you complete the transfer?")

What's happening:

This is the settlement phase—the money is actually in your account when this returns.

Step 4: Wire It Into Your LLM Agent via MCP (4 minutes)

If you're using Claude or another MCP-compatible LLM, you can expose these payment tools as native agent actions. Install the MCP server:

pip install agentpay-mcp

Add this to your Claude config (e.g., ~/.claude/mcp-settings.json):

{
  "mcpServers": {
    "agentpay": {
      "command": "agentpay-mcp",
      "args": [
        "--account-number", "0123456789",
        "--account-name", "Phuoc's Online Course",
        "--bank-code", "970436",
        "--api-key", "your-agentpay-api-key"
      ]
    }
  }
}

Now your LLM agent has three native tools:

  1. create_payment_request – Create a new payment
  2. send_checkout_url – Generate and format the checkout link
  3. await_settlement – Poll for payment confirmation

Your agent can call these autonomously mid-conversation. Here's what a conversation might look like:

User: "I want to buy your Advanced Python course."

Agent (internal): Calls `create_payment_request(amount_vnd=500000, description="Advanced Python Course")

Agent (to user): "Great! That's 500,000 VND. [Generates QR] Scan this with your banking app to pay."

User: Scans QR, pays from their bank

Agent (internal): Calls await_settlement(order_id=...) and waits up to 120 seconds

Agent (to user): "✓ Payment confirmed! Your course access link is [download]. Enjoy!"

All of this happens in one conversation thread. No page reloads. No redirects. Seamless.

Real-World Walkthrough: A Café Bot That Takes Orders & Payments

Let's say you run an espresso subscription service and want to automate orders via WhatsApp (using an LLM agent).

from agentpay_vn import PaymentClient
import asyncio

class CafeBot:
    def __init__(self):
        self.payment_client = PaymentClient(
            account_number="0987654321",
            account_name="Phuoc's Espresso Co.",
            bank_code="970436",
            api_key="sk_live_..."
        )
        self.menu = {
            "espresso_monthly": {"price": 300000, "name": "Monthly Espresso Box"},
            "cold_brew_pack": {"price": 250000, "name": "Cold Brew 6-Pack"}
        }

    async def process_order(self, customer_name, product_key):
        """
        Customer says: 'I want the monthly espresso box.'
        Bot handles everything: payment → confirmation → fulfillment.
        """
        product = self.menu.get(product_key)
        if not product:
            return "Sorry, we don't have that item."

        # Step 1: Create payment request
        payment = self.payment_client.create_payment_request(
            amount_vnd=product["price"],
            description=f"{product['name']} for {customer_name}",
            customer_id=customer_name,
            order_id=f"{customer_name}_{product_key}_{int(time.time())}"
        )

        # Step 2: Send checkout link
        checkout_msg = f"""
        Great choice! {product['name']} costs {product['price']:,} VND.

        Pay here: {payment.checkout_url}
        Or scan: {payment.qr_code_url}

        Waiting for your payment...
        """

        # Step 3: Wait for settlement
        settlement = await self.payment_client.await_settlement(
            order_id=payment.order_id,
            timeout=300  # 5-minute timeout
        )

        if settlement:
            return f"""
            ✓ Payment received! Your {product['name']} ships tomorrow.
            Tracking: [link]
            Questions? Reply to this chat.
            """
        else:
            return "Payment timeout. Please try again or contact support."

# Usage:
bot = CafeBot()
response = asyncio.run(bot.process_order("Alice", "espresso_monthly"))
print(response)

This bot can handle 100+ concurrent orders. Each customer gets a unique QR code. Money flows straight to your bank. No middleman.

Do's and Don'ts: Best Practices

Do Don't
Store order_id and link it to your customer DB Reuse the same payment request for multiple customers
Set reasonable timeouts (120–300 seconds) based on your UX Assume settlement is instant; always await confirmation
Log settlement transactions for accounting Hardcode bank details; use environment variables (os.getenv())
Test with small amounts (10,000 VND) first Expose your API key in GitHub or client-side code
Use customer_id to track repeat buyers Ignore failed settlement callbacks

Advanced Tips

Tip 1: Batch Payments & Reconciliation

If you're processing high volume, track payments in a database:

import sqlite3

def log_payment(order_id, amount_vnd, status):
    conn = sqlite3.connect("payments.db")
    c = conn.cursor()
    c.execute("INSERT INTO orders (order_id, amount_vnd, status, timestamp) VALUES (?, ?, ?, datetime('now'))",
              (order_id, amount_vnd, status))
    conn.commit()
    conn.close()

# After settlement:
log_payment(settlement.order_id, settlement.amount_vnd, "settled")

At end-of-day, sum your settled orders and cross-check your bank statement. AgentPay VN provides the bank transaction ID, so reconciliation is trivial.

Tip 2: Dynamic Pricing Based on Agent Logic

Your agent can calculate prices on-the-fly:

def calculate_price(customer_tier, product):
    """
    Platinum customers get 10% off.
    """
    base_price = product["price"]
    if customer_tier == "platinum":
        return int(base_price * 0.9)
    return base_price

price = calculate_price(user_tier, menu["espresso_monthly"])
payment = client.create_payment_request(amount_vnd=price, ...)

The agent can even negotiate or offer discounts mid-conversation, and the payment amount updates in real-time.

Tip 3: Webhook Integration for Real-Time Notifications

Instead of polling with await_settlement(), set up a webhook:

# On your server, expose an endpoint:
@app.post("/webhook/settlement")
async def handle_settlement(payload: dict):
    """
    AgentPay VN POSTs here when payment settles.
    This is faster and more reliable than polling.
    """
    order_id = payload["order_id"]
    amount = payload["amount_vnd"]
    transaction_id = payload["transaction_id"]

    # Instantly fulfill the order
    fulfill_order(order_id)

    # Notify your agent or customer
    notify_slack(f"Order {order_id} settled for {amount} VND")

    return {"status": "ok"}

Register this URL in the AgentPay VN dashboard. You'll get real-time confirmations with zero latency.

Troubleshooting

Q: I created a payment request, but the QR code won't scan. A: Verify your bank code is correct. Wrong bank code = invalid QR. Check the supported banks list.

Q: My agent never receives the settlement callback. A: Ensure your await_settlement() timeout is long enough (minimum 60 seconds). Network latency or bank processing can take 30–90 seconds. Also, confirm your API key has webhook permissions.

Q: Can I refund a payment? A: No—AgentPay VN doesn't hold money, so there's nothing to refund on our side. You'd refund directly from your bank account to the customer's account, or credit their account in your system.

Q: Is there a fee? A: No transaction fees from AgentPay VN (it's open-source). Your bank may charge a small per-transaction fee (typically 0.5–2% in Vietnam), but you'd pay that anyway with any payment processor.

FAQ

How secure is this? AgentPay VN is open-source (MIT license) on GitHub. Your private API key is never exposed to customers. QR codes are generated server-side and only contain your bank account + amount, which is exactly what a VietQR should contain. Money flows directly from customer's bank to yours with no intermediary.

Can I use this in production? Yes. AgentPay VN is production-ready and used by multiple Vietnamese startups. Start with small test transactions and scale up with confidence.

What if my bank doesn't support VietQR? Almost all Vietnamese banks launched VietQR support by 2023. If yours hasn't, contact your bank's business team—they'll enable it quickly. Alternatively, use a fintech like Viettel Money or Momo that wraps VietQR.

Can I combine this with other payment methods? Absolutely. Use AgentPay VN for bank transfers + stripe for international cards. Your agent can offer both: "Pay via VietQR (instant) or credit card (also works)." Code example in docs.

Key Takeaways

Next Steps

Ready to add checkout to your agent? Here's your action plan:

  1. Install: pip install agentpay-vn
  2. Grab your bank details: Account number, bank code (from supported list)
  3. Paste the 12-line example above into a Python script and test with 10,000 VND
  4. Read the full docs: agentpay.servicesai.vn/v1/docs
  5. Join the community: Star the GitHub repo and ask questions in the Issues section

Your AI agent is now a merchant. Welcome to the future of autonomous businesses.

Get started →

← All posts