Sell Digital Products from AI Chatbots Without Holding Funds
The Problem: Why Most AI Commerce Solutions Fall Short
Imagine you've built a brilliant AI chatbot that sells online courses, digital templates, or API access. Your bot engages customers beautifully, answers their questions in Vietnamese, and closes sales effortlessly. But then reality hits: every payment processor wants to either hold your money for 7–30 days, charge you 3–5% per transaction, or force you through a lengthy merchant onboarding that takes weeks.
Worse, many solutions require you to hold customer funds temporarily—creating compliance headaches, potential fraud liability, and the need for a separate accounting system. Your lean AI startup wasn't built to be a fintech company.
This is where AgentPay VN changes the game. Instead of your bot playing intermediary with customer money, it orchestrates a direct payment flow: your customer scans a VietQR code, their bank processes the transfer straight to your merchant account, and a bank feed confirms settlement in real time. Your bot simply coordinates the handshake. No fund holding. No licensing overhead. No middleman friction.
What Is AgentPay VN?
AgentPay VN is an open-source Python SDK (MIT license) plus an MCP (Model Context Protocol) server that lets AI agents—Claude, custom LLMs, or autonomous bots—request and track VietQR payments. Think of it as the nervous system connecting your chatbot to Vietnam's banking infrastructure.
Key facts:
- Zero fund holding: QR codes point directly to your bank account.
- Settlement confirmation: Bank feeds verify that money actually arrived.
- Production-ready: Powers real e-commerce bots and service platforms in Vietnam.
- Easy install: pip install agentpay-vn (4 seconds) and agentpay-mcp for Claude integration.
- Open source: MIT license means you own the integration, no vendor lock-in.
The core flow is elegantly simple: create a payment request → send a checkout URL to the customer → wait for settlement confirmation. That's it. No webhooks to debug. No state machines to manage.
Setting Up AgentPay VN: A 5-Minute Quick Start
Installation
First, install the SDK in your Python environment:
pip install agentpay-vn
If you're integrating with Claude or another MCP-compatible AI agent, also install the MCP server:
pip install agentpay-mcp
Your First Payment Request
Here's a minimal example. This code creates a payment request for a customer buying a Figma template for 250,000 VND:
from agentpay_vn import PaymentClient
# Initialize the client (credentials from AgentPay dashboard)
client = PaymentClient(
api_key="your_api_key_here",
merchant_id="merchant_12345"
)
# Create a payment request
payment = client.create_payment_request(
amount_vnd=250000,
description="Figma Design System Template Pack",
order_id="order_20250115_001",
customer_email="buyer@example.com"
)
# Print the checkout URL to send to your customer
print(f"Send this link: {payment.checkout_url}")
print(f"Payment ID for tracking: {payment.payment_id}")
Line-by-line breakdown:
PaymentClient(...): Connects to AgentPay's API using your credentials. Get these from https://agentpay.servicesai.vn/v1/docs after signing up.create_payment_request(...): Generates a unique payment request. Theamount_vndis in Vietnamese Dong (no decimals). Theorder_idmust be unique per transaction; use timestamps or UUIDs to guarantee uniqueness.payment.checkout_url: A shareable link containing an embedded VietQR code. Send this via SMS, email, or display it in your chatbot interface.payment.payment_id: A reference ID for polling settlement status later.
Waiting for Settlement
Now your customer scans the QR, transfers money from their bank app, and the settlement completes in seconds (Vietnam's VietQR is instant). Your bot polls for confirmation:
import time
from agentpay_vn import SettlementStatus
# Poll for settlement (check every 5 seconds, up to 2 minutes)
payment_id = "pay_abc123xyz"
max_wait = 120 # seconds
elapsed = 0
while elapsed < max_wait:
settlement = client.await_settlement(
payment_id=payment_id,
timeout_seconds=5
)
if settlement.status == SettlementStatus.CONFIRMED:
print(f"✅ Payment received! {settlement.amount_vnd} VND")
print(f"Settlement reference: {settlement.bank_ref}")
# Deliver the digital product here
deliver_template_pack_to_email(buyer_email)
break
elif settlement.status == SettlementStatus.FAILED:
print(f"❌ Payment failed: {settlement.error_reason}")
break
elapsed += 5
else:
print("⏳ Payment still pending; customer may retry later")
Key concepts:
await_settlement(...): Blocks (or polls) until the bank feed confirms the transfer. Thetimeout_secondsprevents your bot from freezing indefinitely.SettlementStatus.CONFIRMED: Money hit your bank account. Safe to deliver the product.settlement.bank_ref: Your bank's transaction ID (useful for reconciliation and customer support).- Delivery timing: Only hand over the product after confirmation. This is non-negotiable.
Integrating with Claude via MCP
If you're using Claude (via API or Claude.dev), you can give it direct access to AgentPay VN functions through MCP. Here's a sample MCP configuration:
{
"mcpServers": {
"agentpay": {
"command": "python",
"args": ["-m", "agentpay_mcp.server"],
"env": {
"AGENTPAY_API_KEY": "your_api_key_here",
"AGENTPAY_MERCHANT_ID": "merchant_12345"
}
}
}
}
Add this to your Claude configuration file (or environment variables). Now Claude can call these MCP functions directly:
create_payment_request– Generate a checkout URL.get_payment_status– Check if payment arrived.list_recent_payments– Retrieve transaction history.
With this setup, your Claude-powered bot can say: "I've created your checkout link. Please scan the QR code and let me know once you've transferred the funds," and then automatically confirm payment without explicit user feedback.
Real-World Walkthrough: An Online Course Sales Bot
Let's build a realistic scenario: CourseBot, a Telegram chatbot that sells Python programming mini-courses in Vietnam.
The flow:
- Customer texts the bot: "Show me Python courses."
- Bot lists 3 courses (Basic: 150k VND, Intermediate: 300k VND, Advanced: 500k VND).
- Customer replies: "I want Advanced."
- Bot creates a payment request for 500,000 VND and sends the VietQR checkout link.
- Customer scans QR with their bank app, sees the payment request, and approves it.
- Their bank sends 500k VND to CourseBot's merchant account (instant settlement).
- Bot detects settlement via
await_settlement, sends a thank-you message, and delivers a download link to the course PDF + video playlist. - Bot logs the transaction for accounting.
Code sketch:
# Pseudo-code for CourseBot (Telegram)
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters
from agentpay_vn import PaymentClient
client = PaymentClient(api_key="...", merchant_id="...")
COURSES = {
"basic": {"price": 150000, "name": "Python Basics", "hours": 5},
"intermediate": {"price": 300000, "name": "OOP & APIs", "hours": 10},
"advanced": {"price": 500000, "name": "Async & ML", "hours": 20},
}
async def handle_purchase(update: Update, context):
course_key = context.args[0] # e.g., "advanced"
course = COURSES[course_key]
# Create payment request
payment = client.create_payment_request(
amount_vnd=course["price"],
description=course["name"],
order_id=f"course_{update.effective_user.id}_{int(time.time())}",
customer_email=update.effective_user.username + "@telegram.local"
)
# Send checkout link
await update.message.reply_text(
f"Khóa học {course['name']} giá {course['price']:,} VND\n"
f"Nhấn vào link để thanh toán: {payment.checkout_url}"
)
# Poll for settlement in background
settlement = client.await_settlement(
payment_id=payment.payment_id,
timeout_seconds=120
)
if settlement.status == SettlementStatus.CONFIRMED:
# Deliver course
await update.message.reply_text(
f"✅ Thanh toán thành công!\n"
f"Tài liệu của bạn: [link to course]\n"
f"Hóa đơn: {settlement.bank_ref}"
)
# Log to database
log_transaction(user_id=update.effective_user.id, course=course_key, ref=settlement.bank_ref)
else:
await update.message.reply_text("❌ Thanh toán thất bại. Vui lòng thử lại.")
app = Application.builder().token("TELEGRAM_TOKEN").build()
app.add_handler(CommandHandler("buy", handle_purchase))
app.run_polling()
In this scenario, your bot never touches the 500k VND. It just orchestrates the request and confirms settlement. Clean, simple, compliant.
Do's and Don'ts: Common Pitfalls
| Do | Don't |
|---|---|
Always wait for SettlementStatus.CONFIRMED before delivering products. |
Never deliver before settlement—you risk fraud. |
Use unique order_id for every payment request. |
Reuse order IDs; it breaks reconciliation. |
Store bank_ref for tax and reconciliation records. |
Ignore settlement references; audits will hurt. |
Set reasonable timeout_seconds (60–120s typical for VietQR). |
Use 0 timeout; your bot will freeze. |
| Test with small amounts (1,000 VND) first. | Go live without testing; customers will discover bugs. |
| Monitor API quota and rate limits. | Assume unlimited API calls; implement backoff. |
Advanced Tips: Production Hardening
1. Async/Await Pattern
For high-traffic bots, avoid blocking await_settlement. Instead, use async polling with a background job:
import asyncio
from agentpay_vn import PaymentClient
async def monitor_payment_async(payment_id: str, callback):
"""Non-blocking settlement monitor."""
for attempt in range(24): # 24 attempts = 2 minutes at 5s intervals
settlement = client.await_settlement(payment_id, timeout_seconds=5)
if settlement.status != SettlementStatus.PENDING:
await callback(settlement)
return
await asyncio.sleep(5)
await callback(None) # Timeout
# Usage in your bot
async def on_settlement(settlement):
if settlement and settlement.status == SettlementStatus.CONFIRMED:
# Deliver product
pass
await monitor_payment_async("pay_xyz", on_settlement)
2. Idempotency
Network glitches happen. Implement idempotency keys to prevent double-charging if your request retries:
payment = client.create_payment_request(
amount_vnd=500000,
order_id="order_unique_string",
idempotency_key="idempotency_12345", # Replay-safe
description="Advanced Python Course"
)
3. Reconciliation
Daily, compare your local orders table with AgentPay's settlement logs:
# Fetch all settlements from the last 24 hours
settlements = client.list_settlements(days_back=1)
for s in settlements:
# Verify against your database
local_order = db.query(Order).filter_by(order_id=s.order_id).first()
if local_order and local_order.status != "delivered":
log_warning(f"Settled but not delivered: {s.order_id}")
Frequently Asked Questions
Q: What if the customer's bank transfer fails?
A: AgentPay's bank feed will detect the failure, and await_settlement returns SettlementStatus.FAILED with an error reason (insufficient funds, wrong account, etc.). Your bot can then retry or refund instructions.
Q: Can I use AgentPay VN outside Vietnam?
A: VietQR is Vietnam-only (it's tied to Vietnamese banks). However, AgentPay VN is designed for Vietnamese merchants and customers. If you're in the diaspora, it still works if your bank is Vietnamese.
Q: How do fees work?
A: AgentPay VN is open-source and MIT-licensed—it's free to integrate. Your bank (who receives the VietQR transfer) may charge a standard transfer fee (usually 0–1,000 VND per transaction), but that's their standard policy, not AgentPay's markup.
Q: How long does settlement take?
A: VietQR transfers settle instantly (within seconds). Your bank feed confirms it in near real-time. Total latency: < 10 seconds typically.
Key Takeaways
- AgentPay VN eliminates the intermediary cost model. Your bot requests payment; customers pay directly to your bank; you keep 100% minus bank fees.
- Zero fund holding means zero compliance headaches. You're not a fintech; you're just a facilitator.
- The 3-line flow (
create_payment_request→checkout_url→await_settlement) is production-ready. You can build a real e-commerce bot in an afternoon. - MCP integration with Claude makes AI agents payment-aware. Your chatbot can upsell, track orders, and deliver digital goods autonomously.
- Test thoroughly with small amounts before scaling. VietQR is reliable, but your integration needs testing.
- Store
bank_reffor every transaction. Tax and compliance require audit trails.
Get Started Now
You're 4 minutes away from a fully functional AI payment bot:
- Install:
pip install agentpay-vn - Sign up: Visit https://agentpay.servicesai.vn/v1/docs to create an account and get your API key.
- Copy the code examples above into your Python bot (Telegram, Discord, FastAPI, whatever).
- Test with 1,000 VND to verify the flow.
- Deploy and start selling.
The code is open-source, the integration is free, and your first payment can land in your bank account within minutes. No vendor lock-in. No hidden fees. Just you, your customers, and their money flowing directly to your account.
For detailed API docs, example projects, and troubleshooting, head to https://github.com/phuocdu/agentpay-vn and https://agentpay.servicesai.vn/v1/docs.
Happy selling. 🚀