Add VietQR Checkout to Your LLM Agent in 10 Minutes
The Problem: Your AI Agent Can't Actually Close Sales
You've built an incredible LLM agent—it answers customer questions, recommends products, even negotiates pricing. But the moment a customer says "I want to buy," your agent hits a wall. It can't process payments. It can't confirm the transaction. It can't move money. So your agent becomes a glorified chatbot, and you lose the sale.
This is the gap AgentPay VN fills. In the next 10 minutes, you'll add a fully functional checkout system to your AI agent using VietQR—Vietnam's instant payment standard. No payment holding. No complex integrations. No monthly fees. Just a direct link from your customer's bank account to your merchant account.
Why AgentPay VN Changes the Game
Traditional payment APIs require you to: - Integrate with multiple providers - Store sensitive bank details - Handle PCI compliance - Wait days for settlement - Pay percentage fees per transaction
AgentPay VN does none of that. It's an open-source Python SDK + MCP server (MIT licensed) that generates a VietQR payment request, returns a checkout URL, and confirms settlement via your bank feed. The money never touches AgentPay—it flows directly from customer to you.
Think of it as plumbing for AI payments: connect your agent's checkout tool to your bank account in three function calls.
What You'll Build Today
By the end of this tutorial, you'll have: 1. A Python agent that creates payment requests on demand 2. A checkout URL your customers can scan or click 3. Automatic settlement tracking tied to your bank account 4. Integration with Claude (or any MCP-compatible LLM)
Let's build it.
Step 1: Install AgentPay VN
Start with the SDK:
pip install agentpay-vn
If you're using an MCP server (recommended for Claude integration), also install:
pip install agentpay-mcp
That's it. No API keys. No SDK initialization with secrets. AgentPay VN is designed to be lightweight and self-contained.
Step 2: Create Your First Payment Request
Here's the core workflow in Python:
from agentpay_vn import create_payment_request, await_settlement
import asyncio
# Step 1: Create a payment request
# Parameters: amount (VND), description, merchant_account_number
payment = create_payment_request(
amount=250000, # 250,000 VND for a course
description="Advanced Python for AI Agents",
merchant_account="0711000123456789" # Your VietQR account
)
# payment is a dict with:
# {
# "request_id": "req_abc123...",
# "checkout_url": "https://api.vietqr.io/...",
# "qr_code": "00020126...", # QR string for scanning
# "status": "pending"
# }
print(f"Send this link to your customer: {payment['checkout_url']}")
print(f"Or show them this QR: {payment['qr_code']}")
# Step 2: Wait for settlement (blocks until payment confirmed)
settlement = await_settlement(
request_id=payment['request_id'],
timeout_seconds=600 # 10-minute timeout
)
if settlement['status'] == 'confirmed':
print(f"✓ Payment received: {settlement['amount']} VND")
print(f"✓ Payer bank: {settlement['payer_bank']}")
print(f"✓ Transaction ID: {settlement['transaction_id']}")
# Deliver your product/service here
else:
print("✗ Payment cancelled or timed out")
Line-by-line explanation:
- Line 1-2: Import the two core functions—
create_payment_requestandawait_settlement. - Line 5-10:
create_payment_request()takes an amount in Vietnamese Dong (VND), a description, and your merchant account number. It returns a dict with a uniquecheckout_urland QR code. - Line 17: Send the checkout URL to your customer via SMS, email, or display it in your chat interface.
- Line 21-22:
await_settlement()blocks your agent's execution until the payment is confirmed by your bank. Thetimeout_secondsprevents infinite waiting. - Line 24-31: Once settlement is confirmed, you have full payment details. Now you can unlock content, send an invoice, or trigger fulfillment.
Step 3: Integrate with Your AI Agent
Here's how to add checkout as a tool in your agent:
import anthropic
from agentpay_vn import create_payment_request, await_settlement
import json
# Initialize Claude with tools
client = anthropic.Anthropic()
# Define checkout as a tool
tools = [
{
"name": "create_checkout",
"description": "Generate a VietQR payment link for the customer to scan",
"input_schema": {
"type": "object",
"properties": {
"amount": {
"type": "integer",
"description": "Amount in VND (e.g., 250000 for 250k)"
},
"description": {
"type": "string",
"description": "What the customer is buying (course, product, service)"
}
},
"required": ["amount", "description"]
}
}
]
# Agent conversation loop
messages = [
{"role": "user", "content": "I want to buy the Advanced AI course. How much?"}
]
while True:
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
tools=tools,
messages=messages
)
# Check if Claude wants to call the checkout tool
if response.stop_reason == "tool_use":
for block in response.content:
if block.type == "tool_use" and block.name == "create_checkout":
# Extract parameters
amount = block.input["amount"]
description = block.input["description"]
# Create payment request
payment = create_payment_request(
amount=amount,
description=description,
merchant_account="0711000123456789"
)
# Simulate payment confirmation (in production, use async tasks)
settlement = await_settlement(payment['request_id'])
# Return result to Claude
messages.append({"role": "assistant", "content": response.content})
messages.append({
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": block.id,
"content": json.dumps({
"checkout_url": payment['checkout_url'],
"status": "payment_created"
})
}
]
})
else:
# Claude finished responding
print(response.content[0].text)
break
This agent can now: 1. Understand the customer's purchase intent 2. Calculate the right amount 3. Generate a checkout URL 4. Communicate the payment link back to the user
Step 4: Use AgentPay VN with Claude via MCP
For the cleanest integration, use AgentPay VN's MCP server. Add this to your Claude configuration:
{
"mcpServers": {
"agentpay-vn": {
"command": "python",
"args": ["-m", "agentpay_mcp"],
"env": {
"AGENTPAY_MERCHANT_ACCOUNT": "0711000123456789",
"AGENTPAY_BANK_FEED_URL": "https://your-bank-api.com/feed"
}
}
}
}
Now Claude can call create_payment_request and await_settlement directly without explicit tool definitions. The MCP server abstracts all the complexity.
Real-World Example: An Online Course Bot
Imagine you're selling a course on "Building AI Agents for Business." A customer finds your chatbot on Telegram:
Customer: "How much for the full course?"
Bot (Claude): "The complete course is 499,000 VND. It includes 12 modules, lifetime access, and weekly Q&A sessions. Would you like to buy now?"
Customer: "Yes, let's do it."
Bot calls create_payment_request(amount=499000, description="AI Agents Full Course")
Bot responds: "Perfect! Click here to pay: [checkout link]. Or scan this QR code with your banking app."
Customer scans → confirms payment in their bank app → settlement detected
Bot calls await_settlement() → receives confirmation
Bot: "✓ Payment received! Your course access is ready. Check your email for the login link."
Flow duration: 60-90 seconds. Zero manual work.
Do's and Don'ts
| ✓ Do | ✗ Don't |
|---|---|
Store the request_id for reconciliation |
Assume payment without calling await_settlement() |
| Use different amounts for different products | Hardcode merchant account in production code |
Set reasonable timeout_seconds (300-600) |
Create multiple requests for the same order |
| Log settlement confirmations to your database | Try to refund via AgentPay (contact your bank) |
| Test with small amounts first (1,000 VND) | Expose your merchant account number in frontend code |
Use async tasks for await_settlement() in production |
Ignore bank feed notifications for verification |
Advanced Tips
1. Async Settlement Waiting
For production agents, don't block on await_settlement(). Use task queues:
import asyncio
async def process_payment_async(amount, description):
payment = create_payment_request(amount, description, merchant_account)
# Fire and forget—check status later
asyncio.create_task(
wait_and_fulfill(payment['request_id'])
)
return {"status": "pending", "checkout_url": payment['checkout_url']}
async def wait_and_fulfill(request_id):
settlement = await_settlement(request_id, timeout_seconds=3600)
if settlement['status'] == 'confirmed':
# Send email, unlock content, etc.
fulfill_order(request_id)
2. Bank Feed Integration
AgentPay VN confirms payments via your bank's transaction feed. Set this up with your bank's API:
def verify_settlement_via_bank(transaction_id, amount):
"""Cross-check with your bank's API"""
bank_txn = bank_api.get_transaction(transaction_id)
return bank_txn['amount'] == amount and bank_txn['status'] == 'completed'
3. Idempotency
Store request_id keyed by customer + product to prevent duplicate charges:
from datetime import datetime, timedelta
# In your database
class PaymentRequest:
request_id: str
customer_id: str
amount: int
created_at: datetime
@classmethod
def get_or_create(cls, customer_id, amount, description):
# Avoid duplicate requests within 5 minutes
existing = cls.query(
customer_id=customer_id,
amount=amount,
created_at__gte=datetime.now() - timedelta(minutes=5)
)
if existing:
return existing[0]
payment = create_payment_request(amount, description, ...)
cls.create(request_id=payment['request_id'], customer_id=customer_id)
return payment
FAQ
Q: Does AgentPay VN hold my money? No. The QR code points directly to your merchant bank account. Settlement happens through your bank's standard transaction process. AgentPay VN only manages the request lifecycle, not funds.
Q: What if a customer's payment fails?
The await_settlement() call will timeout (or return a failed status). You can then offer to retry. The customer's bank will show the failed transaction, and they can try again immediately.
Q: Can I refund customers? AgentPay VN doesn't handle refunds—that's between you and your bank. Once settled, contact your bank to issue a refund like you would for any other transaction.
Q: What VietQR banks are supported? VietQR works with all Vietnamese banks and e-wallets (Vietcombank, Agribank, Techcombank, Momo, Zalopay, etc.). Your customers can use any banking app they prefer.
Key Takeaways
- AgentPay VN is 3 functions:
create_payment_request()→ send checkout URL →await_settlement()confirms. - Installation is instant:
pip install agentpay-vnand you're ready to add payments to any agent. - No payment holding: Money flows directly to your bank account; AgentPay VN just orchestrates the request.
- MCP integration with Claude makes it seamless—Claude can call payment tools natively.
- Open-source (MIT): Audit the code, fork it, adapt it to your needs. Full transparency.
- Real-world use cases: course sales, food delivery orders, consulting bookings, SaaS trials—any agent that needs to close transactions.
- Settlement is fast: Most VietQR payments confirm within 30-60 seconds. Your agent can deliver instantly.
Get Started Now
You now have everything you need to add checkout to your AI agent. Here's your next step:
-
Install AgentPay VN:
bash pip install agentpay-vn -
Explore the full SDK and examples: GitHub: github.com/phuocdu/agentpay-vn
-
Read detailed API docs: AgentPay VN Documentation
-
Test with a small amount (1,000 VND) to see the flow end-to-end.
Your AI agent is now ready to accept real payments. Build something great.