Accept VietQR Payments in Python: AI Agent Tutorial

2026-06-14 · AgentPay VN

pythonvietqrai-agentspaymentsopen-source

Why VietQR Payments for AI Agents?

As AI agents increasingly handle real-world tasks, accepting payments becomes essential. Traditional payment processors add complexity: custodial wallets, transaction delays, and integration friction. AgentPay VN solves this by letting your Python-based AI agents collect payments directly to merchant bank accounts via VietQR—Vietnam's standardized QR payment format.

The key advantage: your agent never touches the money. The QR code points directly to the merchant's bank account, and settlement confirmation comes from the bank feed. This eliminates custody risk and regulatory headaches.

What is AgentPay VN?

AgentPay VN is an MIT-licensed open-source project combining:

With just three method calls, your agent can request payments, generate checkout URLs, and await settlement confirmation.

Installation & Setup

Get started in under a minute:

pip install agentpay-vn

If using the MCP server (for Claude and other MCP-compatible agents):

pip install agentpay-mcp

The 3-Line Payment Flow

AgentPay VN abstracts payment collection into three steps:

  1. create_payment_request – Initialize a payment
  2. send_checkout_url – Share the VietQR checkout with your customer
  3. await_settlement – Confirm payment from bank feed

Let's build a practical example.

Building Your First Payment Integration

Step 1: Create a Payment Request

Here's a complete Python example:

from agentpay_vn import AgentPayClient

# Initialize the client
client = AgentPayClient(
    api_key="your_api_key_here",
    merchant_id="your_merchant_id"
)

# Create a payment request
payment = client.create_payment_request(
    amount=100000,  # VND
    description="Service delivery - Order #12345",
    order_id="order_12345",
    customer_name="Nguyen Van A",
    customer_phone="0912345678"
)

print(f"Payment Request ID: {payment.id}")
print(f"Amount: {payment.amount} VND")

The create_payment_request method returns a payment object containing: - Unique payment ID (for tracking) - Amount and description - Metadata for your records

Step 2: Generate and Send the Checkout URL

Next, create a VietQR checkout URL to share with your customer:

# Generate checkout URL
checkout_url = client.send_checkout_url(
    payment_id=payment.id
)

print(f"Send this URL to customer: {checkout_url}")

# In a real agent scenario, you'd:
# - Send via email
# - Display in a web interface
# - Include in an SMS

The URL points to a VietQR QR code that customers can scan with any Vietnamese banking app.

Step 3: Await Settlement

Confirm payment once the bank processes it:

import time
from datetime import datetime

# Poll for settlement (or use webhooks in production)
max_wait_seconds = 300  # 5 minutes
start_time = datetime.now()

while (datetime.now() - start_time).total_seconds() < max_wait_seconds:
    settlement = client.await_settlement(
        payment_id=payment.id,
        timeout_seconds=10
    )

    if settlement.status == "confirmed":
        print(f"✓ Payment confirmed!")
        print(f"  Amount received: {settlement.amount} VND")
        print(f"  Settlement time: {settlement.settled_at}")
        break
    elif settlement.status == "failed":
        print(f"✗ Payment failed: {settlement.error_message}")
        break

    time.sleep(2)  # Check every 2 seconds

Using AgentPay VN with MCP (Claude Integration)

If you're building Claude-based agents, configure the MCP server:

{
  "mcpServers": {
    "agentpay": {
      "command": "python",
      "args": ["-m", "agentpay_mcp.server"],
      "env": {
        "AGENTPAY_API_KEY": "your_api_key",
        "AGENTPAY_MERCHANT_ID": "your_merchant_id"
      }
    }
  }
}

Claude can now use AgentPay tools directly in conversation:

User: "I need to request a 500,000 VND payment for invoice INV-2024-001"

Claude: I'll create that payment request for you.
[Calls: create_payment_request(amount=500000, order_id="INV-2024-001")]
Payment created. Checkout URL: https://checkout.agentpay.vn/...

Security & Trust Considerations

Non-Custodial by Design

Best Practices

  1. Store API keys securely – Use environment variables, never commit keys python import os api_key = os.getenv("AGENTPAY_API_KEY")

  2. Validate payment amounts – Ensure agent requests match expected prices python MAX_SINGLE_PAYMENT = 50_000_000 # VND if payment_amount > MAX_SINGLE_PAYMENT: raise ValueError("Payment exceeds limit")

  3. Log transactions – Track all payment activity for audits python import logging logging.info(f"Payment {payment.id} created: {payment.amount} VND")

  4. Use webhooks – Don't poll indefinitely in production python # Configure webhook endpoint in dashboard # Receive instant settlement notifications

Troubleshooting Common Issues

"API key invalid" error - Verify your API key in the AgentPay dashboard - Ensure it's set in environment variables or passed to AgentPayClient

Settlement takes too long - VietQR settlements typically confirm within 1-2 minutes - Check your bank's processing status - Review settlement logs in the dashboard

Checkout URL not generating - Confirm the payment request was created successfully - Verify merchant account is active - Check API rate limits

FAQ

Q: Does AgentPay VN charge transaction fees? A: Check the pricing page at agentpay.servicesai.vn for current rates.

Q: Can I use this with non-Vietnamese banks? A: AgentPay VN currently supports Vietnamese bank accounts and VietQR payments. International support is on the roadmap.

Q: What happens if a payment fails? A: The await_settlement method returns a failed status. You can retry or prompt the customer to try again.

Q: Is AgentPay VN production-ready? A: Yes. It's MIT-licensed, open-source, and used in production by AgentPay partner merchants. Review the GitHub repository for details.

Q: Can I customize the checkout page? A: The checkout URL points to a standard VietQR flow. Custom branding is available in premium plans.

Next Steps

You now know how to integrate VietQR payments into Python AI agents. Here's your action plan:

  1. Install AgentPay VNpip install agentpay-vn
  2. Get an API key – Sign up at agentpay.servicesai.vn
  3. Read the full docs – Explore API reference for advanced features
  4. Star on GitHub – Support the project at github.com/phuocdu/agentpay-vn
  5. Join the community – Discuss integrations and share feedback

Building AI agents that handle payments opens new possibilities—from autonomous service providers to smart e-commerce bots. AgentPay VN makes it safe, simple, and non-custodial.

Happy coding! 🚀

Get started →

← All posts