VietQR Payment Automation for AI Agents: Stripe Alternative
The Pain Point: Why Vietnamese Businesses Can't Use Stripe for Agent Payments
You're building an AI chatbot that sells online courses to Vietnamese customers. The bot works flawlessly—it qualifies leads, answers questions, and closes deals. But when it's time to collect payment, you hit a wall. Stripe doesn't operate in Vietnam. PayPal integration is clunky for domestic transfers. Your users aren't comfortable with crypto wallets. You end up building a fragile custom integration with a Vietnamese payment gateway, wrestling with bank APIs, handling security compliance yourself, and watching settlement times stretch to days.
Meanwhile, your AI agent sits idle, unable to complete the payment loop without human intervention.
This is the exact problem AgentPay VN solves. It's a lightweight, open-source Python SDK (MIT license) purpose-built for AI agents to collect VietQR payments—Vietnam's instant bank transfer standard—directly into a merchant's bank account. No holding funds. No payment processor risk. No days-long settlement. Just a QR code, a bank confirmation, and instant agent autonomy.
What Is AgentPay VN and How Does It Differ from Stripe?
Standard payment processors like Stripe operate as money custodians: they hold customer funds briefly, perform fraud checks, take a cut, and eventually settle to your merchant account (usually in 2–3 business days). They're built for global scale and regulatory complexity.
AgentPay VN is agent-native: it generates a VietQR payment request that points directly at your bank account. When a customer scans and pays, the money lands in your bank account within seconds. The SDK simply orchestrates the flow and confirms settlement via bank feed integration.
Key Differences:
| Aspect | Stripe | AgentPay VN |
|---|---|---|
| Settlement time | 2–3 business days | Seconds (instant bank transfer) |
| Fund custody | Stripe holds money | Direct to merchant bank |
| Vietnam support | No | Yes (VietQR native) |
| Agent-ready | No setup for agents | Purpose-built for AI |
| Open source | Proprietary | MIT license |
| Setup complexity | Moderate | Minimal (3 lines of code) |
For AI agents operating in Vietnam, this is transformative: your bot can generate a payment request, send the checkout URL to a customer, and await settlement confirmation—all without leaving your agent loop.
Core Concept: The 3-Line Payment Flow
AgentPay VN abstracts payment collection into three sequential steps:
- create_payment_request() – Generate a unique VietQR request with amount, description, and expiry.
- send_checkout_url() – Deliver the QR code/payment link to the customer (SMS, email, chat).
- await_settlement() – Poll the bank feed until payment confirms; unblock the agent when funds arrive.
That's it. No webhooks to debug. No PCI compliance to audit. Just a clean, agent-friendly abstraction.
Installation and Setup
Step 1: Install the SDK
pip install agentpay-vn
This pulls the latest SDK from PyPI. Requires Python 3.8+.
Step 2: Configure Your Bank Credentials
AgentPay VN integrates with your bank's open API to watch for incoming payments. Most Vietnamese banks (Vietcombank, Techcombank, MB Bank) support this via their open banking initiatives. Set environment variables:
export BANK_API_KEY="your_bank_api_key_here"
export MERCHANT_ACCOUNT="your_bank_account_number"
export MERCHANT_NAME="Your Business Name"
export VIETQR_PARTNER_CODE="your_partner_code"
Obtain these from your bank's developer portal (usually takes 24–48 hours).
Step 3: Initialize the SDK
from agentpay_vn import AgentPayClient
client = AgentPayClient(
bank_api_key=os.getenv("BANK_API_KEY"),
merchant_account=os.getenv("MERCHANT_ACCOUNT"),
merchant_name=os.getenv("MERCHANT_NAME"),
vietqr_partner_code=os.getenv("VIETQR_PARTNER_CODE")
)
Real-World Example: An Online Course Bot
Imagine you're running an AI tutor that sells 30-minute coding consultations for 500,000 VND ($20 USD). Here's how your agent collects payment:
from agentpay_vn import AgentPayClient
import asyncio
import os
client = AgentPayClient(
bank_api_key=os.getenv("BANK_API_KEY"),
merchant_account=os.getenv("MERCHANT_ACCOUNT"),
merchant_name="AI Tutor VN",
vietqr_partner_code=os.getenv("VIETQR_PARTNER_CODE")
)
async def handle_course_purchase(customer_name, customer_phone, amount_vnd=500000):
"""
Agent function to process a course purchase.
Returns True if payment confirmed, False if timeout/failure.
"""
# Step 1: Create the payment request
# amount_vnd: 500000 (500k VND)
# description: reference text shown in customer's bank app
# expires_in: 900 (15 minutes before QR expires)
payment_req = await client.create_payment_request(
amount_vnd=amount_vnd,
description=f"Course: {customer_name}",
expires_in=900,
order_id=f"course_{customer_name}_{int(time.time())}"
)
# payment_req now contains:
# - qr_code_url: Direct image URL of the VietQR code
# - checkout_url: Deep link for mobile/web payment
# - request_id: Unique identifier to poll for settlement
print(f"[Agent] Payment request created: {payment_req['request_id']}")
# Step 2: Send checkout URL to customer
# In a real agent, this would be sent via SMS, Telegram, or WhatsApp
await send_sms_or_message(
phone=customer_phone,
message=f"Thanh toán khóa học: {payment_req['checkout_url']}"
)
print(f"[Agent] Checkout URL sent to {customer_phone}")
# Step 3: Await settlement
# timeout_sec: 900 (15 minutes, matching QR expiry)
# poll_interval_sec: 2 (check every 2 seconds)
settlement = await client.await_settlement(
request_id=payment_req['request_id'],
timeout_sec=900,
poll_interval_sec=2
)
if settlement['confirmed']:
print(f"[Agent] Payment confirmed! Amount: {settlement['amount_vnd']} VND")
print(f"[Agent] Settlement ID: {settlement['settlement_id']}")
# Agent can now proceed: send course link, grant access, etc.
await grant_course_access(customer_name)
return True
else:
print(f"[Agent] Payment timeout or failed. QR expired.")
return False
# Usage in your agent loop:
result = await handle_course_purchase(
customer_name="Nguyen Van A",
customer_phone="0912345678",
amount_vnd=500000
)
Line-by-line explanation:
- Line 16–22 (
create_payment_request): Generates a unique VietQR payment request. The SDK communicates with your bank's open API to register the request. Returns a QR code URL and a checkout deep link. - Line 24–32: In production, send the checkout URL to the customer via SMS/chat. The agent doesn't block here—it's async.
- Line 34–44 (
await_settlement): The agent polls the bank feed at 2-second intervals, checking if the payment has landed. If it confirms within 15 minutes, the agent proceeds. If the QR expires, it gracefully exits and can offer retry logic. - Line 46–50: Once confirmed, the agent has autonomy to complete downstream actions (grant access, send confirmations, update a database) without human intervention.
Using AgentPay VN with Claude and MCP Servers
If you're building agents that run on Claude (Anthropic's AI), you can expose AgentPay VN as an MCP (Model Context Protocol) server. This lets Claude call create_payment_request and await_settlement as native tools.
MCP Server Setup
# Install the MCP server
pip install agentpay-mcp
# Start the server (listens on port 3000 by default)
agentpay-mcp --port 3000 --bank-api-key $BANK_API_KEY --merchant-account $MERCHANT_ACCOUNT
Claude Integration (Claude Desktop Config)
Add this to your claude_desktop_config.json:
{
"mcpServers": {
"agentpay_vn": {
"command": "agentpay-mcp",
"args": [
"--port",
"3000",
"--bank-api-key",
"your_bank_api_key_here",
"--merchant-account",
"your_account_number_here",
"--merchant-name",
"Your Business Name",
"--vietqr-partner-code",
"your_partner_code_here"
],
"env": {}
}
}
}
Now Claude can natively invoke AgentPay tools:
Claude: "A customer wants to buy a course for 500k VND. Create a payment request and send the QR code."
Claude (internally calls MCP):
→ create_payment_request(amount_vnd=500000, description="Course purchase")
← qr_code_url: "https://...", checkout_url: "https://..."
Claude can then compose a response with the payment link, and you can set up a background job to poll for settlement.
Advanced Tips: Production Hardening
1. Idempotency and Duplicate Prevention
If your agent retries a payment request (network failure, timeout), always use the same order_id:
order_id = f"course_{customer_id}_{session_date}"
# Even if called twice with same order_id, SDK returns cached result
payment_req = await client.create_payment_request(
amount_vnd=500000,
order_id=order_id # Uniquely identifies this transaction
)
2. Webhook Confirmations (Faster Than Polling)
For high-volume scenarios, avoid polling. Instead, configure a webhook endpoint that your bank pushes settlement notifications to:
client.configure_webhook(
endpoint="https://yourapi.com/webhooks/agentpay",
secret="webhook_signing_secret"
)
Your agent can then listen for a webhook event instead of blocking on await_settlement(). This scales to thousands of concurrent transactions.
3. Expiry and Retry Logic
QR codes have expiry windows (default 15 minutes). Implement retry logic:
for attempt in range(3):
settlement = await client.await_settlement(
request_id=payment_req['request_id'],
timeout_sec=900
)
if settlement['confirmed']:
break
elif attempt < 2:
print(f"[Agent] Retry {attempt + 1}...")
# Optionally create a fresh payment request
payment_req = await client.create_payment_request(...)
Do's and Don'ts
Do:
- ✅ Use unique, idempotent order_id for each transaction.
- ✅ Set reasonable QR expiry times (600–1800 seconds depending on your use case).
- ✅ Log settlement_id and request_id for reconciliation.
- ✅ Test with test bank accounts first (sandbox mode in SDK: sandbox=True).
- ✅ Use webhooks instead of polling for high-volume agents.
Don't:
- ❌ Create multiple payment requests for the same order without canceling the old one.
- ❌ Assume instant settlement; network delays can add 1–5 seconds.
- ❌ Ignore settlement['confirmed'] status; always verify before granting access.
- ❌ Hardcode bank credentials; use environment variables.
- ❌ Disable SSL verification in production (verify_ssl=False).
Frequently Asked Questions
Q: What if a customer scans the QR but payment fails at their bank?
The settlement['confirmed'] will remain False, and the QR will expire after 15 minutes (or your configured window). The agent will timeout gracefully and can offer the customer to retry or contact support.
Q: Does AgentPay VN hold customer money?
No. The VietQR points directly at your merchant bank account. AgentPay VN only orchestrates the request and confirms settlement—it never touches funds.
Q: Can I use AgentPay VN with banks outside Vietnam?
Currently, no. VietQR is Vietnam-specific. However, the SDK is open-source (MIT license), so you can extend it to other countries' payment standards (e.g., Thai PromptPay, Philippines GCash).
Q: What happens if my agent crashes mid-payment?
Your customer's payment is still safe (in the bank, bound to your account). When your agent restarts, query the settlement status using the same request_id. The SDK provides a get_settlement_status() function for this:
status = await client.get_settlement_status(request_id="...")
if status['confirmed']:
# Resume operation
await grant_course_access(customer_name)
Key Takeaways
- AgentPay VN is an open-source Python SDK designed for AI agents to autonomously collect VietQR payments directly to merchant bank accounts.
- Instant settlement (seconds) replaces traditional payment processor delays (2–3 days).
- The 3-line flow (
create_payment_request→send_checkout_url→await_settlement) eliminates boilerplate. - No fund custody: Money never touches AgentPay—it flows directly from customer bank to your account.
- MCP integration lets Claude and other AI platforms call AgentPay tools natively.
- Webhook support scales payment processing for high-volume agents without polling overhead.
- Suitable for course sales bots, café ordering agents, online shop assistants, and any AI system operating in Vietnam.
Getting Started Now
You're 3 steps away from agent-powered payments:
- Install:
pip install agentpay-vn - Configure: Set
BANK_API_KEY,MERCHANT_ACCOUNT, etc. in your environment. - Code: Copy the course bot example above and adapt it to your use case.
For detailed API documentation, code examples, and bank integration guides, visit:
🔗 GitHub Repository – MIT license, contributions welcome.
Your AI agent is now free to collect Vietnamese payments without intermediaries. What will you build?