1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
| import logging from datetime import datetime
import requests from flask import Flask, request, jsonify from flask_cors import CORS
app = Flask(__name__) CORS(app)
logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s' ) logger = logging.getLogger(__name__)
TELEGRAM_BOT_TOKEN = "-poY" TELEGRAM_API_URL = f'https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}'
payment_records = {}
@app.route('/create_payment', methods=['POST']) def create_payment(): try: data = request.json chat_id = data.get('chat_id') user_id = data.get('user_id') product_id = data.get('product_id') amount = data.get('amount') payment_id = data.get('payment_id')
logger.info(f"payment_id: {payment_id} chat_id: {chat_id} user_id: {user_id}")
if not all([chat_id, user_id, product_id, amount, payment_id]): return jsonify({ 'success': False, 'error': '缺少必要参数' }), 400
payment_records[payment_id] = { 'chat_id': chat_id, 'user_id': user_id, 'product_id': product_id, 'amount': amount, 'status': 'pending', 'created_at': datetime.utcnow().isoformat() }
invoice_data = { 'chat_id': chat_id, 'title': '测试商品', 'description': '这是一个测试商品的描述', 'payload': payment_id, 'currency': 'XTR', 'prices': [{ 'label': '商品价格', 'amount': amount }], 'start_parameter': payment_id }
response = requests.post(f'{TELEGRAM_API_URL}/createInvoiceLink', json=invoice_data) result = response.json()
if result.get('ok'): return jsonify({ 'success': True, 'invoice_url': result['result'] }) else: return jsonify({ 'success': False, 'error': result.get('description', '创建发票失败') })
except Exception as e: return jsonify({ 'success': False, 'error': str(e) }), 500
@app.route('/webhook', methods=['POST']) def webhook(): try: data = request.json
if 'pre_checkout_query' in data: logger.info(f"pre_checkout_query") pre_checkout_query = data['pre_checkout_query'] query_id = pre_checkout_query['id'] payment_id = pre_checkout_query['invoice_payload']
logger.info(f"query_id: {query_id} payment_id: {payment_id}")
payment_info = payment_records.get(payment_id) if not payment_info: response = requests.post(f'{TELEGRAM_API_URL}/answerPreCheckoutQuery', json={ 'pre_checkout_query_id': query_id, 'ok': False, 'error_message': '找不到支付记录' }) return '', 200
response = requests.post(f'{TELEGRAM_API_URL}/answerPreCheckoutQuery', json={ 'pre_checkout_query_id': query_id, 'ok': True })
logger.info(f"通过预支付")
payment_records[payment_id]['status'] = 'pre_checkout_approved'
elif 'message' in data and 'successful_payment' in data['message']: logger.info(f"successful_payment") successful_payment = data['message']['successful_payment'] payment_id = successful_payment['invoice_payload'] logger.info(f"successful_payment: {successful_payment} payment_id: {payment_id}")
if payment_id in payment_records: payment_records[payment_id]['status'] = 'completed' payment_records[payment_id]['completed_at'] = datetime.utcnow().isoformat()
return '', 200
except Exception as e: logger.error(f"Webhook error: {str(e)}") return '', 500
def setup_webhook(): """设置 Webhook""" requests.post(f"{TELEGRAM_API_URL}/deleteWebhook")
webhook_url = "https://tgapi.thlm.bond/webhook" set_url = f"{TELEGRAM_API_URL}/setWebhook" set_payload = { "url": webhook_url, "allowed_updates": ["message", "pre_checkout_query", "callback_query"] } response = requests.post(set_url, json=set_payload) logger.info("Webhook 设置结果:", response.json())
return response.json()
if __name__ == '__main__': setup_webhook() app.run(host='127.0.0.1', port=8443)
|