VietQR Payment Automation for AI Agents
The problem: AI agents in Vietnam can't easily collect payments
Imagine you've built an AI chatbot that sells online courses to Vietnamese students. A customer asks to enroll, your agent generates a course link, and then... silence. Your bot can't actually collect payment. It can't generate a payment link. It can't confirm the transaction happened.
Stripe doesn't support Vietnam's local payment rails. PayPal integration is clunky for Vietnamese merchants. You're left cobbling together APIs, manually tracking QR codes, and reconciling spreadsheets—defeating the entire purpose of having an AI agent handle transactions.
This is the gap AgentPay VN fills: a lightweight, open-source Python SDK that lets your AI agents create, send, and settle VietQR payments—Vietnam's fastest-growing payment method—in three lines of code.
What is AgentPay VN?
AgentPay VN is an MIT-licensed Python SDK + Model Context Protocol (MCP) server designed specifically for AI agents to handle Vietnamese bank transfers via VietQR. It's not a payment processor that holds your money. Instead, it acts as a thin orchestration layer:
- Your agent creates a payment request
- You send the customer a dynamic checkout URL (containing a VietQR code)
- The customer scans and pays directly to your merchant bank account
- AgentPay watches the bank feed and confirms settlement in seconds
No intermediary, no escrow, no 2–3% fee overhead. The money lands in your account; the agent knows immediately.
Why VietQR + AI agents = a winning combination
VietQR (Quick Response code for Vietnamese banks) is now the default for peer-to-peer and merchant payments across Vietnam. Over 40 million Vietnamese use it daily via banking apps. Compare this to Stripe (US-only infrastructure, high fees, compliance friction) or international gateways (slow, expensive).
For AI agents, this matters because:
- Speed: Agents can generate payment links in <100ms and await confirmation in real-time
- Autonomy: No manual steps; the agent orchestrates the entire transaction loop
- Cost: Merchant fees vary by bank (~0.5–1%), but you keep 99%+ of revenue
- Trust: Money goes directly to your account; you see it in your bank dashboard
Getting started: Installation and setup
Step 1: Install the SDK
pip install agentpay-vn
That's it. No API keys to juggle, no webhook URLs to expose. The library is self-contained.
Step 2: Initialize AgentPay in your agent code
Here's a minimal Python example that a Claude agent or other LLM can call:
from agentpay_vn import AgentPayClient, PaymentRequest
import json
import time
# Initialize the client (connects to your bank's VietQR service)
client = AgentPayClient(
merchant_id="MERCHANT_ABC123", # Your unique merchant ID from your bank
bank_account="1234567890", # Your linked bank account
)
# Step 1: Create a payment request
payment_req = client.create_payment_request(
amount_vnd=500000, # 500k VND for a course
description="Python Masterclass Enrollment",
reference_id="course_001_2025", # Unique order ID
expiry_minutes=30 # QR code valid for 30 min
)
# Step 2: Extract the checkout URL (send this to the customer)
checkout_url = payment_req.checkout_url
print(f"Pay here: {checkout_url}")
# Step 3: Wait for settlement (blocks until paid or timeout)
result = client.await_settlement(
reference_id="course_001_2025",
timeout_seconds=600 # Wait up to 10 minutes
)
if result.status == "SETTLED":
print(f"✓ Payment confirmed! Transaction ID: {result.transaction_id}")
# Now enroll the student, unlock the course, etc.
else:
print(f"✗ Payment failed or expired: {result.status}")
Line-by-line breakdown:
AgentPayClient: Initializes your merchant connection.merchant_idandbank_accountlink to your actual bank partner (e.g., Vietcombank, MB Bank).create_payment_request(): Generates a unique QR code for this transaction. Returns an object withcheckout_url(a link containing the QR),qr_data, andexpires_at.await_settlement(): Polls your bank's transaction feed. Blocks until the exact amount lands in your account or the timeout expires. No webhooks required.
Step 3: Use AgentPay as an MCP server with Claude
If you're running Claude (or another Claude-compatible agent), you can skip the Python integration and use AgentPay as a native MCP server:
{
"mcpServers": {
"agentpay-vn": {
"command": "agentpay-mcp",
"args": [
"--merchant-id",
"MERCHANT_ABC123",
"--bank-account",
"1234567890",
"--api-endpoint",
"https://api.agentpay.servicesai.vn"
],
"env": {
"BANK_FEED_TYPE": "vietcombank",
"POLLING_INTERVAL_SECONDS": "2"
}
}
}
}
With this config, your Claude agent can now call:
create_payment_request(amount_vnd, description, reference_id)await_settlement(reference_id, timeout_seconds)get_transaction_status(reference_id)
...directly in its function calling—no custom Python code needed.
Real-world walkthrough: An AI-powered course marketplace
Let's walk through a concrete scenario: Hana, a language teacher, built a Vietnamese→English conversation bot powered by Claude. She wants to charge 250k VND (≈$10 USD) per student.
Flow:
- Student chats with the bot: "I want to enroll."
- Bot creates a payment request:
python req = client.create_payment_request( amount_vnd=250000, description="Hana's English Conversation Course", reference_id=f"student_{student_id}_2025", expiry_minutes=15 ) -
Bot sends the checkout link: "Scan this QR code with your banking app to pay." - The link embeds a high-res VietQR code - Student opens their bank app (Vietcombank, Techcombank, etc.), scans, and pays - Takes ~10 seconds from QR to confirmation
-
Bot awaits settlement (blocks until paid):
python result = client.await_settlement( reference_id=f"student_{student_id}_2025", timeout_seconds=900 ) if result.status == "SETTLED": # Unlock the course, send materials, add to student DB db.students.update_one( {"_id": student_id}, {"$set": {"course_access": True, "paid_at": result.settled_at}} ) -
Hana's bank balance: 250k VND (minus ~2.5k VND bank fee) lands in her account within 30 seconds. No middleman, no waiting 3–5 days.
In a single afternoon, Hana onboarded 12 paying students. Without AgentPay, she'd have manually requested payment via email, tracked transfers in a spreadsheet, and manually unlocked courses—a 2-hour process per student.
Advanced tips: Production patterns
Idempotency and retries
When calling create_payment_request() in a distributed system, always use a stable reference_id:
import hashlib
# Generate deterministic ID based on student + timestamp (floor to minute)
reference_id = hashlib.md5(
f"{student_id}_{int(time.time() / 60)}".encode()
).hexdigest()[:12]
# If the network drops and you retry, you'll get the same QR code
# (not a duplicate charge)
Timeout strategy
Don't block indefinitely. Set reasonable timeouts:
- 15–30 min for web checkout: Customer scans and pays in real-time
- 5–10 min for bot interaction: Assumes customer has their phone open
- Fallback to async: For batch processes, check settlement status asynchronously every 10 seconds
async def poll_payment_async(ref_id, interval=10, max_polls=120):
for i in range(max_polls):
result = client.get_transaction_status(ref_id)
if result.status == "SETTLED":
return result
await asyncio.sleep(interval)
raise TimeoutError(f"Payment {ref_id} not settled after {max_polls * interval}s")
Handling VietQR ambiguity
VietQR codes embed the account number and amount. If a customer has multiple banking apps or is on a slow network, they might pay from the wrong account or enter a different amount. Always validate:
if result.status == "SETTLED":
assert result.amount_vnd == 250000, "Amount mismatch!"
assert result.merchant_account == "1234567890", "Account mismatch!"
# Safe to fulfill the order
AgentPay VN vs. traditional payment gateways
| Feature | AgentPay VN | Stripe | PayPal | Local VietQR |
|---|---|---|---|---|
| Supports Vietnam | ✓ Native VietQR | ✗ Not available | ✗ High fees | ✓ Yes, but no API |
| AI agent integration | ✓ Built for agents (MCP) | ✓ But overkill | ✗ Complex OAuth | ✗ Manual |
| Fee | ~0.5–1% (to bank) | 3.6% + $0.30 | 3.49% + $0.49 | N/A |
| Settlement speed | ~30 sec | 1–2 days | 1–3 days | Real-time (direct to bank) |
| Holds funds? | ✗ No escrow | ✓ Yes (disputes) | ✓ Yes | ✗ Direct transfer |
| Open-source | ✓ MIT | ✗ Proprietary | ✗ Proprietary | ✗ N/A |
| Local bank support | 40+ Vietnamese banks | ✗ Not applicable | Limited | 40+ banks |
FAQ
Q: What if my customer's bank isn't supported?
A: AgentPay integrates with 40+ Vietnamese banks (Vietcombank, Techcombank, MB Bank, ACB, BIDV, etc.). These cover ~98% of Vietnamese banked population. For unsupported banks, fall back to a traditional transfer with a manual confirmation link.
Q: How do I handle refunds?
A: AgentPay doesn't process refunds—it's not a payment processor. To refund, you initiate a manual transfer from your bank account back to the customer's account. AgentPay can monitor that transfer for confirmation if needed. Alternatively, credit the customer's account in your system and let them re-use the credit.
Q: Can my agent handle concurrent payments?
A: Yes. Each create_payment_request() returns a unique reference_id and checkout_url. You can create 100 concurrent payment requests and await each independently. AgentPay's bank feed polling scales linearly.
Q: Is my bank account safe if I share it with AgentPay?
A: AgentPay never writes to your account. It only reads your transaction feed (read-only API access). Money only lands via legitimate VietQR transfers from customers' banks. Your private key stays with your bank.
Key takeaways
- VietQR + AI agents = natural fit: Direct to bank, instant confirmation, no intermediary.
- 3-line setup:
create_payment_request(), send URL,await_settlement(). - AgentPay is lightweight: 50KB SDK, no external dependencies, no API keys to leak.
- MCP mode for Claude: Drop the JSON config and your agent gains payment superpowers immediately.
- Cost-effective: 0.5–1% to the bank vs. 3–5% to Stripe/PayPal.
- Production-ready: Idempotent requests, async polling, real-world tested with 100+ merchants.
- Open-source: Audit the code, fork it, self-host if needed.
Get started now
Ready to give your AI agent payment superpowers?
- Install:
pip install agentpay-vn - Read the docs: https://agentpay.servicesai.vn/v1/docs
- Explore the code: https://github.com/phuocdu/agentpay-vn
- Set up an MCP server: Add the JSON config above and connect to Claude
In 15 minutes, your bot can accept payments. By tomorrow, you'll be running a fully autonomous payment loop.
Have questions? Open an issue on GitHub or ping the community. Happy selling!