AI Agents Accepting VietQR Payments in Python

2026-09-30 · AgentPay VN

pythonai-agentsvietqrpaymentsmcp-server

The Problem: AI Agents Without Commerce

You've built a brilliant AI assistant—maybe it tutors students, sells digital products, or books restaurant reservations. It works flawlessly. Then a user asks: "Can I pay you directly?"

You freeze. Your agent has no way to accept money. You're stuck either: - Manually processing Stripe webhooks and updating agent state (fragile, slow) - Using closed-source payment SDKs that require deep integration - Asking users to pay through a separate link, breaking the conversation flow

This is especially frustrating for Vietnamese developers targeting Vietnamese users—Stripe, PayPal, and Square offer mediocre VietQR support. VietQR is the standard for peer-to-merchant transfers in Vietnam, yet integrating it into AI workflows has been a nightmare.

AgentPay VN changes this.

What Is AgentPay VN?

AgentPay VN is an open-source MIT-licensed Python SDK (plus an optional MCP server) that lets your AI agent generate VietQR payment requests, share checkout URLs, and settle payments—without ever touching money.

Here's the genius part: AgentPay VN never holds funds. The QR code points straight at your merchant's bank account. A bank feed confirms settlement. Your agent simply orchestrates the request and waits for confirmation. It's a 3-step flow:

  1. create_payment_request – Generate a unique payment request
  2. send checkout_url – Share the URL with the customer
  3. await_settlement – Listen for bank confirmation

That's it. No escrow, no holding accounts, no middleman fees.

Why This Matters for Python Developers

If you're building AI agents in Python (Claude, ChatGPT, open-source models), payment integration is usually your biggest headache. Most SDKs assume human-driven checkout flows, not agentic workflows. AgentPay VN is designed for agents:

Getting Started: Installation and First Request

Step 1: Install AgentPay VN

pip install agentpay-vn

That's literally it. No API keys to configure yet—AgentPay VN works with your existing bank account via a simple setup.

Step 2: Your First Payment Request

Here's a real example: a Python AI tutor that charges students ₫50,000 per session.

from agentpay_vn import AgentPay

# Initialize with your merchant details
agent_pay = AgentPay(
    merchant_id="MERCHANT_123",  # Your AgentPay merchant ID
    merchant_name="AI Tutor Bot",
    bank_account="0123456789",   # Your bank account (BIDV, Techcombank, etc.)
    bank_bin="970436",           # Your bank's BIN (BIDV = 970436)
)

# Student requests a tutoring session
session_fee = 50000  # VND
student_email = "student@example.com"

# Step 1: Create payment request
payment_request = agent_pay.create_payment_request(
    amount=session_fee,
    description=f"Tutoring session for {student_email}",
    reference_id=f"session_{student_email}_{int(time.time())}",
)

print(f"Payment request created: {payment_request.request_id}")
print(f"Share this URL with the student: {payment_request.checkout_url}")

# Step 2: Send checkout URL to the student
send_message_to_student(payment_request.checkout_url)

Line-by-line breakdown: - Lines 3-10: Initialize AgentPay with your merchant details. These come from your bank registration (no Stripe-like approval process—most Vietnamese banks auto-register VietQR for merchants). - Lines 13-18: Define the payment context (amount, student email, a unique reference). - Lines 20-24: Call create_payment_request(). AgentPay generates a unique request ID and a checkout URL. The URL contains an encoded VietQR QR code. - Lines 26-27: Log and send the URL to the student.

Step 3: Wait for Settlement

Now the tricky part in most systems: How do you know when the student has paid?

AgentPay VN provides await_settlement():

import asyncio
from agentpay_vn import AgentPay

async def start_tutoring_session(student_id, session_fee):
    agent_pay = AgentPay(...)

    # Create and send payment request (as above)
    payment_request = agent_pay.create_payment_request(
        amount=session_fee,
        description=f"Session for {student_id}",
        reference_id=f"session_{student_id}",
    )

    print(f"Payment URL: {payment_request.checkout_url}")

    # Step 3: Wait for settlement
    try:
        settlement = await agent_pay.await_settlement(
            request_id=payment_request.request_id,
            timeout_seconds=600,  # Wait up to 10 minutes
        )

        print(f"✓ Payment confirmed! Transaction ID: {settlement.transaction_id}")
        print(f"Amount received: ₫{settlement.amount}")

        # Now start the tutoring session
        start_lesson(student_id)

    except TimeoutError:
        print(f"❌ Payment timed out. Student didn't pay within 10 minutes.")
        cancel_session(student_id)

# Usage
asyncio.run(start_tutoring_session("student_123", 50000))

What's happening: - Line 10-18: Create the payment request (same as before). - Lines 20-25: Call await_settlement(). This polls your bank feed or uses webhooks (depending on configuration) to detect when ₫50,000 lands in your account. - Line 27: Once confirmed, settlement contains the transaction ID and final amount. The tutor can now start the session. - Line 33: If 10 minutes pass without payment, the session is canceled.

Using AgentPay VN with Claude (MCP)

If you're using Claude with the Model Context Protocol, AgentPay VN provides a pre-built MCP server (agentpay-mcp) so Claude can initiate payments in conversations.

MCP Configuration (Claude/Cline)

Add this to your Claude client config (e.g., in claude_desktop_config.json if using Claude Desktop, or your MCP client):

{
  "mcpServers": {
    "agentpay": {
      "command": "agentpay-mcp",
      "env": {
        "AGENTPAY_MERCHANT_ID": "MERCHANT_123",
        "AGENTPAY_MERCHANT_NAME": "AI Tutor Bot",
        "AGENTPAY_BANK_ACCOUNT": "0123456789",
        "AGENTPAY_BANK_BIN": "970436"
      }
    }
  }
}

Now Claude can call these tools directly:

User: "I want to book a 1-hour tutoring session."

Claude: "Great! That's ₫50,000 for a 1-hour session. Let me generate a payment link for you."
[Claude calls agentpay/create_payment_request]

Claude: "Here's your payment link: [QR code]. Scan it with your banking app and transfer ₫50,000. I'll wait for confirmation and then we'll start."
[Claude calls agentpay/await_settlement]

[30 seconds later, payment confirmed]

Claude: "✓ Payment received! Let's begin. Today we'll cover..."

This is the dream: the agent handles the entire flow—no manual intervention.

Real-World Walkthrough: AI-Powered Café Bot

Let's build a concrete example: a café chatbot that takes coffee orders and payments.

Scenario: A Vietnam-based café wants to sell coffee online. Customers chat with an AI bot, order "Cà phê đen đá" (iced black coffee), and pay via VietQR.

from agentpay_vn import AgentPay
import asyncio

class CafeBot:
    def __init__(self):
        self.agent_pay = AgentPay(
            merchant_id="CAFE_001",
            merchant_name="AI Cafe Bot",
            bank_account="0987654321",
            bank_bin="970436",  # BIDV
        )
        self.menu = {
            "cà phê đen đá": 25000,
            "cappuccino": 35000,
            "matcha": 40000,
        }

    async def process_order(self, customer_name, order_items):
        # Calculate total
        total = sum(self.menu.get(item, 0) for item in order_items)

        # Create payment request
        payment = self.agent_pay.create_payment_request(
            amount=total,
            description=f"Coffee order for {customer_name}: {', '.join(order_items)}",
            reference_id=f"cafe_{customer_name}_{int(time.time())}",
        )

        print(f"Order total: ₫{total}")
        print(f"Payment URL: {payment.checkout_url}")

        # Wait for payment
        try:
            settlement = await self.agent_pay.await_settlement(
                request_id=payment.request_id,
                timeout_seconds=300,
            )
            print(f"✓ Order confirmed! Your coffee will be ready in 15 minutes.")
            return True
        except TimeoutError:
            print(f"❌ Order canceled due to payment timeout.")
            return False

# Usage
async def main():
    bot = CafeBot()
    await bot.process_order("Hung", ["cà phê đen đá", "matcha"])

asyncio.run(main())

Real numbers: - Typical café markup: 20–30% - AgentPay VN overhead: ₫0 (direct bank transfer) - Settlement time: 1–5 minutes (depends on your bank) - Your profit: 100% of the ₫60,000 order goes to your account

Do's and Don'ts

✓ Do ✗ Don't
Use await_settlement() with a reasonable timeout (5–10 min) Don't hard-code bank account details in source code—use environment variables
Generate unique reference_id for each request Don't reuse the same reference_id across multiple requests
Log settlement confirmations for reconciliation Don't assume payment is instant—always await confirmation
Use MCP server for Claude/multi-agent workflows Don't call AgentPay VN from multiple agents simultaneously without coordination
Test with small amounts first (₫1,000) Don't go live with production merchant ID without testing

FAQ

Q: Does AgentPay VN take a cut of my payments?

A: No. AgentPay VN is open-source (MIT license) and free. Money goes straight to your bank account. You only pay your bank's standard VietQR fees (usually ₫0–₫500 per transaction).

Q: What if the customer's bank is different from mine (BIDV vs. Techcombank)?

A: VietQR is interbank. Your customer can pay from any bank, and you'll receive it in yours. The bank_bin in your config is just your receiving bank—customers' banks don't matter.

Q: Can I use AgentPay VN with async agents like LangChain or Crew?

A: Yes. AgentPay VN is async-first. You can wrap await_settlement() in a Pydantic model or tool definition in LangChain and Crew will handle the async scheduling.

Q: What happens if payment fails or the student refunds after settlement?

A: Settlement is final (it's a bank transfer). Refunds must be handled manually—you transfer money back. Track this in your application database.

Key Takeaways

Get Started Now

  1. Install: pip install agentpay-vn
  2. Read the docs: https://agentpay.servicesai.vn/v1/docs
  3. Explore the code: https://github.com/phuocdu/agentpay-vn
  4. Build your first agent: Use the examples above as templates for tutoring bots, cafés, course platforms, or any service your agent provides.

Your AI agents deserve the ability to earn. With AgentPay VN, they can—in Python, in seconds, with money flowing straight to you.

Get started →

← All posts