VietQR Payment Automation for AI Agents
The Problem: AI Agents Need a Native Vietnamese Payment Layer
Imagine you've built an AI agent that sells online courses to Vietnamese students. Your agent can process orders, answer questions in real-time, and recommend content—but when payment time arrives, it hits a wall. Stripe doesn't accept Vietnamese bank accounts in most cases. PayPal integration is clunky. You end up asking customers to jump through manual payment hoops, killing 40% of your conversion rate before they even reach checkout.
Now picture a different scenario: A café's reservation chatbot collects deposits. A freelance marketplace's AI assistant handles milestone payments. An e-learning platform's bot completes transactions in seconds—all denominated in VND, all settling directly to the merchant's bank account.
This is the gap AgentPay VN fills. It's a lightweight, open-source (MIT license) Python SDK that lets AI agents request, send, and verify VietQR payments without ever touching your money. The QR code points straight at your bank account. A bank feed confirms settlement. No middleware. No monthly fees for each transaction.
What Is AgentPay VN? The Tech Stack
AgentPay VN consists of three core pieces:
- Python SDK (
pip install agentpay-vn)—a synchronous library for creating payment requests, generating checkout URLs, and polling settlement status. - MCP Server (
agentpay-mcp)—a Model Context Protocol server that exposes AgentPay functions to Claude and other AI models, turning your agent into a payment-capable assistant. - VietQR Integration—automatic QR code generation that routes payments to your nominated bank account, with settlement confirmation via bank API feeds.
The beauty: your agent never holds, processes, or logs sensitive payment data. It orchestrates the flow and confirms completion. Your bank holds the money from second one. That's radically different from Stripe's architecture in Vietnam.
Why AgentPay VN Beats Stripe for Vietnamese Merchants
Let's be direct. Stripe doesn't have native VietQR support for Vietnamese merchants. You'd need to build custom integrations, manage currency conversion, and wait weeks for payout. AgentPay VN was purpose-built for this market.
Quick Comparison Table
| Feature | AgentPay VN | Stripe | PayPal |
|---|---|---|---|
| VietQR support | ✅ Native | ❌ No | ❌ No |
| AI agent-ready | ✅ MCP server included | ❌ No | ❌ No |
| Vietnam bank settlement | ✅ Direct | ⚠️ Multi-step | ⚠️ Multi-step |
| Open-source | ✅ MIT | ❌ No | ❌ No |
| Holds customer funds | ❌ No | ✅ Yes (48h minimum) | ✅ Yes |
| Monthly transaction fees | ❌ No | ✅ 2.9% + $0.30 | ✅ 2.2% + fixed |
Installation & Setup: 5 Minutes to Your First Payment
Step 1: Install the SDK
pip install agentpay-vn
This installs the core Python package. No additional dependencies beyond requests and pydantic.
Step 2: Initialize Your Merchant Account
Head to https://agentpay.servicesai.vn/v1/docs to:
- Create an account with your bank details
- Link your Vietnam bank account (VCB, Techcombank, VIB, etc.)
- Grab your
MERCHANT_IDandAPI_KEY
Stash these in environment variables:
export AGENTPAY_MERCHANT_ID="your-merchant-id"
export AGENTPAY_API_KEY="your-api-key"
Step 3: Create Your First Payment Request
Here's a real Python example:
from agentpay_vn import AgentPayClient, PaymentRequest
import os
# Initialize the client
client = AgentPayClient(
merchant_id=os.getenv("AGENTPAY_MERCHANT_ID"),
api_key=os.getenv("AGENTPAY_API_KEY")
)
# Create a payment request for 500,000 VND (≈$20 USD)
payment = client.create_payment_request(
amount=500000,
currency="VND",
description="Online Course: Advanced Python",
reference_id="order_12345", # Your unique order ID
customer_email="student@example.com",
customer_phone="0912345678"
)
print(f"Payment ID: {payment.id}")
print(f"Checkout URL: {payment.checkout_url}")
# Output:
# Payment ID: pay_abc123xyz
# Checkout URL: https://agentpay.servicesai.vn/checkout/pay_abc123xyz
Line-by-line:
- create_payment_request() reaches AgentPay's backend, which generates a unique VietQR code linked to your bank account
- amount is in VND (Vietnamese dong), no currency conversion needed
- reference_id is YOUR order ID—use it to reconcile with your database
- The function returns a PaymentRequest object with checkout_url; send this URL to your customer
The 3-Step Flow: From Request to Settlement
The entire payment lifecycle for an AI agent:
Step 1: Create Payment Request (Agent Initiates)
Your agent receives an order and triggers create_payment_request(). This reserves a unique VietQR and generates a checkout link.
Step 2: Send Checkout URL (Agent Communicates)
Your agent sends the URL to the customer via email, SMS, or displays it in the chat interface. The customer scans the QR with their banking app and confirms the transfer. No form-filling, no sensitive data exchange.
Step 3: Await Settlement (Agent Confirms)
Your agent polls the payment status until it confirms settlement:
import time
from agentpay_vn import PaymentStatus
payment_id = "pay_abc123xyz"
max_wait = 300 # 5 minutes
elapsed = 0
while elapsed < max_wait:
status = client.get_payment_status(payment_id)
if status.status == PaymentStatus.SETTLED:
print(f"✅ Payment confirmed! Settled at {status.settled_at}")
# Fulfill the order: send course access, deliver product, etc.
fulfill_order(reference_id=status.reference_id)
break
elif status.status == PaymentStatus.FAILED:
print(f"❌ Payment failed: {status.failure_reason}")
# Notify customer, retry, or escalate
break
else:
print(f"⏳ Pending... ({elapsed}s elapsed)")
time.sleep(5)
elapsed += 5
Key insights:
- Settlement confirmation is near-instant (seconds to ~2 minutes)—much faster than Stripe's 48-hour holds
- The reference_id in the response matches your order ID, so you know which customer's payment succeeded
- PaymentStatus.FAILED includes a reason (e.g., "insufficient funds", "timeout", "customer cancelled")
Integrating with Claude via MCP Server
If you're running AgentPay with Claude or another LLM, use the MCP server to expose payment functions as tool calls.
Install MCP Server
pip install agentpay-mcp
Configure Claude Desktop
Edit ~/.config/Claude/claude_desktop_config.json (or Windows equivalent):
{
"mcpServers": {
"agentpay": {
"command": "python",
"args": ["-m", "agentpay_mcp.server"],
"env": {
"AGENTPAY_MERCHANT_ID": "your-merchant-id",
"AGENTPAY_API_KEY": "your-api-key"
}
}
}
}
Restart Claude. Now Claude can call:
create_payment_request— initiate a paymentget_payment_status— check if it's settledlist_recent_payments— retrieve transaction history
Example Claude prompt:
User: "I want to enroll in the Python course. It costs 499,000 VND."
Claude: "I'll set that up for you right now."
[Claude calls: create_payment_request(amount=499000, description="Python Course Enrollment")]
"Here's your checkout link: https://agentpay.servicesai.vn/checkout/pay_xyz789
Just scan the QR with your banking app and confirm the 499,000 VND transfer. I'll grant you access the moment it settles—usually within 60 seconds."
[Claude polls get_payment_status in the background]
"✅ Payment received! Your course access is active. Here are your login credentials..."
Claude's LLM brain + AgentPay's payment engine = a fully autonomous checkout experience.
Real-World Walkthrough: An Online Course Bot
Let's walk through a concrete example: a Vietnamese online course platform that uses an AI agent to handle enrollments.
Scenario: A student named Linh browses a course on advanced data science (2.5 million VND for lifetime access).
The Flow
- Linh clicks "Enroll with AI Agent" → Chatbot appears
- Agent greets her: "Xin chào! I'll help you enroll. Just confirm your email and phone, and I'll generate your payment link."
- Linh provides: email = linh@example.com, phone = 0987654321
- Agent calls
create_payment_request(amount=2500000, description="Data Science Masterclass", reference_id="enrollment_linh_20250115") - Agent responds: "Your QR code is ready. Scan this link with your banking app to pay 2,500,000 VND: [checkout_url]"
- Linh scans the QR → Her bank app opens → She confirms the transfer → Transaction settles in 45 seconds
- Agent polls
get_payment_status()→ DetectsPaymentStatus.SETTLED - Agent sends: "✅ Payment confirmed! Your course access is live. Download the first module here: [link]"
- Agent logs:
enrollment_linh_20250115ascompletedin the database
Result: Zero manual intervention. Linh has access within a minute. The platform's bank account received 2.5 million VND. The agent handled everything.
Advanced Tips & Best Practices
1. Idempotency Keys
Always include a stable reference_id so duplicate requests don't create multiple payment requests:
import hashlib
def generate_order_id(user_id, product_id, timestamp):
key = f"{user_id}_{product_id}_{timestamp}"
return hashlib.md5(key.encode()).hexdigest()[:12]
order_id = generate_order_id(user_id=1001, product_id=42, timestamp="2025-01-15")
payment = client.create_payment_request(
amount=500000,
reference_id=order_id # Unique, repeatable
)
2. Webhook Support (Future)
Currently, you poll for status. In production, set a cron job or use a task queue:
# Check every 10 seconds for up to 5 minutes
for i in range(30):
status = client.get_payment_status(payment_id)
if status.status != PaymentStatus.PENDING:
break
time.sleep(10)
Or integrate with Celery/APScheduler for background polling.
3. Error Handling
Always wrap API calls:
from agentpay_vn.exceptions import AgentPayError, NetworkError
try:
payment = client.create_payment_request(amount=500000)
except NetworkError as e:
print(f"Network issue: {e.message}")
# Retry with exponential backoff
except AgentPayError as e:
print(f"API error: {e.code} - {e.message}")
# Log and alert admin
4. Test Mode
During development, use test amounts:
payment = client.create_payment_request(
amount=1000, # Test with 1,000 VND first
environment="TEST" # Doesn't hit your live bank account
)
Do's and Don'ts
| ✅ DO | ❌ DON'T |
|---|---|
Store reference_id in your DB to reconcile |
Store customer bank details—AgentPay handles that |
| Poll status every 5–10 seconds initially, then back off | Poll every second (you'll hit rate limits) |
| Use HTTPS for your agent's webhook receiver | Log payment IDs in plain text |
| Test with small amounts first (1,000 VND) | Build against production without testing |
| Set a reasonable timeout (5 min) for settlement | Wait indefinitely for a settlement signal |
FAQ
Q: Does AgentPay hold my money? A: No. The payment goes straight from the customer's bank account to your bank account. AgentPay is a connector, not a payment processor. We never touch the funds.
Q: What banks does it support? A: Any Vietnamese bank with VietQR infrastructure: Vietcombank, Techcombank, VIB, ACB, MB, TPBank, VPBank, Agribank, SHB, and 20+ others. Your customers don't need to use the same bank as you.
Q: How fast is settlement? A: VietQR transfers settle in 1–3 minutes under normal conditions. You'll be notified immediately when the bank confirms the transfer, so your agent can instantly fulfill the order.
Q: Can I use this in production right now? A: Yes. AgentPay VN is MIT-licensed and production-ready. The SDK is stable. Start with a small test batch (100 VND orders) to confirm your bank integration, then scale.
Key Takeaways
- AgentPay VN is an open-source Python SDK + MCP server for VietQR payments—purpose-built for Vietnamese AI agents and merchants
- No fund holding: Payments route directly to your bank account, settling in 1–3 minutes
- Three-step flow:
create_payment_request()→ send checkout URL →await_settlement() - AI-native: MCP server integration means Claude and other LLMs can handle payments autonomously
- Zero fees for the platform (you're not paying AgentPay per transaction)
- Perfect for course platforms, SaaS, e-commerce, booking systems, and service delivery bots operating in Vietnam
- Beats Stripe in Vietnam because it natively supports VietQR and doesn't impose 48-hour fund holds
Next Steps
Ready to add payments to your AI agent?
- Install:
pip install agentpay-vn - Read the docs: https://agentpay.servicesai.vn/v1/docs
- Clone the repo: https://github.com/phuocdu/agentpay-vn (includes example agents and test suites)
- Set up an account on the platform and grab your API credentials
- Test with 1,000 VND to verify your bank integration
- Deploy your payment-enabled agent to production
Your Vietnamese customers are waiting for frictionless, fast, local payments. AgentPay VN makes that possible in about 30 minutes of integration time.