VietQR Payment Automation for AI Agents

2026-08-01 · AgentPay VN

vietqrpayment-automationpython-sdkai-agentsvietnam

The Problem: AI Agents Need Local Payment Rails

You've built a clever AI chatbot that helps Vietnamese small businesses book appointments, sell courses, or take food orders. Your agent works beautifully—it chats, it understands intent, it closes deals. But then comes the awkward moment: how do you collect payment?

Stripe doesn't support VietQR. PayPal has spotty coverage. You're left scrambling with legacy payment gateways, manual bank transfers, or building fragile integrations that break every quarter. Meanwhile, your users expect instant checkout links they can scan with their phone—the Vietnamese standard.

This is where AgentPay VN changes the game. It's an open-source Python SDK that lets your AI agents generate VietQR codes, send checkout links, and confirm settlement—all without touching customer money. The QR points straight at your merchant's bank account.

What Is AgentPay VN?

AgentPay VN is a lightweight, MIT-licensed Python library + MCP server that bridges AI agents and VietQR payments. Think of it as a payment conductor for agents:

The beauty is simplicity. Three steps. No merchant accounts. No days-long approval processes. Your agent creates a payment request, sends the checkout URL, then waits for settlement confirmation. That's it.

The Three-Step Payment Flow

Step 1: Create a Payment Request

Your agent gathers the sale details and asks AgentPay to mint a VietQR code.

Step 2: Send the Checkout URL

The agent shares the QR or link with the customer. They scan, they pay via their bank app. Simple.

Step 3: Await Settlement

Your system polls for confirmation that the payment landed in your account. When it does, deliver the service.

Getting Started: Installation & Configuration

Install the SDK in seconds:

pip install agentpay-vn

Then initialize it with your merchant details:

from agentpay_vn import AgentPayClient

# Set up the client with your VietQR account
client = AgentPayClient(
    merchant_id="your_merchant_id",
    api_key="your_api_key",
    bank_account="123456789",  # Your bank account for VietQR
    bank_code="970012"  # VIETCOMBANK code example
)

Grab your credentials from the AgentPay VN dashboard.

Building Your First Payment Agent: A Course-Selling Bot

Let's walk through a concrete example: an AI agent that sells online courses.

The Scenario

Nguyen runs a Python programming course. His Discord bot helps students ask questions, and when they're ready to buy, the agent should: 1. Confirm the course ($29 USD ≈ 740,000 VND) 2. Generate a VietQR code 3. Send it to the student 4. Wait for payment confirmation 5. Grant course access

The Code

from agentpay_vn import AgentPayClient
import asyncio
import time

# Initialize client
client = AgentPayClient(
    merchant_id="course_shop_001",
    api_key="sk_live_abc123xyz",
    bank_account="0123456789",
    bank_code="970012"
)

async def sell_course_to_student(student_name: str, course_id: str, price_vnd: int):
    """
    End-to-end course sale with VietQR payment.
    """

    # Step 1: Create the payment request
    payment_request = await client.create_payment_request(
        amount=price_vnd,
        description=f"Python Course - {course_id}",
        metadata={
            "student": student_name,
            "course": course_id,
            "type": "course_purchase"
        }
    )

    # payment_request contains:
    # - qr_code_url: The QR image to display
    # - checkout_url: Direct link for mobile (easier than scanning)
    # - request_id: Unique reference for this transaction

    print(f"💰 {student_name}, scan this QR or visit: {payment_request['checkout_url']}")

    # Step 2: Store the request ID for settlement checking
    request_id = payment_request["request_id"]

    # Step 3: Poll for settlement (in production, use webhooks)
    settled = False
    timeout_seconds = 600  # Wait up to 10 minutes
    poll_interval = 5
    elapsed = 0

    while not settled and elapsed < timeout_seconds:
        settlement = await client.await_settlement(
            request_id=request_id,
            timeout=poll_interval
        )

        if settlement["status"] == "settled":
            settled = True
            print(f"✅ Payment received! {settlement['amount']} VND")
            # Grant course access here
            await grant_course_access(student_name, course_id)
        else:
            elapsed += poll_interval
            time.sleep(poll_interval)

    if not settled:
        print(f"⏱️ Payment timeout. Student can retry.")
        return False

    return True

async def grant_course_access(student_name: str, course_id: str):
    """
    Your business logic: activate course, send credentials, etc.
    """
    print(f"🎓 Course {course_id} unlocked for {student_name}!")
    # Send course materials, activate account, etc.

# Usage:
await sell_course_to_student(
    student_name="Tran Minh Duc",
    course_id="PYTHON-101",
    price_vnd=740000
)

What's Happening Here?

  1. create_payment_request() generates a unique VietQR code pointing to your bank account. The amount is embedded in the QR, so no manual typing.
  2. await_settlement() checks your bank feed (via your bank's API) to confirm the payment arrived. When it does, the agent instantly delivers.
  3. Metadata tags the transaction so you know which student, which course, for accounting/analytics.

Integrating with Claude: MCP Server

If you want Claude or another LLM to directly call VietQR functions, use the MCP server:

{
  "mcpServers": {
    "agentpay": {
      "command": "agentpay-mcp",
      "args": [
        "--merchant-id", "your_merchant_id",
        "--api-key", "your_api_key",
        "--bank-account", "0123456789",
        "--bank-code", "970012"
      ]
    }
  }
}

Now in your Claude conversation, it can call: - agentpay:create_payment_request → Generates VietQR - agentpay:check_settlement → Confirms payment - agentpay:list_transactions → Reports

This is powerful for agents that need autonomy. Claude can decide mid-conversation to charge for a premium feature without your code calling it explicitly.

Real-World Example: Tiny Café Loyalty Bot

The Setup

A café in Hanoi has a Telegram bot. Regulars order coffee, chat with the bot, and want to prepay a "loyalty card" (e.g., ₫200,000 for 10 drinks).

Old way: Café owner manually sends bank details, waits for confirmation screenshots, manually unlocks cards. Slow, error-prone, no automation.

New way (AgentPay VN):

  1. Customer types /buy_card 10_drinks in Telegram
  2. Bot calls create_payment_request(amount=200000, description="10-drink card")
  3. Bot sends QR and checkout URL
  4. Customer scans, pays via bank app (2 seconds)
  5. Bot detects settlement, issues card code instantly
  6. Next visit, customer scans card barcode, gets their 10th drink free

Result: Zero manual work, zero settlement delays, 100% customer delight.

Best Practices & Do's/Don'ts

Do Don't
Store request IDs for reconciliation Try to handle money yourself (use webhooks for settlement confirmation)
Use metadata to tag transactions by user/product Poll for settlement more than every 5 seconds (wastes API calls)
Set reasonable timeouts (5–10 min for consumer, 1 hour for B2B) Hardcode merchant credentials—use environment variables
Test with small amounts first Assume bank feeds are instant (usually 10–30 seconds)
Monitor settlement failures and retry gracefully Forget to handle network timeouts

Advanced Tips

Webhook Confirmations (Production)

Instead of polling, listen for payment webhooks:

from fastapi import FastAPI, Request

app = FastAPI()

@app.post("/agentpay/webhook")
async def handle_settlement(payload: Request):
    data = await payload.json()

    # data["request_id"] identifies the transaction
    # data["status"] is "settled" or "failed"
    # data["amount"] is the VND amount

    if data["status"] == "settled":
        await grant_course_access(data["student"], data["course"])

    return {"ok": True}

Configure webhooks in your AgentPay dashboard.

Bulk Transfers & Reconciliation

For high-volume scenarios (restaurant, e-commerce), batch settle to a secondary account:

bulk_settlement = await client.bulk_settle(
    request_ids=["req_001", "req_002", "req_003"],
    destination_account="1111111111",  # Optional redistribution
    reference="daily_settlement_2024_01_15"
)

Currency Handling

AgentPay VN works in VND. For USD pricing, convert at checkout:

import requests

def usd_to_vnd(usd_amount: float) -> int:
    """Fetch live FX rate, convert to VND."""
    rate = requests.get("https://api.exchangerate.org/rates/USD").json()["rates"]["VND"]
    return int(usd_amount * rate)

price_vnd = usd_to_vnd(29)  # $29 USD → ~740,000 VND

Comparison: AgentPay VN vs. Alternatives

Feature AgentPay VN Stripe Paypal Bank Transfer
VietQR Support ✅ Native ❌ No ⚠️ Limited ✅ Manual
AI Agent Integration ✅ MCP ⚠️ Custom ⚠️ Custom ❌ No
Settlement Speed 10–30s 1–3 days 1–3 days 0–24h
Monthly Fee $0 2.9% + $0.30 1.99% + $0.49 $0
Code Complexity ~10 lines 50+ lines 50+ lines Manual
Funds Touch Gateway No Yes Yes No

FAQ

Q: Does AgentPay hold my money? No. The VietQR code points directly to your merchant bank account. AgentPay is a conductor, not a vault. Settlement confirmation comes from your bank's feed.

Q: What if payment fails or times out? Your agent can catch SettlementTimeoutException and retry, send a new QR, or ask the user to try again. No penalty.

Q: Can I use this with payment plans (e.g., installments)? Currently, AgentPay VN handles one-off payments. For installments, you'll need to create multiple requests (one per payment) and track them by metadata.

Q: Is there a webhook delay if my bank is slow? Bank settlement feeds vary (usually 10–30 seconds for major banks). We recommend a 30-second polling fallback in development, but use webhooks in production for reliability.

Key Takeaways

Next Steps

  1. Install the SDK (30 seconds): bash pip install agentpay-vn

  2. Get your API key from agentpay.servicesai.vn/v1/docs

  3. Clone the example bot from GitHub and adapt it to your use case.

  4. Read the full docs for webhooks, bulk settle, error handling, and advanced features.

  5. Test with a small payment (e.g., ₫10,000) to see the flow in action.

Your AI agents deserve payment infrastructure as smart as they are. AgentPay VN makes that real.

Get started →

← All posts