python payment in Web3 TON Token

I want to make a bot with payment in Web3 TON Token, but I can’t do it. For some reason, after connecting the wallet, payment is made in ton and not in Web3 TON Token

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import asyncio
from datetime import datetime
from tonsdk.utils import Address
from nacl.utils import random
from pytonconnect import TonConnect
from pytonconnect.parsers import WalletInfo
from telegram import Update, Bot, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Application, CommandHandler, CallbackContext
import time
import json
import tracemalloc
tracemalloc.start()
def generate_payload(ttl: int) -> str:
payload = bytearray(random(8))
ts = int(datetime.now().timestamp()) + ttl
payload.extend(ts.to_bytes(8, 'big'))
return payload.hex()
# Перевірка payload
def check_payload(payload: str, wallet_info: WalletInfo):
if len(payload) < 32:
return False
if not wallet_info.check_proof(payload):
return False
ts = int(payload[16:32], 16)
if datetime.now().timestamp() > ts:
return False
return True
# Функція для створення платіжного запиту
async def create_payment_request(connector: TonConnect):
proof_payload = generate_payload(600)
wallets_list = connector.get_wallets()
for i in wallets_list:
print(i['name'])
if wallets_list:
generated_url = await connector.connect(wallets_list[0], {'ton_proof': proof_payload})
return generated_url, proof_payload
return None, None
# Функція для відправлення транзакцій
async def send_transaction(connector: TonConnect, transaction):
try:
# Використовуємо await для асинхронної операції
result = await connector.send_transaction(transaction)
if "boc" in result:
return "Дякую за оплату! Транзакція пройшла успішно."
else:
return f"Помилка при відправленні транзакції: {result}"
except Exception as e:
return f"Неізвестна помилка: {str(e)}"
# Команда /start для бота
async def start(update: Update, context: CallbackContext):
chat_id = update.message.chat_id
bot = context.bot
connector = TonConnect(manifest_url='https://raw.githubusercontent.com/XaBbl4/pytonconnect/main/pytonconnect-manifest.json')
try:
generated_url, proof_payload = await create_payment_request(connector)
if generated_url:
keyboard = [[InlineKeyboardButton("Connect Wallet", url=generated_url)]]
reply_markup = InlineKeyboardMarkup(keyboard)
await bot.send_message(chat_id=chat_id, text="Click the button below to connect your wallet:", reply_markup=reply_markup)
def status_changed(wallet_info):
async def process_status_change():
try:
print(wallet_info)
if wallet_info is not None and check_payload(proof_payload, wallet_info):
transaction = {
'valid_until': int(time.time()) + 3600, # Дійсно протягом 1 години
'messages': [
{
'address': WALLET_ADDRESS,
'amount': str(PAYMENT_AMOUNT), # Сума в найменшій одиниці
'token': WEB3_TON_TOKEN_ADDRESS # Адреса токена
}
]
}
# Асинхронний виклик транзакції
result = await send_transaction(connector, transaction)
await bot.send_message(chat_id, result)
else:
await bot.send_message(chat_id, "Failed to verify the wallet info.")
except Exception as e:
error_message = f"Error in status change: {str(e)}"
print(error_message)
await bot.send_message(chat_id, error_message)
asyncio.create_task(process_status_change())
def status_error(e):
async def process_error():
try:
error_message = f"Connection error: {str(e)}"
await bot.send_message(chat_id, error_message)
except Exception as e:
print(f"Error sending message: {e}")
asyncio.create_task(process_error())
connector.on_status_change(status_changed, status_error)
except Exception as e:
await bot.send_message(chat_id, f"An error occurred: {str(e)}")
# Основна функція для запуску бота
def main():
loop = asyncio.get_event_loop()
application = Application.builder().token(TOKEN).build()
application.add_handler(CommandHandler("start", start))
loop.run_until_complete(application.run_polling())
if __name__ == '__main__':
main()
</code>
<code>import asyncio from datetime import datetime from tonsdk.utils import Address from nacl.utils import random from pytonconnect import TonConnect from pytonconnect.parsers import WalletInfo from telegram import Update, Bot, InlineKeyboardButton, InlineKeyboardMarkup from telegram.ext import Application, CommandHandler, CallbackContext import time import json import tracemalloc tracemalloc.start() def generate_payload(ttl: int) -> str: payload = bytearray(random(8)) ts = int(datetime.now().timestamp()) + ttl payload.extend(ts.to_bytes(8, 'big')) return payload.hex() # Перевірка payload def check_payload(payload: str, wallet_info: WalletInfo): if len(payload) < 32: return False if not wallet_info.check_proof(payload): return False ts = int(payload[16:32], 16) if datetime.now().timestamp() > ts: return False return True # Функція для створення платіжного запиту async def create_payment_request(connector: TonConnect): proof_payload = generate_payload(600) wallets_list = connector.get_wallets() for i in wallets_list: print(i['name']) if wallets_list: generated_url = await connector.connect(wallets_list[0], {'ton_proof': proof_payload}) return generated_url, proof_payload return None, None # Функція для відправлення транзакцій async def send_transaction(connector: TonConnect, transaction): try: # Використовуємо await для асинхронної операції result = await connector.send_transaction(transaction) if "boc" in result: return "Дякую за оплату! Транзакція пройшла успішно." else: return f"Помилка при відправленні транзакції: {result}" except Exception as e: return f"Неізвестна помилка: {str(e)}" # Команда /start для бота async def start(update: Update, context: CallbackContext): chat_id = update.message.chat_id bot = context.bot connector = TonConnect(manifest_url='https://raw.githubusercontent.com/XaBbl4/pytonconnect/main/pytonconnect-manifest.json') try: generated_url, proof_payload = await create_payment_request(connector) if generated_url: keyboard = [[InlineKeyboardButton("Connect Wallet", url=generated_url)]] reply_markup = InlineKeyboardMarkup(keyboard) await bot.send_message(chat_id=chat_id, text="Click the button below to connect your wallet:", reply_markup=reply_markup) def status_changed(wallet_info): async def process_status_change(): try: print(wallet_info) if wallet_info is not None and check_payload(proof_payload, wallet_info): transaction = { 'valid_until': int(time.time()) + 3600, # Дійсно протягом 1 години 'messages': [ { 'address': WALLET_ADDRESS, 'amount': str(PAYMENT_AMOUNT), # Сума в найменшій одиниці 'token': WEB3_TON_TOKEN_ADDRESS # Адреса токена } ] } # Асинхронний виклик транзакції result = await send_transaction(connector, transaction) await bot.send_message(chat_id, result) else: await bot.send_message(chat_id, "Failed to verify the wallet info.") except Exception as e: error_message = f"Error in status change: {str(e)}" print(error_message) await bot.send_message(chat_id, error_message) asyncio.create_task(process_status_change()) def status_error(e): async def process_error(): try: error_message = f"Connection error: {str(e)}" await bot.send_message(chat_id, error_message) except Exception as e: print(f"Error sending message: {e}") asyncio.create_task(process_error()) connector.on_status_change(status_changed, status_error) except Exception as e: await bot.send_message(chat_id, f"An error occurred: {str(e)}") # Основна функція для запуску бота def main(): loop = asyncio.get_event_loop() application = Application.builder().token(TOKEN).build() application.add_handler(CommandHandler("start", start)) loop.run_until_complete(application.run_polling()) if __name__ == '__main__': main() </code>
import asyncio
from datetime import datetime
from tonsdk.utils import Address
from nacl.utils import random
from pytonconnect import TonConnect
from pytonconnect.parsers import WalletInfo
from telegram import Update, Bot, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Application, CommandHandler, CallbackContext
import time
import json
import tracemalloc
tracemalloc.start()

def generate_payload(ttl: int) -> str:
    payload = bytearray(random(8))
    ts = int(datetime.now().timestamp()) + ttl
    payload.extend(ts.to_bytes(8, 'big'))
    return payload.hex()

# Перевірка payload
def check_payload(payload: str, wallet_info: WalletInfo):
    if len(payload) < 32:
        return False
    if not wallet_info.check_proof(payload):
        return False
    ts = int(payload[16:32], 16)
    if datetime.now().timestamp() > ts:
        return False
    return True

# Функція для створення платіжного запиту
async def create_payment_request(connector: TonConnect):
    proof_payload = generate_payload(600)
    wallets_list = connector.get_wallets()
    for i in wallets_list:
        print(i['name'])
    if wallets_list:
        generated_url = await connector.connect(wallets_list[0], {'ton_proof': proof_payload})
        return generated_url, proof_payload
    return None, None

# Функція для відправлення транзакцій
async def send_transaction(connector: TonConnect, transaction):
    try:
        # Використовуємо await для асинхронної операції
        result = await connector.send_transaction(transaction)
        if "boc" in result:
            return "Дякую за оплату! Транзакція пройшла успішно."
        else:
            return f"Помилка при відправленні транзакції: {result}"
    except Exception as e:
        return f"Неізвестна помилка: {str(e)}"

# Команда /start для бота
async def start(update: Update, context: CallbackContext):
    chat_id = update.message.chat_id
    bot = context.bot
    connector = TonConnect(manifest_url='https://raw.githubusercontent.com/XaBbl4/pytonconnect/main/pytonconnect-manifest.json')

    try:
        generated_url, proof_payload = await create_payment_request(connector)
        if generated_url:
            keyboard = [[InlineKeyboardButton("Connect Wallet", url=generated_url)]]
            reply_markup = InlineKeyboardMarkup(keyboard)
            await bot.send_message(chat_id=chat_id, text="Click the button below to connect your wallet:", reply_markup=reply_markup)

            def status_changed(wallet_info):
                async def process_status_change():
                    try:
                        print(wallet_info)
                        if wallet_info is not None and check_payload(proof_payload, wallet_info):
                            transaction = {
                                'valid_until': int(time.time()) + 3600,  # Дійсно протягом 1 години
                                'messages': [
                                    {
                                        'address': WALLET_ADDRESS,
                                        'amount': str(PAYMENT_AMOUNT),  # Сума в найменшій одиниці
                                        'token': WEB3_TON_TOKEN_ADDRESS  # Адреса токена
                                    }
                                ]
                            }
                            # Асинхронний виклик транзакції
                            result = await send_transaction(connector, transaction)
                            await bot.send_message(chat_id, result)
                        else:
                            await bot.send_message(chat_id, "Failed to verify the wallet info.")
                    except Exception as e:
                        error_message = f"Error in status change: {str(e)}"
                        print(error_message)
                        await bot.send_message(chat_id, error_message)

                asyncio.create_task(process_status_change())

            def status_error(e):
                async def process_error():
                    try:
                        error_message = f"Connection error: {str(e)}"
                        await bot.send_message(chat_id, error_message)
                    except Exception as e:
                        print(f"Error sending message: {e}")

                asyncio.create_task(process_error())

            connector.on_status_change(status_changed, status_error)
    except Exception as e:
        await bot.send_message(chat_id, f"An error occurred: {str(e)}")

# Основна функція для запуску бота
def main():
    loop = asyncio.get_event_loop()
    application = Application.builder().token(TOKEN).build()
    application.add_handler(CommandHandler("start", start))
    loop.run_until_complete(application.run_polling())

if __name__ == '__main__':
    main()

how to implement payment in Web3 TON Token with wallet connection? Maybe you need to use another library, or am I somehow not forming the request correctly?

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật