Sell Digital Products from AI Chatbots Without Holding Funds

2026-09-07 · AgentPay VN

ai-paymentsvietqrpython-sdkchatbotsfintech

The Problem: AI Chatbots That Can't Actually Close Sales

Imagine you've built an AI chatbot that sells online courses, design templates, or software licenses. Your agent engages users, answers questions, and confidently says "ready to buy?" — then what? You either:

  1. Redirect to a payment gateway (losing context, breaking conversation flow)
  2. Build custom payment infrastructure (months of compliance work, liability headaches)
  3. Use a payment processor that holds your funds (waiting 7–14 days, plus fees eating margins)
  4. Abandon monetization entirely (and your chatbot stays a hobby)

This is where most AI projects die. The technology works, but the money doesn't.

AgentPay VN solves this by letting your AI agent handle payments natively, collecting funds directly into your bank account within minutes—no intermediary, no fund custody, no friction.

Why AgentPay VN Changes the Game

AgentPay VN is an open-source Python SDK + MCP server purpose-built for AI agents accepting Vietnamese payments. Here's what makes it different:

Instead of your agent saying "go to this link," it can now orchestrate the entire payment experience while you get paid directly.

How It Works: The 3-Step Flow

1. Create a Payment Request

Your AI agent generates a unique payment request with amount, description, and customer details:

from agentpay_vn import create_payment_request

# Agent receives order details from user conversation
order_total = 499_000  # VND
customer_email = "user@example.com"
product_name = "Advanced Python Course Bundle"

# Step 1: Create the payment request
payment = create_payment_request(
    amount=order_total,
    description=f"Purchase: {product_name}",
    order_id="ORD-20250115-001",
    customer_email=customer_email,
    customer_phone="0912345678",
    return_url="https://yourapp.com/confirm"
)

print(f"Payment ID: {payment['payment_id']}")
print(f"QR URL: {payment['qr_url']}")
# Output:
# Payment ID: pay_abc123xyz789
# QR URL: https://vietqr.io/...

Line-by-line breakdown: - amount: Transaction value in Vietnamese Dong (VND) - description: What's being sold (appears on customer's bank statement) - order_id: Your internal order reference for reconciliation - customer_email/customer_phone: Contact info for confirmation emails - return_url: Where the agent continues conversation after payment

The function returns a QR code (as image URL or raw data) and a payment_id for tracking.

2. Send the Checkout URL to the Customer

Your chatbot surfaces this to the user:

# Agent sends payment link to user
checkout_message = f"""
🛒 Ready to complete your purchase!

Amount: ₫{order_total:,}
Item: {product_name}

Scan this QR code to pay:
{payment['qr_url']}

Or click here: {payment['checkout_url']}

Once payment is confirmed, I'll instantly send your course access.
"""

# Send via Telegram, WhatsApp, email, or display in chat UI
agent.send_message(user_id, checkout_message, image=payment['qr_image'])

The URL works on desktop (opens bank transfer form) and mobile (VietQR app integration).

3. Await Settlement Confirmation

Your agent polls for payment confirmation, then executes the fulfillment:

from agentpay_vn import await_settlement
import time

# Agent waits for payment to clear
# Timeout after 15 minutes (customer has time to scan & confirm)
payment_id = payment['payment_id']
deadline = time.time() + (15 * 60)

while time.time() < deadline:
    settlement = await_settlement(
        payment_id=payment_id,
        timeout_seconds=2
    )

    if settlement['status'] == 'confirmed':
        print(f"✅ Payment confirmed! Amount: ₫{settlement['amount']}")
        print(f"Transaction ID: {settlement['transaction_id']}")
        print(f"Settled to account: {settlement['merchant_account']}")

        # Agent fulfills the order
        course_access_link = generate_course_token(customer_email)
        agent.send_message(
            user_id,
            f"🎉 Payment received! Here's your course access:\n{course_access_link}"
        )
        break

    time.sleep(2)  # Poll every 2 seconds
else:
    agent.send_message(user_id, "Payment timeout. Please try again.")

Key behaviors: - status == 'confirmed': Bank feed verified the transfer to your account - status == 'pending': User has scanned QR, payment in flight - status == 'failed': Transfer rejected or timed out; agent prompts retry - Settlement arrives in your bank account within 60–120 seconds (same-day clearing)

Setting Up the MCP Server for Claude

If you're using Claude as your AI agent, AgentPay VN ships with a Model Context Protocol server that auto-exposes payment functions:

{
  "mcpServers": {
    "agentpay": {
      "command": "python",
      "args": ["-m", "agentpay_mcp"],
      "env": {
        "AGENTPAY_MERCHANT_ID": "your-merchant-id",
        "AGENTPAY_API_KEY": "your-api-key",
        "AGENTPAY_BANK_ACCOUNT": "1234567890@vietcombank"
      }
    }
  }
}

Add this to your Claude Desktop config (or Cline settings if using VS Code). Now Claude has native tools:

Your agent can then reason about payment logic without SDK imports:

User: "I want to buy the Pro plan for 999,000 VND"
Claude: I'll create a payment request and send you a QR code.
[calls agentpay:create_payment_request with amount=999000]
Claude: Here's your payment link. I'll confirm once settled.
[polling agentpay:await_settlement until confirmed]
Claude: ✅ Payment confirmed! Setting up your Pro account now.

Real-World Example: Online Course Bot

Let's build a complete e-learning chatbot:

from agentpay_vn import create_payment_request, await_settlement
from datetime import datetime
import json

class CourseBot:
    def __init__(self, merchant_email):
        self.merchant_email = merchant_email
        self.courses = {
            "python-101": {"name": "Python Basics", "price": 299_000},
            "django-pro": {"name": "Django Mastery", "price": 599_000},
            "bundle": {"name": "Full Stack Bundle", "price": 799_000},
        }

    def handle_purchase(self, user_email, course_id):
        """User wants to buy a course"""
        course = self.courses[course_id]

        # Step 1: Create payment
        payment = create_payment_request(
            amount=course['price'],
            description=f"Course: {course['name']}",
            order_id=f"CRS-{datetime.now().strftime('%Y%m%d%H%M%S')}",
            customer_email=user_email,
        )

        # Step 2: Show checkout
        print(f"\n📚 {course['name']} - ₫{course['price']:,}")
        print(f"QR: {payment['qr_url']}")
        print(f"ID: {payment['payment_id']}")

        # Step 3: Await payment + deliver course
        settlement = await_settlement(payment['payment_id'], timeout_seconds=900)

        if settlement['status'] == 'confirmed':
            access_token = self.issue_course_access(user_email, course_id)
            return f"✅ Access granted! Token: {access_token}"
        else:
            return "❌ Payment failed or timed out."

    def issue_course_access(self, email, course_id):
        """Generate course access token (your business logic)"""
        # In production: store in DB, send email with links
        return f"TOKEN-{course_id}-{hash(email) % 10000}"

# Usage
bot = CourseBot(merchant_email="courses@example.com")
result = bot.handle_purchase("student@gmail.com", "django-pro")
print(result)

Output (after user pays):

📚 Django Mastery - ₫599,000
QR: https://vietqr.io/...
ID: pay_xyz123

[User scans QR, completes bank transfer, settlement confirmed]

✅ Access granted! Token: TOKEN-django-pro-5432

Installation & Setup

Quick Start (3 steps)

1. Install the SDK:

pip install agentpay-vn

2. Configure credentials:

export AGENTPAY_MERCHANT_ID="your-id-from-dashboard"
export AGENTPAY_API_KEY="your-api-key"
export AGENTPAY_BANK_ACCOUNT="1234567890@vietcombank"  # Your account

3. Test in Python:

from agentpay_vn import create_payment_request
payment = create_payment_request(amount=100_000, description="Test")
print(payment['qr_url'])

For Claude Desktop Users

  1. Install: pip install agentpay-vn[mcp]
  2. Add the MCP config to ~/Library/Application Support/Claude/claude_desktop_config.json
  3. Restart Claude
  4. Claude now has agentpay:* tools available

Do's and Don'ts

✅ Do ❌ Don't
Store payment_id in your database for reconciliation Assume payment is instant; always poll with await_settlement
Set reasonable timeouts (5–15 min) for QR codes Leave QR codes active indefinitely; they expire after merchant timeout
Validate customer_email before creating request Accept payments without confirming customer identity
Log all transaction_id values for accounting Lose transaction records; they're your audit trail
Test with small amounts first (10k VND) Deploy to production without testing on staging
Use order IDs to prevent duplicate processing Process the same payment_id twice

Advanced: Bank Feed Integration

AgentPay VN's killer feature is real bank settlement confirmation, not webhook guessing. Here's why it matters:

# Traditional payment processors:
# 1. User pays
# 2. Webhook received (sometimes delayed/lost)
# 3. You hope funds are actually there
# Settlement: 7-14 days later

# AgentPay VN:
# 1. User pays via VietQR
# 2. Bank feed confirms transfer to YOUR account (60-120 seconds)
# 3. 100% guaranteed settlement
# Funds: Already in your account

This means your agent never says "payment processing" — it says "payment confirmed" and means it.

FAQ

Q: Does AgentPay VN hold my money?

A: Never. QR codes point directly at your merchant bank account. We don't touch the funds. Settlement is confirmed via your bank's API, not our system.

Q: What if a customer initiates a chargeback?

A: Bank transfers in Vietnam are irreversible by design (unlike card payments). Once the transfer clears, it's final. This protects you from chargebacks at the cost of no refund mechanism — build refund logic into your app if needed.

Q: How fast is settlement?

A: Most banks confirm transfers within 60–120 seconds during business hours. Your agent can await confirmation in real time. Weekends/holidays may add delay, but funds still arrive same-day.

Q: Can I use this with Telegram bots?

A: Yes. AgentPay VN is pure Python, so it works with python-telegram-bot, Discord.py, or any chat framework. Send QR as image attachment, then poll for settlement in background.

Comparison: AgentPay VN vs. Traditional Payment Flows

Aspect Traditional Gateway AgentPay VN
Fund Custody Processor holds funds Zero custody — straight to bank
Settlement Speed 7–14 days 60–120 seconds
Integration Friction Redirect to external site Native to chatbot
Fees 2–3% + transaction fees Per-request API cost (~0.1%)
Compliance Complex PCI/regulatory burden Bank-verified, simplified
AI Agent UX Breaks conversation Seamless in-chat experience

Key Takeaways

Getting Started Now

  1. Install: pip install agentpay-vn
  2. Read docs: https://agentpay.servicesai.vn/v1/docs
  3. Explore code: https://github.com/phuocdu/agentpay-vn
  4. Build: Start with the course bot example above, adapt to your use case

Your AI agent is ready to earn money. Let's ship it.

Get started →

← All posts