Build a Telegram Bot Payment Collector with VietQR & AgentPay
Why Telegram Payments Matter for Your Business
Telegram bots have become a powerful channel for customer engagement and commerce in Vietnam. Whether you're running a digital product store, subscription service, or marketplace, accepting payments directly through Telegram eliminates friction and builds trust. However, integrating payment processing can be complex and risky if you're handling customer funds.
AgentPay VN changes this equation. It lets your Telegram bot collect VietQR payments without ever touching the money—payments flow directly to your merchant bank account, confirmed by real bank feeds.
How AgentPay VN Works
AgentPay is an open-source Python SDK and MCP server (MIT licensed) designed specifically for AI agents and bots to handle payments. Here's the flow:
- Create a payment request with amount, description, and customer details
- Send a checkout URL to your customer via Telegram
- Await settlement confirmation from your bank
The entire transaction is transparent, bank-settled, and zero-custody.
Installation & Setup
Start by installing the SDK:
pip install agentpay-vn
For MCP integration (if using Claude or other AI frameworks):
pip install agentpay-mcp
You'll also need the Telegram bot library:
pip install python-telegram-bot
Building Your First Payment-Enabled Telegram Bot
Here's a complete example of a simple Telegram bot that accepts payments for digital products:
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Application, CommandHandler, ContextTypes, CallbackQueryHandler
from agentpay_vn import PaymentClient
import os
# Initialize AgentPay client
payment_client = PaymentClient(
api_key=os.getenv("AGENTPAY_API_KEY"),
merchant_id=os.getenv("AGENTPAY_MERCHANT_ID")
)
# Product catalog
PRODUCTS = {
"ebook": {"name": "Python Guide", "price": 50000},
"course": {"name": "Telegram Bot Masterclass", "price": 199000},
"support": {"name": "Email Support (1 month)", "price": 99000}
}
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Send product menu."""
keyboard = [
[InlineKeyboardButton(f"{prod['name']} - {prod['price']:,}₫",
callback_data=f"buy_{key}")]
for key, prod in PRODUCTS.items()
]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text(
"📦 Welcome! Choose a product:\n",
reply_markup=reply_markup
)
async def handle_purchase(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle product selection and create payment request."""
query = update.callback_query
await query.answer()
product_key = query.data.split("_")[1]
product = PRODUCTS[product_key]
# Create payment request with AgentPay
payment_request = await payment_client.create_payment_request(
amount_vnd=product["price"],
description=product["name"],
customer_id=str(query.from_user.id),
customer_name=query.from_user.first_name,
metadata={"product": product_key, "telegram_user": query.from_user.id}
)
# Get checkout URL
checkout_url = payment_request["checkout_url"]
payment_id = payment_request["id"]
# Send payment link to user
keyboard = [[InlineKeyboardButton("💳 Pay with VietQR", url=checkout_url)]]
reply_markup = InlineKeyboardMarkup(keyboard)
await query.edit_message_text(
text=f"✅ Ready to pay for **{product['name']}**?\n\n"
f"Amount: **{product['price']:,}₫**\n\n"
f"Click the button below to scan and pay.",
reply_markup=reply_markup,
parse_mode="Markdown"
)
# Store payment ID in context for settlement polling
context.user_data["pending_payment"] = payment_id
async def check_settlement(context: ContextTypes.DEFAULT_TYPE):
"""Background job to check payment settlement status."""
# This would typically run on a schedule
# In production, use webhooks or bank feeds for real-time confirmation
pass
def main():
"""Start the Telegram bot."""
app = Application.builder().token(os.getenv("TELEGRAM_BOT_TOKEN")).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(CallbackQueryHandler(handle_purchase, pattern="^buy_"))
app.run_polling()
if __name__ == "__main__":
main()
Using AgentPay with MCP Server
If you're building an AI-powered bot using Claude or similar frameworks, use the MCP configuration:
{
"mcpServers": {
"agentpay": {
"command": "agentpay-mcp",
"env": {
"AGENTPAY_API_KEY": "your_api_key_here",
"AGENTPAY_MERCHANT_ID": "your_merchant_id"
}
}
}
}
This allows your AI agent to autonomously create and manage payment requests.
Key Features for Telegram Integrations
Bank-Direct Transfers: VietQR payments go directly to your registered merchant bank account. No holding periods, no escrow, no intermediary risk.
Bank Feed Confirmation: AgentPay confirms settlement through actual bank transactions, not just API logs. This means genuine, irreversible payment confirmation.
Zero Custody: Your bot never holds customer funds. You eliminate PCI compliance headaches and fraud liability.
Metadata Flexibility: Attach custom data (user IDs, product codes, order IDs) to each payment request for easy reconciliation.
Best Practices
- Store payment IDs: Keep track of payment request IDs in your bot database to match VietQR settlements with orders
- Implement idempotency: Use unique customer IDs and order references to prevent duplicate charges
- Add timeouts: Set expiration times on payment requests (typically 15-30 minutes)
- Use webhooks: Subscribe to settlement notifications instead of polling
- Test thoroughly: Use a sandbox environment before going live
Frequently Asked Questions
Q: Does AgentPay charge transaction fees? A: Check the current pricing on agentpay.servicesai.vn. Fees are typically lower than traditional payment gateways since there's no intermediary.
Q: Can I refund payments? A: Refunds go through your bank's standard process since money settles directly to your account. AgentPay doesn't reverse transactions—your bank handles them.
Q: What if a customer doesn't pay within the time limit? A: The payment request simply expires. You can create a new one or remind the customer through Telegram.
Q: Is this production-ready? A: AgentPay VN is MIT-licensed open source. Review the code and security practices before deploying to production. The SDK is actively maintained at github.com/phuocdu/agentpay-vn.
Next Steps
You're now equipped to build payment-collecting Telegram bots powered by AgentPay VN. Start with the basics: create payment requests, send checkout URLs, and verify settlements through your bank feeds.
For detailed API documentation, visit the official AgentPay docs. Join the community on GitHub to share your bot ideas and contribute improvements.
Happy building! 🚀