python-telegram-bot/examples/paymentbot.py

165 lines
5.6 KiB
Python
Raw Normal View History

2017-06-10 21:43:38 +02:00
#!/usr/bin/env python
# pylint: disable=missing-function-docstring, unused-argument
# This program is dedicated to the public domain under the CC0 license.
"""Basic example for a bot that can receive payment from user."""
2017-06-10 21:43:38 +02:00
import logging
from telegram import LabeledPrice, ShippingOption, Update
from telegram.ext import (
CommandHandler,
MessageHandler,
2021-11-20 11:36:18 +01:00
filters,
PreCheckoutQueryHandler,
ShippingQueryHandler,
Application,
CallbackContext,
)
2017-06-10 21:43:38 +02:00
2017-06-10 21:43:38 +02:00
# Enable logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
)
2017-06-10 21:43:38 +02:00
logger = logging.getLogger(__name__)
PAYMENT_PROVIDER_TOKEN = "PAYMENT_PROVIDER_TOKEN"
2017-06-10 21:43:38 +02:00
async def start_callback(update: Update, context: CallbackContext.DEFAULT_TYPE) -> None:
"""Displays info on how to use the bot."""
msg = (
"Use /shipping to get an invoice for shipping-payment, or /noshipping for an "
"invoice without shipping."
)
await update.message.reply_text(msg)
2017-06-10 21:43:38 +02:00
async def start_with_shipping_callback(
update: Update, context: CallbackContext.DEFAULT_TYPE
) -> None:
"""Sends an invoice with shipping-payment."""
2017-06-10 21:43:38 +02:00
chat_id = update.message.chat_id
title = "Payment Example"
description = "Payment Example using python-telegram-bot"
# select a payload just for you to recognize its the donation from your bot
payload = "Custom-Payload"
# In order to get a provider_token see https://core.telegram.org/bots/payments#getting-a-token
2017-06-10 21:43:38 +02:00
currency = "USD"
# price in dollars
price = 1
2019-10-27 00:15:09 +02:00
# price * 100 so as to include 2 decimal points
2017-06-10 22:30:21 +02:00
# check https://core.telegram.org/bots/payments#supported-currencies for more details
2017-06-10 21:43:38 +02:00
prices = [LabeledPrice("Test", price * 100)]
# optionally pass need_name=True, need_phone_number=True,
# need_email=True, need_shipping_address=True, is_flexible=True
await context.bot.send_invoice(
chat_id,
title,
description,
payload,
PAYMENT_PROVIDER_TOKEN,
currency,
prices,
need_name=True,
need_phone_number=True,
need_email=True,
need_shipping_address=True,
is_flexible=True,
)
2017-06-10 21:43:38 +02:00
async def start_without_shipping_callback(
update: Update, context: CallbackContext.DEFAULT_TYPE
) -> None:
"""Sends an invoice without shipping-payment."""
2017-06-10 21:43:38 +02:00
chat_id = update.message.chat_id
title = "Payment Example"
description = "Payment Example using python-telegram-bot"
# select a payload just for you to recognize its the donation from your bot
payload = "Custom-Payload"
# In order to get a provider_token see https://core.telegram.org/bots/payments#getting-a-token
2017-06-10 21:43:38 +02:00
currency = "USD"
# price in dollars
price = 1
2019-10-27 00:15:09 +02:00
# price * 100 so as to include 2 decimal points
2017-06-10 21:43:38 +02:00
prices = [LabeledPrice("Test", price * 100)]
# optionally pass need_name=True, need_phone_number=True,
# need_email=True, need_shipping_address=True, is_flexible=True
await context.bot.send_invoice(
chat_id, title, description, payload, PAYMENT_PROVIDER_TOKEN, currency, prices
)
2017-06-10 21:43:38 +02:00
async def shipping_callback(update: Update, context: CallbackContext.DEFAULT_TYPE) -> None:
"""Answers the ShippingQuery with ShippingOptions"""
2017-06-10 21:43:38 +02:00
query = update.shipping_query
# check the payload, is this from your bot?
if query.invoice_payload != 'Custom-Payload':
# answer False pre_checkout_query
await query.answer(ok=False, error_message="Something went wrong...")
2017-06-10 21:43:38 +02:00
return
# First option has a single LabeledPrice
options = [ShippingOption('1', 'Shipping Option A', [LabeledPrice('A', 100)])]
# second option has an array of LabeledPrice objects
price_list = [LabeledPrice('B1', 150), LabeledPrice('B2', 200)]
options.append(ShippingOption('2', 'Shipping Option B', price_list))
await query.answer(ok=True, shipping_options=options)
2017-06-10 21:43:38 +02:00
# after (optional) shipping, it's the pre-checkout
async def precheckout_callback(update: Update, context: CallbackContext.DEFAULT_TYPE) -> None:
"""Answers the PreQecheckoutQuery"""
2017-06-10 21:43:38 +02:00
query = update.pre_checkout_query
# check the payload, is this from your bot?
if query.invoice_payload != 'Custom-Payload':
# answer False pre_checkout_query
await query.answer(ok=False, error_message="Something went wrong...")
2017-06-10 21:43:38 +02:00
else:
await query.answer(ok=True)
2017-06-10 21:43:38 +02:00
2019-10-11 20:10:21 +02:00
# finally, after contacting the payment provider...
async def successful_payment_callback(
update: Update, context: CallbackContext.DEFAULT_TYPE
) -> None:
"""Confirms the successful payment."""
2019-10-11 20:10:21 +02:00
# do something after successfully receiving payment?
await update.message.reply_text("Thank you for your payment!")
2017-06-10 21:43:38 +02:00
def main() -> None:
"""Run the bot."""
# Create the Application and pass it your bot's token.
application = Application.builder().token("TOKEN").build()
2017-06-10 21:43:38 +02:00
# simple start function
application.add_handler(CommandHandler("start", start_callback))
2017-06-10 21:43:38 +02:00
# Add command handler to start the payment invoice
application.add_handler(CommandHandler("shipping", start_with_shipping_callback))
application.add_handler(CommandHandler("noshipping", start_without_shipping_callback))
2017-06-10 21:43:38 +02:00
# Optional handler if your product requires shipping
application.add_handler(ShippingQueryHandler(shipping_callback))
2017-06-10 21:43:38 +02:00
# Pre-checkout handler to final check
application.add_handler(PreCheckoutQueryHandler(precheckout_callback))
2017-06-10 21:43:38 +02:00
# Success! Notify your user!
application.add_handler(
MessageHandler(filters.SUCCESSFUL_PAYMENT, successful_payment_callback)
)
2017-06-10 21:43:38 +02:00
# Run the bot until the user presses Ctrl-C
application.run_polling()
2017-06-10 21:43:38 +02:00
if __name__ == '__main__':
main()