VietQR Payment Automation for AI Agents

2026-07-23 · AgentPay VN

vietqrai-agentspayment-automationvietnammcp

The Problem: Why Your AI Agent Can't Take Vietnamese Payments Today

Imagine you've built a brilliant AI chatbot that tutors Vietnamese students in English. It's trained, deployed, and users love it. But the moment someone asks, "How do I pay you?" — you hit a wall.

Stripe doesn't support Vietnamese VietQR codes. PayPal withdrawals in Vietnam carry 25% fees. You're left building clunky bank transfer workflows or manually processing payments via bank apps. Your AI agent, capable of managing complex conversations, suddenly can't handle a simple transaction.

This is the reality for thousands of Vietnamese software founders, agency owners, and AI developers. Payment infrastructure designed for Western markets fails to account for Vietnam's unique banking landscape, where VietQR — a unified QR payment standard — dominates and connects directly to 44+ banks.

Until now, there was no straightforward way to let AI agents initiate VietQR payments programmatically. AgentPay VN changes that.

What Is AgentPay VN? A Payment Bridge for AI

AgentPay VN is an open-source Python SDK (MIT license) and Model Context Protocol (MCP) server that enables AI agents to create and settle VietQR payments without ever holding funds. The architecture is beautifully simple:

  1. Your AI agent calls create_payment_request()
  2. A QR code is generated pointing directly to the merchant's bank account
  3. The customer scans and pays via their banking app
  4. A bank feed confirms settlement in real-time

No intermediary wallet. No escrow. No daily settlement delays. Money flows from customer bank → merchant bank in seconds, and your agent knows about it immediately.

The SDK is lightweight (installable in 10 seconds), the MCP server integrates with Claude and other AI platforms, and the entire codebase is auditable on GitHub — crucial for handling money.

Installation & Setup: Get Running in 5 Minutes

Step 1: Install the SDK

pip install agentpay-vn

This installs the core library with zero production dependencies. The package is 4 MB and installs in under 5 seconds on any Python 3.8+ environment.

Step 2: Configure Your Merchant Account

AgentPay VN doesn't require account creation — it works with your existing Vietnamese bank account. You'll need:

Step 3: Initialize the Client

from agentpay_vn import AgentPayClient

client = AgentPayClient(
    bank_account="1234567890",
    bank_code="970033",  # Techcombank
    account_name="Your Business Name"
)

That's it. No API keys, no OAuth flows. Your merchant identity is tied to your real bank account, which is why the security model is so robust — the system can't pay anyone except you.

The Core Flow: 3 Lines of Agent Logic

Let's walk through how an AI agent would handle a payment from start to finish.

Creating a Payment Request

from agentpay_vn import AgentPayClient
from datetime import datetime, timedelta

client = AgentPayClient(
    bank_account="1234567890",
    bank_code="970033",
    account_name="AI Tutoring Platform"
)

# Step 1: Customer requests a course (your AI agent logic)
course_price = 299000  # VND
customer_name = "Nguyen Van A"
customer_phone = "0912345678"

# Step 2: Create payment request
payment = client.create_payment_request(
    amount=course_price,
    description=f"English Course - {customer_name}",
    reference_id=f"COURSE_001_{datetime.now().timestamp()}",
    customer_name=customer_name,
    customer_phone=customer_phone,
    expires_at=datetime.now() + timedelta(hours=1)  # 1-hour payment window
)

# Step 3: Get the QR code URL and send to customer
checkout_url = payment['checkout_url']
qr_code = payment['qr_code']  # PNG as base64

print(f"Send this to customer: {checkout_url}")
print(f"Or display QR code: {qr_code}")

What's happening here:

The returned checkout_url is a one-time link the customer can open on mobile or desktop. They see a branded checkout, scan/tap the VietQR code, and complete payment in their banking app in 5 seconds.

Awaiting Settlement Confirmation

import asyncio
from agentpay_vn import AgentPayClient

client = AgentPayClient(
    bank_account="1234567890",
    bank_code="970033",
    account_name="AI Tutoring Platform"
)

async def wait_for_payment(reference_id: str, timeout_seconds: int = 300):
    """Poll for payment settlement (typical wait: 3-15 seconds)"""

    try:
        settlement = await client.await_settlement(
            reference_id=reference_id,
            timeout=timeout_seconds  # Default 5 minutes
        )

        if settlement['status'] == 'confirmed':
            print(f"✅ Payment received: {settlement['amount']} VND")
            print(f"   Transaction ID: {settlement['txn_id']}")
            print(f"   Settled at: {settlement['settled_at']}")

            # Your agent continues here: unlock course, send receipt, etc.
            return True

        elif settlement['status'] == 'failed':
            print(f"❌ Payment failed: {settlement['error_reason']}")
            return False

    except asyncio.TimeoutError:
        print("⏱️ Payment window expired — customer didn't complete payment")
        return False

# Usage
result = asyncio.run(wait_for_payment(reference_id="COURSE_001_1699564800"))

Key details:

Real-World Walkthrough: An AI Tutoring Bot

Let's build a complete scenario: a ChatGPT-like AI that sells English conversation courses to Vietnamese users.

Flow:

  1. User opens the bot and asks to buy the "Intermediate Conversation" course (₫299,000)
  2. AI agent greets them, confirms the purchase, and initiates a payment request
  3. QR code appears in the chat
  4. User scans with their banking app (ACB, Techcombank, Vietinbank, etc.)
  5. Payment completes in 8 seconds
  6. Agent immediately sends a receipt, unlocks course materials, and invites them to a live session

Agent code (simplified):

from agentpay_vn import AgentPayClient
import asyncio

class TutoringBot:
    def __init__(self):
        self.client = AgentPayClient(
            bank_account="9876543210",
            bank_code="970407",  # Vietinbank
            account_name="AI English Academy"
        )

    async def handle_purchase(self, user_id: str, course: str):
        # Prices in VND
        courses = {
            "beginner": 199000,
            "intermediate": 299000,
            "advanced": 499000
        }

        price = courses.get(course)
        if not price:
            return f"Course '{course}' not found."

        # Create payment
        payment = self.client.create_payment_request(
            amount=price,
            description=f"{course.title()} English Course",
            reference_id=f"TUTOR_{user_id}_{int(time.time())}",
            customer_name=user_id,
            expires_at=datetime.now() + timedelta(hours=2)
        )

        # Send checkout link to user
        msg = f"📚 **{course.title()} Course** – ₫{price:,}\n"
        msg += f"Click here to pay: {payment['checkout_url']}\n"
        msg += f"Or scan the QR code below.\n"

        # Wait for settlement
        settled = await self.client.await_settlement(
            reference_id=payment['reference_id'],
            timeout=600  # 10 minutes
        )

        if settled['status'] == 'confirmed':
            return f"✅ Payment confirmed! Access to {course} course unlocked. Welcome! 🎉"
        else:
            return f"❌ Payment cancelled or failed. Please try again."

This is production-ready. Your AI agent now handles the entire transaction lifecycle without any manual intervention.

Using AgentPay VN with Claude via MCP

If you're building Claude agents (via Claude API or through platforms like Anthropic's Console), you can expose AgentPay VN as a tool via the Model Context Protocol.

MCP Server Configuration (for Claude):

{
  "mcpServers": {
    "agentpay": {
      "command": "agentpay-mcp",
      "args": [],
      "env": {
        "AGENTPAY_BANK_ACCOUNT": "1234567890",
        "AGENTPAY_BANK_CODE": "970033",
        "AGENTPAY_ACCOUNT_NAME": "My Business",
        "AGENTPAY_WEBHOOK_SECRET": "optional-for-async-webhooks"
      }
    }
  }
}

Once configured, Claude automatically gains access to these MCP tools:

Claude can now autonomously decide when to ask for payment, generate checkout links, and confirm transactions. For instance:

User: "I want to buy the premium AI coaching package."

Claude (via MCP): Creates a payment request → sends QR → waits for settlement → "Great! Your premium access is now active. Let's start with your first session."

This is frictionless from the user's perspective and completely autonomous from the developer's.

Best Practices & Common Pitfalls

Do Don't
Use reference_id as your internal order ID for idempotency Reuse the same reference_id across multiple customers
Set expires_at for time-sensitive offers Leave expires_at unset — customers may lose payment windows
Poll await_settlement() with reasonable timeouts (5–10 min) Poll indefinitely — wasted resources
Store the txn_id from settlement confirmation Assume payment succeeded without checking settlement status
Use webhooks for high-volume systems (async callbacks) Poll for every single transaction
Test with sandbox/test accounts first Go live without verifying bank details

Comparing AgentPay VN to Stripe in Vietnam

Why Stripe doesn't work here:

AgentPay VN advantages:

Trade-off: AgentPay VN is Vietnam-only; Stripe is global. For domestic Vietnamese payments, AgentPay VN is superior.

FAQ

Q: Does AgentPay VN hold my money? No. Money flows directly from customer's bank → your merchant bank account. AgentPay VN never touches the funds — it's only a QR generation and settlement confirmation service.

Q: What if a customer pays the wrong amount? VietQR codes are strict — the customer's bank app shows the exact amount before they confirm. Overpayments are rare, but if one occurs, you can refund via your bank's app like any other transaction.

Q: Is my bank account information safe? Yes. Bank account + bank code are not secret (they're on your invoice letterhead). AgentPay VN never stores credentials — it generates time-limited QR codes that your bank validates server-side.

Q: Can I integrate this with my existing e-commerce platform? Absolutely. The SDK returns a checkout_url you can embed as a button, redirect, or modal. The MCP server works with any AI platform supporting MCP (Claude, other LLMs).

Key Takeaways

Getting Started Now

Ready to add VietQR payments to your AI agent?

Install AgentPay VN:

pip install agentpay-vn

Read the full documentation: https://agentpay.servicesai.vn/v1/docs

Explore the source code on GitHub: https://github.com/phuocdu/agentpay-vn

The barrier to accepting payments in Vietnam just dropped dramatically. Your AI agent can now serve products and collect money in the same conversation — with no Stripe account, no international delays, and no intermediary risk. Build faster. Get paid faster. That's AgentPay VN.

Get started →

← All posts