VietQR Payment Automation for AI Agents

2026-09-15 · AgentPay VN

vietqrpayment automationai agentspython sdkvietnam

The Problem: Why Vietnamese Businesses Need Local Payment Solutions

Imagine you're running an AI-powered course marketplace in Ho Chi Minh City. A student completes their enrollment flow, clicks "Pay Now," and your agent needs to collect payment instantly. You reach for Stripe—the obvious choice—but here's what happens: high international fees (2.9% + $0.30), compliance friction with US regulations, and a 7-10 day settlement cycle that delays your cash flow.

Now imagine if your AI agent could generate a VietQR code pointing directly at your business bank account, settle funds in hours, and collect payments without ever touching the money itself. That's AgentPay VN.

This isn't just cost optimization. It's about building payment systems that think like your customers—local, fast, and trustworthy.

What Is AgentPay VN?

AgentPay VN is an open-source Python SDK (MIT license) that enables AI agents to request and verify VietQR payments without holding funds. Here's the architecture:

Install it in seconds: pip install agentpay-vn. Run the MCP server for Claude: agentpay-mcp.

Real-World Use Case: An AI Course Sales Bot

Let's walk through a concrete scenario. You've built an AI agent that helps students find courses, answer questions, and guide them to checkout. Here's the payment flow:

  1. Student says: "I want to enroll in the Python for Data Science course (₫1,500,000)."
  2. Agent creates payment request → gets a checkout URL with embedded VietQR code.
  3. Student scans QR → payment goes directly to your Vietcombank account.
  4. Within 30 seconds, a bank webhook confirms settlement.
  5. Agent verifies payment → unlocks course access, sends welcome email.

Total latency: under 2 minutes. Cost: ~0.5% (bank fee), not 3.2%. Settlement: next business day, not next week.

Step 1: Installation & Setup

Install the SDK

pip install agentpay-vn

Install the MCP Server (for Claude)

pip install agentpay-mcp

Configure Your Merchant Account

You'll need: - Merchant ID: issued by AgentPay VN (apply via dashboard) - Bank Account: any Vietnamese bank (VCB, TPB, MB, etc.) - Webhook Secret: for verifying settlement callbacks

Store these as environment variables:

export AGENTPAY_MERCHANT_ID="your_merchant_id"
export AGENTPAY_API_KEY="your_api_key"
export AGENTPAY_WEBHOOK_SECRET="your_webhook_secret"

Step 2: Creating Your First Payment Request

Here's a complete Python example:

from agentpay_vn import AgentPayClient
import os

# Initialize client
client = AgentPayClient(
    merchant_id=os.getenv("AGENTPAY_MERCHANT_ID"),
    api_key=os.getenv("AGENTPAY_API_KEY")
)

# Create a payment request
payment = client.create_payment_request(
    amount=1_500_000,              # VND amount
    order_id="COURSE_001_2024",   # your unique order ID
    description="Python Data Science Course",
    customer_name="Nguyen Van A",
    customer_phone="0901234567",
    expiry_minutes=30              # QR expires in 30 minutes
)

# Response structure:
print(f"Payment ID: {payment['id']}")
print(f"Amount: {payment['amount']:,} VND")
print(f"QR Code URL: {payment['qr_code_url']}")
print(f"Checkout URL: {payment['checkout_url']}")
print(f"Status: {payment['status']}")  # 'pending'

What's happening here: - amount: in VND (₫1,500,000 for a course) - order_id: your internal reference (must be unique per merchant) - expiry_minutes: QR code validity window - Response includes a checkout_url you send to the customer

Step 3: Waiting for Settlement

After the customer pays, your agent needs to verify settlement. Here are two approaches:

Approach A: Polling (Simpler)

import time
from agentpay_vn import PaymentStatus

# Create payment (from above)
payment = client.create_payment_request(...)
payment_id = payment['id']

# Poll for settlement (check every 5 seconds)
max_polls = 120  # 10 minutes total
for i in range(max_polls):
    status = client.get_payment_status(payment_id)

    if status['status'] == PaymentStatus.SETTLED:
        print(f"✓ Payment settled! Amount: {status['amount']:,} VND")
        # Unlock course access here
        break
    elif status['status'] == PaymentStatus.EXPIRED:
        print("✗ QR code expired without payment")
        break
    elif status['status'] == PaymentStatus.FAILED:
        print(f"✗ Payment failed: {status['error_reason']}")
        break

    time.sleep(5)  # Wait 5 seconds before checking again
    remaining = max_polls - i
    print(f"Waiting for settlement... ({remaining} polls left)")

Set up a webhook endpoint to receive instant settlement notifications:

from flask import Flask, request, jsonify
import hmac
import hashlib

app = Flask(__name__)
WEBHOOK_SECRET = os.getenv("AGENTPAY_WEBHOOK_SECRET")

@app.route('/webhooks/agentpay', methods=['POST'])
def handle_settlement():
    # Verify webhook signature
    signature = request.headers.get('X-AgentPay-Signature')
    payload = request.get_data()

    expected_sig = hmac.new(
        WEBHOOK_SECRET.encode(),
        payload,
        hashlib.sha256
    ).hexdigest()

    if signature != expected_sig:
        return jsonify({'error': 'Invalid signature'}), 401

    # Parse settlement event
    event = request.json

    if event['type'] == 'payment.settled':
        payment_id = event['data']['payment_id']
        amount = event['data']['amount']
        order_id = event['data']['order_id']

        # Unlock course access immediately
        print(f"✓ Payment {payment_id} settled for {amount:,} VND")
        unlock_course(order_id)

        return jsonify({'status': 'ok'}), 200

    return jsonify({'status': 'ignored'}), 200

Step 4: Integrating with Claude (MCP Server)

Want Claude to create payment requests on behalf of your customers? Use the MCP server:

MCP Configuration (JSON)

{
  "mcpServers": {
    "agentpay": {
      "command": "agentpay-mcp",
      "env": {
        "AGENTPAY_MERCHANT_ID": "your_merchant_id",
        "AGENTPAY_API_KEY": "your_api_key",
        "AGENTPAY_WEBHOOK_SECRET": "your_webhook_secret"
      }
    }
  }
}

Now Claude has access to tools like: - create_payment_request → returns checkout_url - check_payment_status → returns payment status - list_recent_payments → audit trail

Example Claude Conversation

User: "I want to buy the advanced Python course."

Claude: "Perfect! The course costs ₫2,500,000. Let me create a payment request for you."

Claude calls create_payment_request

Claude: "Here's your checkout link: [link]. Scan the VietQR code, and your access will unlock instantly after payment."

Advanced Tips: Scaling Payment Automation

Idempotency Keys

Prevent duplicate charges if your agent retries:

import uuid

payment = client.create_payment_request(
    amount=1_500_000,
    order_id="COURSE_001_2024",
    idempotency_key=str(uuid.uuid4())  # Ensures one charge per key
)

Batch Reconciliation

For high-volume merchants (100+ payments/day), reconcile with your bank feed:

# Get all settled payments from the past 24 hours
settled = client.list_payments(
    status='settled',
    start_date='2024-01-20',
    end_date='2024-01-21'
)

print(f"Settled: {len(settled)} transactions")
print(f"Total: {sum(p['amount'] for p in settled):,} VND")

Error Handling & Retries

from agentpay_vn.exceptions import PaymentExpired, NetworkError
import time

for attempt in range(3):
    try:
        payment = client.create_payment_request(...)
        break
    except NetworkError:
        if attempt < 2:
            time.sleep(2 ** attempt)  # Exponential backoff
        else:
            raise

AgentPay VN vs. Stripe: A Comparison

Feature AgentPay VN Stripe
Setup Time 5 minutes 1-2 days (KYC)
Settlement Fee 0.5% (bank) 2.9% + $0.30
Settlement Time Next business day 2-7 days
Funds Custody None (direct to bank) Stripe holds funds
Vietnam Optimized ✓ VietQR native ✗ International focus
Compliance Local regulations US-centric
AI Agent Tools ✓ MCP server Limited
Open Source ✓ MIT ✗ Proprietary

Common Questions

Q: Do I need to apply for anything to use AgentPay VN?

A: Yes, but it's simple. You need a Vietnamese bank account and a merchant ID. Apply on the dashboard at https://agentpay.servicesai.vn/v1/docs. Approval typically takes 24 hours.

Q: What if a customer's payment fails?

A: The QR code will show as expired after 30 minutes (configurable). Your agent can create a new payment request and resend the link. No charges occur until the customer successfully scans and completes the transfer.

Q: Can I accept payments in USD or other currencies?

A: Currently, AgentPay VN operates in VND only. For international customers, display an exchange rate (e.g., $50 USD ≈ ₫1,250,000 VND) and have them pay in VND.

Q: What if my webhook endpoint goes down?

A: Use polling as a fallback. AgentPay stores payment status permanently, so you can query the API even hours later. The webhook is just faster for real-time unlocking.

Key Takeaways

Next Steps

  1. Install AgentPay VN: pip install agentpay-vn
  2. Apply for a merchant account: https://agentpay.servicesai.vn/v1/docs
  3. Read the full docs: API Reference & Examples
  4. Explore the source code: GitHub: phuocdu/agentpay-vn
  5. Deploy your first agent: Start with a webhook listener and polling fallback; scale to batch reconciliation.

Your AI agents deserve payment infrastructure built for Vietnam—fast, local, and completely transparent. AgentPay VN is here.

Get started →

← All posts