Skip to content

Commit ad603bd

Browse files
committed
add new payment example
1 parent da8a3ce commit ad603bd

1 file changed

Lines changed: 145 additions & 0 deletions

File tree

examples/paymentbot.py

Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
#
4+
# Basic example for a bot that can receive payment from user.
5+
# This program is dedicated to the public domain under the CC0 license.
6+
7+
from telegram import (LabeledPrice, ShippingOption)
8+
from telegram.ext import (Updater, CommandHandler, MessageHandler,
9+
Filters, PreCheckoutQueryHandler, ShippingQueryHandler)
10+
import logging
11+
12+
# Enable logging
13+
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
14+
15+
logger = logging.getLogger(__name__)
16+
17+
18+
def error(bot, update, error):
19+
logger.warn('Update "%s" caused error "%s"' % (update, error))
20+
21+
22+
def start_callback(bot, update):
23+
msg = "Use /shipping to get an invoice for shipping-payment, "
24+
msg += "or /noshipping for an invoice without shipping."
25+
update.message.reply_text(msg)
26+
27+
28+
def start_with_shipping_callback(bot, update):
29+
chat_id = update.message.chat_id
30+
title = "Payment Example"
31+
description = "Payment Example using python-telegram-bot"
32+
# select a payload just for you to recognize its the donation from your bot
33+
payload = "Custom-Payload"
34+
# get your provider_token at @botfather, see https://core.telegram.org/bots/payments#getting-a-token
35+
provider_token = "PROVIDER_TOKEN"
36+
start_parameter = "test-payment"
37+
currency = "USD"
38+
# price in dollars
39+
price = 1
40+
# price * 100 so as to include 2 d.p.
41+
prices = [LabeledPrice("Test", price * 100)]
42+
43+
# optionally pass need_name=True, need_phone_number=True,
44+
# need_email=True, need_shipping_address=True, is_flexible=True
45+
bot.sendInvoice(chat_id, title, description, payload,
46+
provider_token, start_parameter, currency, prices,
47+
need_name=True, need_phone_number=True,
48+
need_email=True, need_shipping_address=True, is_flexible=True)
49+
50+
51+
def start_without_shipping_callback(bot, update):
52+
chat_id = update.message.chat_id
53+
title = "Payment Example"
54+
description = "Payment Example using python-telegram-bot"
55+
# select a payload just for you to recognize its the donation from your bot
56+
payload = "Custom-Payload"
57+
# get your provider_token at @botfather, see https://core.telegram.org/bots/payments#getting-a-token
58+
provider_token = "PROVIDER_TOKEN"
59+
start_parameter = "test-payment"
60+
currency = "USD"
61+
# price in dollars
62+
price = 1
63+
# price * 100 so as to include 2 d.p.
64+
prices = [LabeledPrice("Test", price * 100)]
65+
66+
# optionally pass need_name=True, need_phone_number=True,
67+
# need_email=True, need_shipping_address=True, is_flexible=True
68+
bot.sendInvoice(chat_id, title, description, payload,
69+
provider_token, start_parameter, currency, prices)
70+
71+
72+
def shipping_callback(bot, update):
73+
query = update.shipping_query
74+
# check the payload, is this from your bot?
75+
if query.invoice_payload != 'Custom-Payload':
76+
# answer False pre_checkout_query
77+
bot.answerShippingQuery(shipping_query_id=query.id, ok=False,
78+
error_message="Something went wrong...")
79+
return
80+
else:
81+
options = list()
82+
# a single LabeledPrice
83+
options.append(ShippingOption('1', 'Shipping Option A', [LabeledPrice('A', 100)]))
84+
# an array of LabeledPrice objects
85+
price_list = [LabeledPrice('B1', 150), LabeledPrice('B2', 200)]
86+
options.append(ShippingOption('2', 'Shipping Option B', price_list))
87+
bot.answerShippingQuery(shipping_query_id=query.id, ok=True,
88+
shipping_options=options)
89+
90+
91+
# after (optional) shipping, it's the pre-checkout
92+
def precheckout_callback(bot, update):
93+
query = update.pre_checkout_query
94+
# check the payload, is this from your bot?
95+
if query.invoice_payload != 'Custom-Payload':
96+
# answer False pre_checkout_query
97+
bot.answerPreCheckoutQuery(pre_checkout_query_id=query.id, ok=False,
98+
error_message="Something went wrong...")
99+
else:
100+
bot.answerPreCheckoutQuery(pre_checkout_query_id=query.id, ok=True)
101+
102+
103+
# finally, after contacting to the payment provider...
104+
def successful_payment_callback(bot, update):
105+
# do something after successful receive of payment?
106+
update.message.reply_text("Thank you for your payment!")
107+
108+
109+
def main():
110+
# Create the EventHandler and pass it your bot's token.
111+
updater = Updater(token="BOT_TOKEN")
112+
113+
# Get the dispatcher to register handlers
114+
dp = updater.dispatcher
115+
116+
# simple start function
117+
dp.add_handler(CommandHandler("start", start_callback))
118+
119+
# Add command handler to start the payment invoice
120+
dp.add_handler(CommandHandler("shipping", start_with_shipping_callback))
121+
dp.add_handler(CommandHandler("noshipping", start_without_shipping_callback))
122+
123+
# Optional handler if your product requires shipping
124+
dp.add_handler(ShippingQueryHandler(shipping_callback))
125+
126+
# Pre-checkout handler to final check
127+
dp.add_handler(PreCheckoutQueryHandler(precheckout_callback))
128+
129+
# Success! Notify your user!
130+
dp.add_handler(MessageHandler(Filters.successful_payment, successful_payment_callback))
131+
132+
# log all errors
133+
dp.add_error_handler(error)
134+
135+
# Start the Bot
136+
updater.start_polling()
137+
138+
# Run the bot until you press Ctrl-C or the process receives SIGINT,
139+
# SIGTERM or SIGABRT. This should be used most of the time, since
140+
# start_polling() is non-blocking and will stop the bot gracefully.
141+
updater.idle()
142+
143+
144+
if __name__ == '__main__':
145+
main()

0 commit comments

Comments
 (0)