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 currency,
65 prices,
66 provider_token=PAYMENT_PROVIDER_TOKEN,
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,
94 title,
95 description,
96 payload,
97 currency,
98 prices,
99 provider_token=PAYMENT_PROVIDER_TOKEN,
100 )
101
102
103async def shipping_callback(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
104 """Handles the ShippingQuery with available shipping options."""
105 query = update.shipping_query
106 # Verify if the payload matches, ensure it's from your bot
107 if query.invoice_payload != "Custom-Payload":
108 # If not, respond with an error
109 await query.answer(ok=False, error_message="Something went wrong...")
110 return
111
112 # Define available shipping options
113 # First option with a single price entry
114 options = [ShippingOption("1", "Shipping Option A", [LabeledPrice("A", 100)])]
115 # Second option with multiple price entries
116 price_list = [LabeledPrice("B1", 150), LabeledPrice("B2", 200)]
117 options.append(ShippingOption("2", "Shipping Option B", price_list))
118 await query.answer(ok=True, shipping_options=options)
119
120
121# After (optional) shipping, process the pre-checkout step
122async def precheckout_callback(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
123 """Responds to the PreCheckoutQuery as the final confirmation for checkout."""
124 query = update.pre_checkout_query
125 # Verify if the payload matches, ensure it's from your bot
126 if query.invoice_payload != "Custom-Payload":
127 # If not, respond with an error
128 await query.answer(ok=False, error_message="Something went wrong...")
129 else:
130 await query.answer(ok=True)
131
132
133# Final callback after successful payment
134async def successful_payment_callback(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
135 """Acknowledges successful payment and thanks the user."""
136 await update.message.reply_text("Thank you for your payment.")
137
138
139def main() -> None:
140 """Starts the bot and sets up handlers."""
141 # Create the Application and pass it your bot's token.
142 application = Application.builder().token("TOKEN").build()
143
144 # Start command to display usage instructions
145 application.add_handler(CommandHandler("start", start_callback))
146
147 # Command handlers for starting the payment process
148 application.add_handler(CommandHandler("shipping", start_with_shipping_callback))
149 application.add_handler(CommandHandler("noshipping", start_without_shipping_callback))
150
151 # Handler for shipping query (if product requires shipping)
152 application.add_handler(ShippingQueryHandler(shipping_callback))
153
154 # Pre-checkout handler for verifying payment details.
155 application.add_handler(PreCheckoutQueryHandler(precheckout_callback))
156
157 # Handler for successful payment. Notify the user that the payment was successful.
158 application.add_handler(
159 MessageHandler(filters.SUCCESSFUL_PAYMENT, successful_payment_callback)
160 )
161
162 # Start polling for updates until interrupted (CTRL+C)
163 application.run_polling(allowed_updates=Update.ALL_TYPES)
164
165
166if __name__ == "__main__":
167 main()