Let Your AI Agent Accept VietQR Payments in Python
The Problem: AI Agents That Can't Close the Sale
You've built an intelligent Python agent—maybe it recommends products, answers customer questions, or even completes transactions. But the moment a customer says "I'm ready to buy," your agent hits a wall. How do you collect payment? How do you prove settlement happened? If you're in Vietnam, you've probably dreamed of a frictionless way to let your AI agents accept payments without handling money, holding customer funds, or wrestling with complex banking APIs.
That's exactly why AgentPay VN exists. It's an open-source Python SDK (MIT license) that lets your AI agent generate VietQR payment requests and confirm when money actually lands in your merchant account—with zero middleman holding cash.
What Is AgentPay VN? (The 60-Second Version)
AgentPay VN is two things:
- A Python SDK (
pip install agentpay-vn) that handles VietQR payment flows. - An MCP server (
agentpay-mcp) that integrates directly with Claude and other AI models.
The magic: your agent creates a payment request → generates a checkout URL → watches your bank feed for settlement confirmation. The QR code points directly at your merchant bank account. AgentPay never touches the money. You own the funds immediately.
Why This Matters for Your AI Agent
Traditional payment APIs require you to: - Create accounts with payment providers. - Handle webhook complexity. - Trust intermediaries with customer data. - Wait for settlement (sometimes 2–5 days).
AgentPay VN sidesteps all of this. Your agent can: - Generate a checkout in milliseconds. - Point customers to a direct bank transfer. - Confirm payment from your own bank feed. - Keep 100% of the revenue, instantly.
This is perfect for AI-powered course platforms, SaaS bots, café ordering agents, or any service where your AI needs to collect payment.
Getting Started: Installation and Setup
Step 1: Install the SDK
pip install agentpay-vn
That's it. No external service accounts. No API keys to manage (yet).
Step 2: Connect Your Bank Feed (If Using Bank Settlement Confirmation)
If you want your agent to automatically confirm payment arrival, connect your bank feed. This step is optional if you're happy checking your account manually.
Step 3: Initialize the SDK in Your Python Code
from agentpay_vn import PaymentManager
# Initialize with your merchant details
payment_manager = PaymentManager(
merchant_id="YOUR_MERCHANT_ID", # Your shop name or ID
merchant_account="1234567890", # Your bank account number
bank_code="970418" # VietQR-compatible bank code (e.g., MB Bank)
)
You're ready. No waiting for approval.
The 3-Step Payment Flow Explained
Every payment with AgentPay VN follows this pattern:
Step 1: Create a Payment Request
Your agent initiates a payment by specifying the amount, description, and customer info:
from agentpay_vn import create_payment_request
# Step 1: Create the payment request
payment = create_payment_request(
amount=500000, # 500,000 VND
description="Online Course: Python & AI",
customer_name="Nguyễn Văn A",
customer_phone="0912345678",
order_id="ORD-2025-001",
merchant_account="1234567890",
bank_code="970418"
)
print(f"Payment request created: {payment['id']}")
Line-by-line breakdown:
- amount: Payment in VND (use integers; 500000 = 500k VND).
- description: What the customer is buying (shows in their bank app).
- customer_name / customer_phone: Data you need to track who paid.
- order_id: Your internal reference (link to the course, product, session, etc.).
- merchant_account / bank_code: Where the money goes.
Step 2: Get the Checkout URL and Send It
Once a payment request exists, AgentPay generates a VietQR checkout URL. Your agent shares this with the customer:
# Step 2: Get the checkout URL
checkout_url = payment['checkout_url']
# Example output:
# https://agentpay.servicesai.vn/checkout/pay_1234567890abcdef
# Your agent sends this to the customer (via chat, email, SMS)
agent_message = f"""
Thank you for enrolling! Please complete payment here:
{checkout_url}
Amount: 500,000 VND
Course: Python & AI Essentials
Your payment will be confirmed as soon as we see it in our account.
"""
print(agent_message)
The customer scans the QR code (or taps the link) and transfers money from their bank app. No extra apps, no new accounts—just their normal banking app.
Step 3: Await Settlement and Close the Loop
Your agent waits for the payment to arrive. You can poll your bank feed or let AgentPay watch it for you:
from agentpay_vn import await_settlement
import asyncio
async def check_payment(payment_id):
# Wait up to 5 minutes for settlement
result = await await_settlement(
payment_id=payment_id,
timeout_seconds=300,
expected_amount=500000
)
if result['settled']:
print(f"✓ Payment confirmed! {result['actual_amount']} VND received.")
print(f"Settlement timestamp: {result['settled_at']}")
return True
else:
print(f"✗ Payment not received. Timeout reached.")
return False
# In your agent's flow:
payment_confirmed = asyncio.run(check_payment(payment['id']))
if payment_confirmed:
# Grant course access, send credentials, etc.
agent_response = "Your course access is ready! Check your email for the login link."
else:
agent_response = "We didn't receive your payment. Please try again."
Key points:
- await_settlement() polls your bank feed (or AgentPay's) for the incoming transfer.
- It validates that the amount matches and that it came from the correct customer.
- If settlement arrives within the timeout, your agent unlocks the purchase immediately.
- If not, you can retry or ask the customer to confirm they sent it.
Real-World Walkthrough: An AI Course-Selling Bot
Let's say you're running an AI course platform. Your Claude-powered agent handles everything: course recommendations, previews, and enrollment. Here's the full flow:
from agentpay_vn import create_payment_request, await_settlement
import asyncio
class CourseBot:
def __init__(self):
self.payment_manager = PaymentManager(
merchant_id="AI Academy VN",
merchant_account="1234567890",
bank_code="970418"
)
async def enroll_student(self, course_id, student_name, student_phone):
"""
End-to-end enrollment: create payment, share checkout, await settlement.
"""
# Fetch course details
course = self.get_course(course_id) # e.g., {"name": "Python & AI", "price": 500000}
# Step 1: Create payment request
payment = create_payment_request(
amount=course['price'],
description=f"Enrollment: {course['name']}",
customer_name=student_name,
customer_phone=student_phone,
order_id=f"COURSE-{course_id}-{int(time.time())}",
merchant_account=self.payment_manager.merchant_account,
bank_code=self.payment_manager.bank_code
)
print(f"Payment created: {payment['id']}")
# Step 2: Inform student
checkout_url = payment['checkout_url']
print(f"Student, please pay here: {checkout_url}")
# Step 3: Wait for settlement (with a 10-minute timeout)
try:
result = await await_settlement(
payment_id=payment['id'],
timeout_seconds=600,
expected_amount=course['price']
)
if result['settled']:
# Grant access
self.grant_course_access(course_id, student_phone)
print(f"✓ {student_name} enrolled successfully!")
return {"status": "enrolled", "course_id": course_id}
else:
print(f"✗ Payment timeout for {student_name}")
return {"status": "timeout", "payment_id": payment['id']}
except Exception as e:
print(f"Error: {e}")
return {"status": "error", "message": str(e)}
def get_course(self, course_id):
# Mock: replace with your database
courses = {
"python-ai": {"name": "Python & AI Essentials", "price": 500000},
"advanced-agents": {"name": "Advanced AI Agents", "price": 750000}
}
return courses.get(course_id)
def grant_course_access(self, course_id, student_phone):
# Mock: send credentials, create account, etc.
print(f"Access granted for {course_id} to {student_phone}")
# Usage
bot = CourseBot()
asyncio.run(bot.enroll_student(
course_id="python-ai",
student_name="Nguyễn Văn A",
student_phone="0912345678"
))
In this scenario: 1. Student asks the bot to enroll in a course. 2. Bot creates a payment request. 3. Bot shares a checkout URL. 4. Student pays via their bank app. 5. Bot detects settlement within seconds. 6. Bot grants course access automatically.
Timeline: Student to access = ~2–5 minutes (mostly student's bank transfer time).
Integrating with Claude via MCP Server
If you want Claude (or another AI model) to handle payments natively, use the AgentPay MCP server:
Step 1: Install the MCP Server
pip install agentpay-mcp
Step 2: Configure Claude
Add this to your claude_desktop_config.json (on macOS: ~/Library/Application Support/Claude/claude_desktop_config.json):
{
"mcpServers": {
"agentpay": {
"command": "python",
"args": ["-m", "agentpay_mcp.server"],
"env": {
"MERCHANT_ID": "Your Shop Name",
"MERCHANT_ACCOUNT": "1234567890",
"BANK_CODE": "970418"
}
}
}
}
Step 3: Use in Claude
Now Claude can call AgentPay functions directly:
User: "I want to enroll in the Python course. How much is it?"
Claude: "The course costs 500,000 VND. Let me create a payment link for you."
(Claude calls agentpay:create_payment_request via MCP.)
Claude: "Here's your checkout link: https://agentpay.servicesai.vn/checkout/pay_xxxx"
Claude then monitors the payment and confirms when it arrives.
Do's and Don'ts
| Do | Don't |
|---|---|
Do set realistic timeout_seconds (300–600 for most use cases). |
Don't timeout after 30 seconds; bank transfers take time. |
Do store payment_id and order_id for reconciliation. |
Don't rely on checkout URLs as permanent payment proof. |
Do validate customer_phone before creating requests. |
Don't create payments without knowing who the customer is. |
Do handle await_settlement() exceptions (network, timeouts). |
Don't assume settlement always succeeds silently. |
| Do use bank codes from the VietQR standard (970418 for MB, etc.). | Don't make up or guess bank codes. |
FAQ
Q: Does AgentPay hold my money? No. The QR code points directly to your merchant bank account. AgentPay only coordinates the request and confirms settlement—it never touches funds.
Q: Can I use this outside Vietnam? AgentPay VN is built for Vietnam's VietQR system. If your customers use Vietnamese banks, yes. International use requires custom integration.
Q: How long does settlement take? Most VietQR transfers settle within 30 seconds to 2 minutes. You should wait 5–10 minutes before timing out to account for delays or slow networks.
Q: What if a customer pays the wrong amount?
await_settlement() validates the amount. If it doesn't match, the function returns settled: false. You can then ask the customer to correct the payment or issue a refund manually.
Advanced Tips
- Batch Payments: Create multiple payment requests in parallel if you're enrolling many students at once.
- Customizable Descriptions: Use
descriptionto include order IDs, course names, or promo codes—customers see this in their bank app. - Error Handling: Always wrap
await_settlement()in try-except to handle network timeouts gracefully. - Logging & Audits: Store every payment event (created, settled, failed) in your database for reconciliation.
- Webhooks (Future): Check the docs at https://agentpay.servicesai.vn/v1/docs for real-time settlement webhooks if you need them.
Key Takeaways
- AgentPay VN lets your Python AI agent accept VietQR payments in just three steps: create request → share checkout → await settlement.
- No middleman holds your money; the QR points straight to your bank account.
- Install with
pip install agentpay-vnand start building in minutes. - Use the MCP server to let Claude natively handle payments.
- Perfect for course bots, SaaS agents, and any AI service that needs to collect payment.
- Always validate customer info, set sensible timeouts, and handle exceptions.
Ready to Accept Payments with Your AI?
Start now:
- Install:
pip install agentpay-vn - Learn more: Visit the AgentPay VN docs
- Fork & contribute: GitHub (MIT license)
Your AI agent is ready to make money. Let's go.