1#!/usr/bin/env python
2# pylint: disable=unused-argument
3# This program is dedicated to the public domain under the CC0 license.
4
5"""Basic example for a bot that can receive payments from users."""
6
7import logging
8
9from telegram import LabeledPrice, ShippingOption, Update
10from telegram.ext import (
11 Application,
12 CommandHandler,
13 ContextTypes,
14 MessageHandler,
15 PreCheckoutQueryHandler,
16 ShippingQueryHandler,
17 filters,
18)
19
20# Enable logging
21logging.basicConfig(
22 format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
23)
24# set higher logging level for httpx to avoid all GET and POST requests being logged
25logging.getLogger("httpx").setLevel(logging.WARNING)
26
27logger = logging.getLogger(__name__)
28
29# Insert the token from your payment provider.
30# In order to get a provider_token see https://core.telegram.org/bots/payments#getting-a-token
31PAYMENT_PROVIDER_TOKEN = "PAYMENT_PROVIDER_TOKEN"
32
33
34async def start_callback(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
35 """Provides instructions on how to use the bot."""
36 msg = (
37 "Use /shipping to receive an invoice with shipping included, or /noshipping for an "
38 "invoice without shipping."
39 )
40 await update.message.reply_text(msg)
41
42
43async def start_with_shipping_callback(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
44 """Sends an invoice which triggers a shipping query."""
45 chat_id = update.message.chat_id
46 title = "Payment Example"
47 description = "Example of a payment process using the python-telegram-bot library."
48 # Unique payload to identify this payment request as being from your bot
49 payload = "Custom-Payload"
50 # Set up the currency.
51 # List of supported currencies: https://core.telegram.org/bots/payments#supported-currencies
52 currency = "USD"
53 # Price in dollars
54 price = 1
55 # Convert price to cents from dollars.
56 prices = [LabeledPrice("Test", price * 100)]
57 # Optional parameters like need_shipping_address and is_flexible trigger extra user prompts
58 # https://docs.python-telegram-bot.org/en/stable/telegram.bot.html#telegram.Bot.send_invoice
59 await context.bot.send_invoice(
60 chat_id,
61 title,
62 description,
63 payload,
64 PAYMENT_PROVIDER_TOKEN,
65 currency,
66 prices,
67 need_name=True,
68 need_phone_number=True,
69 need_email=True,
70 need_shipping_address=True,
71 is_flexible=True,
72 )
73
74
75async def start_without_shipping_callback(
76 update: Update, context: ContextTypes.DEFAULT_TYPE
77) -> None:
78 """Sends an invoice without requiring shipping details."""
79 chat_id = update.message.chat_id
80 title = "Payment Example"
81 description = "Example of a payment process using the python-telegram-bot library."
82 # Unique payload to identify this payment request as being from your bot
83 payload = "Custom-Payload"
84 currency = "USD"
85 # Price in dollars
86 price = 1
87 # Convert price to cents from dollars.
88 prices = [LabeledPrice("Test", price * 100)]
89
90 # optionally pass need_name=True, need_phone_number=True,
91 # need_email=True, need_shipping_address=True, is_flexible=True
92 await context.bot.send_invoice(
93 chat_id, title, description, payload, PAYMENT_PROVIDER_TOKEN, currency, prices
94 )
95
96
97async def shipping_callback(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
98 """Handles the ShippingQuery with available shipping options."""
99 query = update.shipping_query
100 # Verify if the payload matches, ensure it's from your bot
101 if query.invoice_payload != "Custom-Payload":
102 # If not, respond with an error
103 await query.answer(ok=False, error_message="Something went wrong...")
104 return
105
106 # Define available shipping options
107 # First option with a single price entry
108 options = [ShippingOption("1", "Shipping Option A", [LabeledPrice("A", 100)])]
109 # Second option with multiple price entries
110 price_list = [LabeledPrice("B1", 150), LabeledPrice("B2", 200)]
111 options.append(ShippingOption("2", "Shipping Option B", price_list))
112 await query.answer(ok=True, shipping_options=options)
113
114
115# After (optional) shipping, process the pre-checkout step
116async def precheckout_callback(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
117 """Responds to the PreCheckoutQuery as the final confirmation for checkout."""
118 query = update.pre_checkout_query
119 # Verify if the payload matches, ensure it's from your bot
120 if query.invoice_payload != "Custom-Payload":
121 # If not, respond with an error
122 await query.answer(ok=False, error_message="Something went wrong...")
123 else:
124 await query.answer(ok=True)
125
126
127# Final callback after successful payment
128async def successful_payment_callback(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
129 """Acknowledges successful payment and thanks the user."""
130 await update.message.reply_text("Thank you for your payment.")
131
132
133def main() -> None:
134 """Starts the bot and sets up handlers."""
135 # Create the Application and pass it your bot's token.
136 application = Application.builder().token("TOKEN").build()
137
138 # Start command to display usage instructions
139 application.add_handler(CommandHandler("start", start_callback))
140
141 # Command handlers for starting the payment process
142 application.add_handler(CommandHandler("shipping", start_with_shipping_callback))
143 application.add_handler(CommandHandler("noshipping", start_without_shipping_callback))
144
145 # Handler for shipping query (if product requires shipping)
146 application.add_handler(ShippingQueryHandler(shipping_callback))
147
148 # Pre-checkout handler for verifying payment details.
149 application.add_handler(PreCheckoutQueryHandler(precheckout_callback))
150
151 # Handler for successful payment. Notify the user that the payment was successful.
152 application.add_handler(
153 MessageHandler(filters.SUCCESSFUL_PAYMENT, successful_payment_callback)
154 )
155
156 # Start polling for updates until interrupted (CTRL+C)
157 application.run_polling(allowed_updates=Update.ALL_TYPES)
158
159
160if __name__ == "__main__":
161 main()