Collect VietQR Payments in Telegram Bots with AgentPay

2026-06-14 · AgentPay VN

vietqrtelegrampaymentspythonagentpay

Introduction

Telegram bots have become a popular way to deliver services and products directly to users. However, accepting payments within Telegram remains challenging in Vietnam. With AgentPay VN, you can now integrate VietQR payment collection into your Telegram bots seamlessly.

Unlike traditional payment gateways that hold funds in intermediary accounts, AgentPay VN directs payments straight to your merchant's bank account. This tutorial shows you how to build a payment-enabled Telegram bot in minutes.

What is AgentPay VN?

AgentPay VN is an open-source (MIT license) Python SDK designed specifically for AI agents and applications to collect VietQR payments. Key features include:

Getting Started

Installation

Install AgentPay VN and the Telegram bot library:

pip install agentpay-vn python-telegram-bot

Core Concepts

AgentPay VN uses a straightforward payment flow:

  1. Create Payment Request: Generate a payment request with amount and description
  2. Send Checkout URL: Share the VietQR checkout link with the user
  3. Await Settlement: Confirm payment via bank feed when funds arrive

Building Your First Payment Telegram Bot

Step 1: Set Up the Telegram Bot

First, create a new Telegram bot and get your API token from BotFather.

Step 2: Create Payment Requests

Here's a complete example integrating AgentPay with a Telegram bot:

from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Application, CommandHandler, ContextTypes
from agentpay_vn import AgentPayClient
import os

# Initialize AgentPay client
agentpay = AgentPayClient(
    merchant_id=os.getenv("MERCHANT_ID"),
    api_key=os.getenv("AGENTPAY_API_KEY")
)

# Initialize Telegram bot
TELEGRAM_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Start command - show payment options"""
    await update.message.reply_text(
        "Welcome! Choose an option:",
        reply_markup=InlineKeyboardMarkup([
            [InlineKeyboardButton("Pay 50,000 VND", callback_data="pay_50000")],
            [InlineKeyboardButton("Pay 100,000 VND", callback_data="pay_100000")],
        ])
    )

async def handle_payment(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Handle payment button clicks"""
    query = update.callback_query
    await query.answer()

    # Parse amount from callback data
    amount = int(query.data.split("_")[1])

    # Create payment request
    payment_request = agentpay.create_payment_request(
        amount=amount,
        description=f"Payment for {amount} VND",
        customer_id=str(update.effective_user.id),
        return_url=f"https://yourbot.com/confirm/{update.effective_user.id}"
    )

    # Get checkout URL
    checkout_url = payment_request.get("checkout_url")
    payment_id = payment_request.get("payment_id")

    # Send payment link to user
    keyboard = InlineKeyboardMarkup([
        [InlineKeyboardButton("Pay Now", url=checkout_url)]
    ])

    await query.edit_message_text(
        text=f"Please click the button below to complete payment of {amount:,} VND",
        reply_markup=keyboard
    )

    # Store payment_id for later confirmation
    context.user_data["payment_id"] = payment_id
    context.user_data["amount"] = amount

async def check_payment(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Check payment status"""
    payment_id = context.user_data.get("payment_id")

    if not payment_id:
        await update.message.reply_text("No active payment. Use /start to create one.")
        return

    # Check settlement status
    settlement = agentpay.await_settlement(
        payment_id=payment_id,
        timeout=30  # seconds
    )

    if settlement.get("status") == "confirmed":
        amount = context.user_data.get("amount")
        await update.message.reply_text(
            f"✅ Payment confirmed! {amount:,} VND received.\n"
            f"Transaction ID: {settlement.get('transaction_id')}"
        )
    else:
        await update.message.reply_text(
            "❌ Payment not confirmed yet. Please try again later."
        )

async def main():
    """Start the bot"""
    app = Application.builder().token(TELEGRAM_TOKEN).build()

    app.add_handler(CommandHandler("start", start))
    app.add_handler(CommandHandler("check", check_payment))

    # Handle button clicks
    from telegram.ext import CallbackQueryHandler
    app.add_handler(CallbackQueryHandler(handle_payment))

    await app.run_polling()

if __name__ == "__main__":
    import asyncio
    asyncio.run(main())

Using AgentPay MCP Server

If you're building AI agents, use the AgentPay MCP server for Claude or other agent frameworks:

pip install agentpay-mcp

MCP Configuration

Add to your Claude config or agent configuration file:

{
  "mcp_servers": {
    "agentpay": {
      "command": "agentpay-mcp",
      "env": {
        "MERCHANT_ID": "your_merchant_id",
        "AGENTPAY_API_KEY": "your_api_key"
      }
    }
  }
}

Now your AI agent can call AgentPay tools directly to create payments and check settlement status.

Best Practices

1. Security

2. User Experience

3. Error Handling

try:
    payment_request = agentpay.create_payment_request(
        amount=amount,
        description="Payment",
        customer_id=customer_id
    )
except Exception as e:
    print(f"Payment creation failed: {str(e)}")
    await update.message.reply_text("Payment service temporarily unavailable.")

FAQ

Q: Does AgentPay hold my money? A: No. Payments go directly to your merchant bank account. AgentPay never holds funds.

Q: How do I confirm payment? A: AgentPay uses bank feed integration. When funds arrive at your bank account, the settlement is confirmed automatically.

Q: Is AgentPay open source? A: Yes, it's MIT licensed. You can review and modify the code at GitHub.

Q: Can I use AgentPay with AI agents? A: Absolutely. Use the AgentPay MCP server to integrate with Claude, Anthropic agents, or other AI frameworks.

Q: What about transaction fees? A: Check the documentation for current pricing.

Next Steps

You now have a working Telegram bot that collects VietQR payments! Here's what to explore next:

Start collecting payments today with AgentPay VN. Install it now:

pip install agentpay-vn

Have questions? Visit the AgentPay documentation or open an issue on GitHub.

Get started →

← All posts