Sell Digital Products from AI Chatbots Without Holding Funds

2026-07-20 · AgentPay VN

ai-agentsvietqr-paymentspython-sdkdigital-productsmcp-server

The Hidden Cost of AI Commerce: Why Most Chatbot Payment Solutions Break Trust

Imagine you've built an AI chatbot that sells online courses. A customer clicks "Buy Now," pays $50, and your bot immediately sends the course link. Everything feels smooth—until you check your bank account three days later and the money hasn't arrived. Instead, it's sitting in a third-party payment processor's account, pending settlement, subject to fees you didn't fully understand.

This is the reality for thousands of developers using traditional payment gateways with their AI agents. The system works, technically, but it introduces friction, trust issues, and operational complexity that shouldn't exist in 2024.

What if payment could be direct—customer to your bank account—with an AI agent managing the entire flow? What if you never touched the money at all, but your customer received their digital product instantly anyway?

That's exactly what AgentPay VN solves.

The AgentPay VN Difference: Direct Payments, Zero Fund Holding

AgentPay VN is an open-source Python SDK (MIT licensed) and MCP server that lets AI agents collect payments via VietQR—Vietnam's unified QR payment standard—without ever holding customer funds. The money flows directly from the customer's bank to your bank account. Your agent simply orchestrates the transaction and confirms settlement via your bank feed.

Here's what makes this different from typical payment platforms:

The Three-Step Payment Flow

AgentPay VN reduces the entire payment cycle to three operations:

  1. create_payment_request: Your agent defines the transaction (amount, product, customer details).
  2. send_checkout_url: The agent generates a VietQR checkout link and sends it to the customer.
  3. await_settlement: The agent monitors your bank feed and confirms when funds arrive.

Let's see this in action.

Installation and Setup

Start with a simple pip install:

pip install agentpay-vn

For MCP (Model Context Protocol) integration with Claude or compatible AI platforms, also set up the server:

agentpay-mcp

That's it. No API keys to external services, no webhook complexity.

Building Your First Payment Flow: A Real-World Example

Let's build an AI chatbot that sells Python e-books. A customer asks, "Can I buy your 'Advanced FastAPI' guide?" Your bot should:

  1. Create a payment request for $19.99
  2. Send the customer a VietQR checkout link
  3. Wait for settlement confirmation
  4. Deliver the e-book

Step 1: Create the Payment Request

from agentpay_vn import create_payment_request, send_checkout_url, await_settlement
import asyncio

# Define your product and customer
payment_request = create_payment_request(
    amount=1999,  # 19.99 USD in cents
    product_name="Advanced FastAPI Guide",
    product_id="ebook_fastapi_001",
    customer_name="Nguyen Van A",
    customer_email="customer@example.com",
    merchant_account="0123456789",  # Your bank account (VietQR format)
    description="E-book: Building production-ready FastAPI applications"
)

print(f"Payment Request Created: {payment_request['id']}")
print(f"Status: {payment_request['status']}")

What's happening here: - amount is in the smallest currency unit (cents/đồng). $19.99 = 1999. - product_id uniquely identifies this e-book so your agent can track deliveries. - merchant_account is your bank account in VietQR format—funds go directly here. - The function returns a request object with a unique id for tracking.

Step 2: Send the Checkout URL

# Generate the VietQR checkout link
checkout_data = send_checkout_url(payment_request)

checkout_url = checkout_data['url']
qr_code_image = checkout_data['qr_image']  # Base64-encoded PNG

# Your chatbot sends this to the customer
bot_message = f"""
Great choice! Here's your checkout link:

{checkout_url}

Or scan this QR code with any Vietnamese banking app:
[QR Code Display]

Once you pay, I'll send your e-book instantly.
"""

print(bot_message)

Key points: - The checkout URL is a VietQR payment link. The customer scans it with their banking app or clicks the link. - No redirect to an external payment gateway—it's a direct bank transfer instruction. - The QR code is generated locally; your agent can display it in chat or email it. - The customer completes the payment in their banking app, their account is debited, and your bank account is credited.

Step 3: Wait for Settlement Confirmation

# Monitor your bank feed for settlement
async def complete_sale(payment_request_id, customer_email, product_file_path):
    """
    Wait for settlement, then deliver the product.
    """

    # Check your bank feed (every 10 seconds for up to 5 minutes)
    settlement = await_settlement(
        request_id=payment_request_id,
        timeout_seconds=300,
        poll_interval=10
    )

    if settlement['confirmed']:
        print(f"✓ Payment confirmed! Amount: {settlement['amount']}")

        # Deliver the e-book
        with open(product_file_path, 'rb') as f:
            ebook_content = f.read()

        # Your chatbot would:
        # 1. Send the file to the customer's email
        # 2. Update your inventory/license database
        # 3. Log the transaction

        send_email(
            to=customer_email,
            subject="Your Advanced FastAPI Guide",
            body="Thank you for your purchase! Here's your e-book.",
            attachment=ebook_content
        )

        return {"status": "delivered", "email_sent": True}
    else:
        print("Payment not received. Customer may have cancelled.")
        return {"status": "failed", "reason": "timeout"}

# Run the flow
asyncio.run(complete_sale(
    payment_request_id=payment_request['id'],
    customer_email="customer@example.com",
    product_file_path="/products/advanced_fastapi.pdf"
))

What's crucial here: - await_settlement polls your bank feed (via your bank's API or CSV feed) to confirm the customer's payment arrived. - Once confirmed=True, the funds are in your account. No waiting for settlement windows. - Your agent then triggers product delivery (email, download link, account creation, etc.). - If the payment doesn't arrive within the timeout, the agent can notify the customer or retry.

Integrating with Claude via MCP

If you want Claude (or another MCP-compatible AI) to manage payments autonomously, configure it like this:

{
  "mcpServers": {
    "agentpay": {
      "command": "agentpay-mcp",
      "args": [],
      "env": {
        "BANK_FEED_API_KEY": "your_bank_feed_credentials",
        "MERCHANT_ACCOUNT": "0123456789",
        "SETTLEMENT_CHECK_INTERVAL": "10"
      }
    }
  }
}

Add this to your Claude client configuration. Now Claude can call payment tools directly:

User: "I want to buy your course."
Claude: [Uses agentpay tool to create_payment_request]
Claude: [Sends checkout URL to user]
Claude: [Monitors settlement in the background]
Claude: "Payment confirmed! Sending your course materials now..."

No custom API layer needed.

Real-World Walkthrough: An AI Course Marketplace

Let's see AgentPay VN in a complete scenario: an AI tutor bot selling programming courses.

Scenario: Student asks, "Do you have a course on Vue.js?"

Bot flow:

  1. Product lookup: Bot queries course database → finds "Vue.js Mastery" ($39.99, course_id=vue_001).
  2. Payment creation: Bot calls create_payment_request(amount=3999, product_id="vue_001", ...).
  3. Presentation: Bot displays checkout URL and QR code: "Here's your course. Scan to pay."
  4. Customer action: Student opens banking app, scans QR, transfers ₫1M (equivalent) from their account to yours.
  5. Settlement check: Bot polls bank feed for confirmation (typically <30 seconds in Vietnam).
  6. Delivery: Once confirmed, bot sends: - Download link to course materials - Access token to private course videos - Enrollment confirmation - Welcome email with curriculum outline
  7. Follow-up: Bot logs transaction, updates sales dashboard, sends thank-you message.

The entire flow, from question to course access, takes ~2 minutes. No third-party intermediary, no fund delays, no trust issues.

Advanced Tips: Scaling Beyond Single Transactions

Handling Multiple Concurrent Sales

If your bot serves many customers simultaneously, use request IDs to track each payment:

from agentpay_vn import create_payment_request, await_settlement
import asyncio

async def handle_multiple_customers(customers):
    """
    Launch concurrent payment flows for multiple customers.
    """
    tasks = []

    for customer in customers:
        payment_req = create_payment_request(
            amount=customer['amount'],
            product_id=customer['product'],
            customer_email=customer['email']
        )

        # Each payment is tracked independently
        task = await_settlement(payment_req['id'], timeout_seconds=300)
        tasks.append(task)

    # Wait for all payments in parallel
    results = await asyncio.gather(*tasks)
    return results

Retry Logic for Network Hiccups

Bank feeds can occasionally be slow. Add resilience:

from agentpay_vn import await_settlement
import time

def robust_settlement_check(request_id, max_retries=3):
    for attempt in range(max_retries):
        try:
            result = await_settlement(request_id, timeout_seconds=600)
            if result['confirmed']:
                return result
        except ConnectionError:
            if attempt < max_retries - 1:
                time.sleep(10 * (2 ** attempt))  # Exponential backoff
                continue
            else:
                raise
    return {"confirmed": False, "reason": "max_retries_exceeded"}

Logging and Audit Trails

For compliance, log every transaction:

import json
from datetime import datetime

def log_payment(payment_request, settlement_result, product_delivered):
    log_entry = {
        "timestamp": datetime.utcnow().isoformat(),
        "request_id": payment_request['id'],
        "amount": payment_request['amount'],
        "customer_email": payment_request['customer_email'],
        "settlement_confirmed": settlement_result['confirmed'],
        "product_delivered": product_delivered,
        "notes": "Audit trail for tax/compliance purposes"
    }

    with open("payment_audit.jsonl", "a") as f:
        f.write(json.dumps(log_entry) + "\n")

Comparison: AgentPay VN vs. Traditional Payment Gateways

Feature AgentPay VN Stripe/PayPal Momo/ZaloPay
Fund holding ✗ Direct to bank ✓ Held 1-3 days ✓ Held 1-2 days
AI-native API ✓ Built for agents ✗ Web/mobile first ✗ Web/mobile first
Settlement fees ~0% (bank transfer) 2.9% + $0.30 1-2%
Vietnam VietQR ✓ Native support ✗ Limited ✓ Native
Open source ✓ MIT licensed ✗ Proprietary ✗ Proprietary
Setup complexity 5 minutes 1 hour 1 hour
Support for agents ✓ MCP server ✗ Webhooks only ✗ Webhooks only

Do's and Don'ts

DO: - ✓ Use unique product_id values for each product so you can track inventory. - ✓ Validate customer_email before creating payment requests; typos delay delivery. - ✓ Store payment request_id in your database for audit trails. - ✓ Implement exponential backoff when polling your bank feed. - ✓ Test with your actual bank account first (use staging/sandbox mode if available).

DON'T: - ✗ Store customer bank account details; VietQR handles this securely. - ✗ Deliver products before await_settlement returns confirmed=True. - ✗ Ignore timeout errors—always have a fallback (e.g., manual review queue). - ✗ Use hardcoded merchant accounts; read from environment variables. - ✗ Assume VietQR payments are instant; Vietnamese banks have variable processing times (typically 10-60 seconds).

FAQ

Q: What if the customer's bank doesn't support VietQR?

A: VietQR is the national standard in Vietnam; virtually all banks support it since 2020. If a customer's bank is unsupported (very rare), the QR code will display an error. Have a fallback process: manual bank transfer details or alternative payment method.

Q: How do I know if a payment arrived if my bank feed is delayed?

A: await_settlement has a configurable timeout. If your bank's API is slow, increase the timeout and polling interval. For maximum reliability, subscribe to SMS/email notifications from your bank as a secondary confirmation.

Q: Can I use AgentPay VN outside Vietnam?

A: VietQR is Vietnam-specific. If you're outside Vietnam but have a Vietnamese bank account, it works. For international customers paying to a Vietnam account, they'd need a Vietnamese bank app. For global use, you'd integrate AgentPay VN with international payment gateways (future roadmap item).

Q: Is there a transaction limit per payment?

A: No hard limit in AgentPay VN itself, but most Vietnamese banks limit single transfers to 1 billion VND (~$40,000 USD) per transaction. Your bank's limits apply. For higher amounts, split into multiple requests or contact your bank.

Key Takeaways

Get Started Now

Your next step is simple:

  1. Install the SDK: bash pip install agentpay-vn

  2. Explore the docs at https://agentpay.servicesai.vn/v1/docs for API reference, examples, and deployment guides.

  3. Check the GitHub repo at https://github.com/phuocdu/agentpay-vn for source code, issues, and community contributions.

  4. Test with your bot using the patterns in this tutorial. Start with a single product, get one full payment flow working, then scale.

The future of AI commerce isn't waiting for third parties to process money—it's agents managing direct, instant, auditable transactions. AgentPay VN is your foundation for building that future in Vietnam and beyond.

Happy coding!

Get started →

← All posts