### Flask Webhook Setup with aiosend Source: https://github.com/vovchic17/aiosend/blob/dev/docs/events/webhook.md Demonstrates integrating aiosend webhooks with a Flask web server. The example provides the installation command and illustrates how to initialize CryptoPay using FlaskManager. ```bash pip install aiosend[flask] ``` ```python import asyncio from flask import Flask from aiosend import CryptoPay from aiosend.types import Invoice from aiosend.webhook import FlaskManager app = Flask(__name__) cp = CryptoPay( "TOKEN", webhook_manager=FlaskManager(app, "/handler"), ) @cp.invoice_paid() async def handler(invoice: Invoice) -> None: print(f"Received {invoice.amount} {invoice.asset}") async def main() -> None: invoice = await cp.create_invoice(1, "USDT") print("invoice link:", invoice.bot_invoice_url) if __name__ == "__main__": asyncio.run(main()) app.run() ``` -------------------------------- ### Create and Manage Check (Example) Source: https://github.com/vovchic17/aiosend/blob/dev/docs/client/shortcuts.md This example shows how to create a check, retrieve its QR code, get a preview image with fiat conversion, and then delete the check. It highlights the usage of check-specific methods. ```python import asyncio from aiosend import CryptoPay async def main() -> None: cp = CryptoPay("TOKEN") check = await cp.create_check(1, "USDT") # invoice preview image with fiat conversion print(await check.get_image("USD")) print(check.qr) # check qr code link await check.delete() # delete check if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### FastAPI Webhook Setup with aiosend Source: https://github.com/vovchic17/aiosend/blob/dev/docs/events/webhook.md This example shows how to integrate aiosend webhooks with a FastAPI application. It includes the necessary installation command and demonstrates setting up the CryptoPay instance with FastAPIManager. ```bash pip install aiosend[fastapi] ``` ```python import asyncio import uvicorn from fastapi import FastAPI from aiosend import CryptoPay from aiosend.types import Invoice from aiosend.webhook import FastAPIManager app = FastAPI() cp = CryptoPay( "TOKEN", webhook_manager=FastAPIManager(app, "/handler"), ) @cp.invoice_paid() async def handler(invoice: Invoice) -> None: print(f"Received {invoice.amount} {invoice.asset}") async def main() -> None: invoice = await cp.create_invoice(1, "USDT") print("invoice link:", invoice.bot_invoice_url) if __name__ == "__main__": asyncio.run(main()) uvicorn.run(app) ``` -------------------------------- ### Create and Manage Invoice (Example) Source: https://github.com/vovchic17/aiosend/blob/dev/docs/client/shortcuts.md This example demonstrates creating an invoice, checking its status, updating it after a payment, retrieving its QR code, and finally deleting it. It showcases the asynchronous nature of the aiosend library. ```python import asyncio from aiosend import CryptoPay async def main() -> None: cp = CryptoPay("TOKEN") invoice = await cp.create_invoice(1, "USDT") print(invoice.status) # active await asyncio.sleep(10) # payment await invoice.update() print(invoice.status) # paid print(invoice.qr) # qr code link await invoice.delete() # delete the invoice if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### aiohttp Webhook Setup with aiosend Source: https://github.com/vovchic17/aiosend/blob/dev/docs/events/webhook.md Example demonstrating how to set up a webhook handler for aiosend using an aiohttp web server. It shows creating a CryptoPay instance with AiohttpManager and defining an invoice_paid event handler. ```python import asyncio from aiohttp.web import Application, _run_app from aiosend import CryptoPay from aiosend.types import Invoice from aiosend.webhook import AiohttpManager app = Application() cp = CryptoPay( "TOKEN", webhook_manager=AiohttpManager(app, "/handler"), ) @cp.invoice_paid() async def handler(invoice: Invoice) -> None: print(f"Received {invoice.amount} {invoice.asset}") async def main() -> None: invoice = await cp.create_invoice(1, "USDT") print("invoice link:", invoice.bot_invoice_url) await _run_app(app) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Python Invoice Polling Example Source: https://github.com/vovchic17/aiosend/blob/dev/docs/events/invoice_polling.md This example demonstrates how to set up invoice paid and expired handlers, create an invoice, and start the polling process using the aiosend library. It utilizes asyncio for asynchronous operations. ```python import asyncio from aiosend import CryptoPay from aiosend.types import Invoice cp = CryptoPay("TOKEN") @cp.invoice_paid() async def payment_handler(invoice: Invoice, payload: str) -> None: print("Received", invoice.amount, invoice.asset, payload) @cp.invoice_expired() async def expired_invoice_handler(invoice: Invoice, payload: str) -> None: print("Expired invoice", invoice.invoice_id, payload) async def main() -> None: invoice = await cp.create_invoice(1, "USDT") print("invoice link:", invoice.bot_invoice_url) invoice.poll(payload="payload") await cp.start_polling() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Initialize CryptoPay Client (Python) Source: https://context7.com/vovchic17/aiosend/llms.txt Demonstrates how to initialize the CryptoPay client for both mainnet and testnet environments. Includes examples for asynchronous and synchronous usage, along with basic token validation. ```python import asyncio from aiosend import CryptoPay, MAINNET, TESTNET # Basic async initialization (mainnet by default) async def main(): cp = CryptoPay(token="YOUR_CRYPTO_PAY_API_TOKEN") app = await cp.get_me() print(f"App name: {app.name}") print(f"App ID: {app.app_id}") asyncio.run(main()) # Testnet initialization test_client = CryptoPay( token="YOUR_TESTNET_TOKEN", network=TESTNET, ) # Synchronous usage (blocking) from aiosend import CryptoPay cp = CryptoPay("TOKEN") app = cp.get_me() # Works synchronously without async/await print(app.name) ``` -------------------------------- ### Install aiosend Python Package Source: https://context7.com/vovchic17/aiosend/llms.txt Installs the aiosend library using pip. This is the primary method to add the Crypto Pay API client to your Python project. ```bash pip install aiosend ``` -------------------------------- ### Install aiosend via package managers Source: https://github.com/vovchic17/aiosend/blob/dev/docs/install.md Commands to install the aiosend library using different Python package managers. Ensure you have the respective tool installed in your environment before running these commands. ```bash pip install -U aiosend ``` ```bash pip install https://github.com/vovchic17/aiosend/archive/refs/heads/main.zip ``` ```bash uv add aiosend ``` ```bash poetry add aiosend ``` ```bash pdm add aiosend ``` ```bash pipx install aiosend ``` ```bash rye add aiosend ``` ```bash conda install aiosend ``` ```bash pipenv install aiosend ``` -------------------------------- ### Implement Check Polling with AIOSend Source: https://github.com/vovchic17/aiosend/blob/dev/docs/events/check_polling.md This example demonstrates how to initialize the CryptoPay client, define handlers for activated and expired checks using decorators, and start the polling process for a created check. It utilizes the asyncio library to manage asynchronous operations. ```python import asyncio from aiosend import CryptoPay from aiosend.types import Check cp = CryptoPay("TOKEN") @cp.check_activated() async def check_handler(check: Check, payload: str) -> None: print("Received", check.amount, check.asset, payload) @cp.check_expired() async def expired_check_handler(check: Check, payload: str) -> None: print("Expired check", check.check_id, payload) async def main() -> None: check = await cp.create_check(1, "USDT") print("check link:", check.check_id) check.poll(payload="payload") await cp.start_polling() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Create and Poll Invoices with aiosend Source: https://github.com/vovchic17/aiosend/blob/dev/docs/events/filters.md Demonstrates initializing the CryptoPay client, creating invoices, and starting the polling process to monitor invoice status. ```python import asyncio from aiosend import CryptoPay from aiosend.types import Invoice cp = CryptoPay("TOKEN") async def main() -> None: invoice1 = await cp.create_invoice( 1, "USDT", payload="product1", ) invoice2 = await cp.create_invoice( 1, "USDT", payload="product2", ) print(invoice1.bot_invoice_url) print(invoice2.bot_invoice_url) invoice1.poll() invoice2.poll() await cp.start_polling() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Initialize and Use aiosend Client Source: https://github.com/vovchic17/aiosend/blob/dev/docs/index.md Demonstrates how to initialize the CryptoPay client and perform a basic API call to retrieve application details. This example uses the asynchronous pattern with asyncio. ```python import asyncio from aiosend import CryptoPay async def main() -> None: cp = CryptoPay(token="TOKEN") app = await cp.get_me() print(app.name) # Your App's Name if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### GET /getMe Source: https://github.com/vovchic17/aiosend/blob/dev/docs/api/methods.md Test the application's authentication token and retrieve basic app information. ```APIDOC ## GET /getMe ### Description Use this method to test your app’s authentication token. On success, returns basic information about an app. ### Method GET ### Endpoint /getMe ### Parameters None ### Response #### Success Response (200) - **app** (Object) - Basic information about the application. #### Response Example { "ok": true, "result": { "app_id": 12345, "name": "My Crypto App" } } ``` -------------------------------- ### Configure and Start Polling in aiosend Source: https://github.com/vovchic17/aiosend/blob/dev/docs/events/polling_config.md Demonstrates how to initialize the CryptoPay client with a custom PollingConfig, define event handlers for paid and expired invoices, and initiate the polling process. ```python import asyncio from aiosend import CryptoPay from aiosend.polling import PollingConfig from aiosend.types import Invoice cp = CryptoPay( "TOKEN", polling_config=PollingConfig( timeout=600, # 10 minutes delay=3, # request every 3 seconds ), ) @cp.invoice_paid() async def handler(invoice: Invoice) -> None: print("Received", invoice.amount, invoice.asset) @cp.invoice_expired() async def expired_invoice_handler(invoice: Invoice, payload: str) -> None: print("Expired invoice", invoice.invoice_id, payload) async def main() -> None: invoice = await cp.create_invoice(1, "USDT") print("invoice link:", invoice.bot_invoice_url) invoice.poll() await cp.start_polling() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Create and handle CryptoPay invoices in python-telegram-bot Source: https://github.com/vovchic17/aiosend/blob/dev/docs/integration_examples/ptb.md This example shows how to initialize the CryptoPay client, create an invoice, and register a decorator to handle payment events. It uses the python-telegram-bot library to interact with users and process messages. ```python import asyncio from telegram import Message, Update from telegram.ext import ( Application, ContextTypes, MessageHandler, filters, ) from aiosend import CryptoPay from aiosend.types import Invoice cp = CryptoPay("TOKEN") app = Application.builder().token("TOKEN").build() async def get_invoice( update: Update, context: ContextTypes.DEFAULT_TYPE, ) -> None: invoice = await cp.create_invoice(1, "USDT") await update.message.reply_text(f"pay: {invoice.mini_app_invoice_url}") invoice.poll(message=update.message) @cp.invoice_paid() async def handle_payment( invoice: Invoice, message: Message, ) -> None: await message.reply_text( f"payment received: {invoice.amount} {invoice.asset}", ) async def main() -> None: app.add_handler(MessageHandler(filters.TEXT, get_invoice)) await app.initialize() await app.start() await asyncio.gather( app.updater.start_polling(allowed_updates=Update.ALL_TYPES), cp.start_polling(), ) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Implementing Dependency Injection with CryptoPay Source: https://github.com/vovchic17/aiosend/blob/dev/docs/client/di.md This example demonstrates how to inject variables into the CryptoPay client via constructor arguments, dictionary-style assignment, and method keyword arguments. These injected values are then accessed within an invoice_paid event handler. ```python import asyncio from aiosend import CryptoPay from aiosend.types import Invoice cp = CryptoPay("TOKEN", var1="value1") # injection cp["var2"] = "value2" # injection async def main() -> None: invoice = await cp.create_invoice(1, "USDT") print("invoice link:", invoice.bot_invoice_url) invoice.poll(var3="value3") # injection await cp.start_polling() @cp.invoice_paid() async def payment_handler( invoice: Invoice, var1: str, # this one is from constructor var2: str, # this one is from key assignment var3: str, # this one is from poll method kwargs ) -> None: print(f"Invoice #{invoice.invoice_id} {var1=} {var2=} {var3=}") if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Integrate CryptoPay with aiogram 3.x Source: https://github.com/vovchic17/aiosend/blob/dev/docs/integration_examples/aiogram3.md This example shows how to set up a bot that creates a CryptoPay invoice and listens for payment events. It uses the aiosend library to manage the invoice lifecycle and polling within an aiogram application. ```python import asyncio from aiogram import Bot, Dispatcher from aiogram.types import Message from aiosend import CryptoPay from aiosend.types import Invoice cp = CryptoPay("TOKEN") bot = Bot("TOKEN") dp = Dispatcher() @dp.message() async def get_invoice(message: Message) -> None: invoice = await cp.create_invoice(1, "USDT") await message.answer(f"pay: {invoice.mini_app_invoice_url}") invoice.poll(message=message) @cp.invoice_paid() async def handle_payment( invoice: Invoice, message: Message, ) -> None: await message.answer( f"payment received: {invoice.amount} {invoice.asset}", ) async def main() -> None: await asyncio.gather( dp.start_polling(bot), cp.start_polling(), ) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### GET /getMe Source: https://github.com/vovchic17/aiosend/blob/dev/docs/api/index.md Retrieves information about the current application using the Crypto Pay API. ```APIDOC ## GET /getMe ### Description A method to retrieve basic information about the application associated with the API key. ### Method GET ### Endpoint /getMe ### Parameters None ### Response #### Success Response (200) - **app** (App) - Returns an App object containing application details. #### Response Example { "ok": true, "result": { "app_id": 12345, "name": "My Crypto App" } } ``` -------------------------------- ### aiosend with python-telegram-bot Integration Source: https://github.com/vovchic17/aiosend/blob/dev/docs/integration_examples/ptb.md This example demonstrates how to use the aiosend CryptoPay client to create payment invoices and handle payment confirmations within a python-telegram-bot application. ```APIDOC ## aiosend CryptoPay Integration Example ### Description This code snippet shows a complete example of integrating the `aiosend` library with `python-telegram-bot` to create cryptocurrency payment invoices and listen for payment confirmation events. ### Method N/A (Illustrative Example) ### Endpoint N/A (Illustrative Example) ### Parameters N/A (Illustrative Example) ### Request Example ```python import asyncio from telegram import Message, Update from telegram.ext import ( Application, ContextTypes, MessageHandler, filters, ) from aiosend import CryptoPay from aiosend.types import Invoice # Initialize CryptoPay with your API token cp = CryptoPay("YOUR_CRYPTO_PAY_TOKEN") # Initialize Telegram Bot Application app = Application.builder().token("YOUR_TELEGRAM_BOT_TOKEN").build() async def get_invoice(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: """Creates a payment invoice and sends the mini-app URL to the user.""" # Create an invoice for 1 USDT invoice = await cp.create_invoice(1, "USDT") await update.message.reply_text(f"Please pay using this link: {invoice.mini_app_invoice_url}") # Start polling for payment status for this invoice, linked to the Telegram message invoice.poll(message=update.message) @cp.invoice_paid() async def handle_payment(invoice: Invoice, message: Message) -> None: """Callback function executed when an invoice is paid.""" await message.reply_text( f"Payment received successfully! Amount: {invoice.amount} {invoice.asset}", ) async def main() -> None: """Sets up and runs the Telegram bot and aiosend polling.""" # Add a message handler for text messages to trigger invoice creation app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, get_invoice)) # Initialize and start the Telegram bot application await app.initialize() await app.start() # Run both Telegram bot polling and aiosend polling concurrently await asyncio.gather( app.updater.start_polling(allowed_updates=Update.ALL_TYPES), cp.start_polling(), ) if __name__ == "__main__": asyncio.run(main()) ``` ### Response #### Success Response (200) N/A (Illustrative Example) #### Response Example N/A (Illustrative Example) ``` -------------------------------- ### Asynchronous Telegram Bot Payment Integration Source: https://github.com/vovchic17/aiosend/blob/dev/docs/integration_examples/pytba_async.md This example shows how to initialize an AsyncTeleBot and CryptoPay instance to handle invoice creation and payment notifications. It utilizes asyncio.gather to run both the bot polling and the payment polling concurrently. ```python import asyncio from telebot.async_telebot import AsyncTeleBot from telebot.types import Message from aiosend import CryptoPay from aiosend.types import Invoice cp = CryptoPay("TOKEN") bot = AsyncTeleBot("TOKEN") @bot.message_handler() async def get_invoice(message: Message) -> None: invoice = cp.create_invoice(1, "USDT") await bot.send_message( message.from_user.id, f"pay: {invoice.mini_app_invoice_url}", ) invoice.poll(user_id=message.from_user.id) @cp.invoice_paid() async def handle_payment( invoice: Invoice, user_id: int, ) -> None: await bot.send_message( user_id, f"payment received: {invoice.amount} {invoice.asset}", ) async def main() -> None: await asyncio.gather( bot.infinity_polling(), cp.start_polling(), ) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Get Application Balances with aiosend Source: https://context7.com/vovchic17/aiosend/llms.txt Retrieves the current balance for all assets or a specific asset in the application. ```python import asyncio from aiosend import CryptoPay async def main(): cp = CryptoPay(token="YOUR_TOKEN") # Get all balances balances = await cp.get_balance() for balance in balances: print(f"{balance.currency_code}: {balance.available} (on hold: {balance.onhold})") # Get balance for specific asset (convenience method) usdt_balance = await cp.get_balance_by_asset("USDT") print(f"USDT available: {usdt_balance.available}") asyncio.run(main()) ``` -------------------------------- ### Get Application Info with get_me (Python) Source: https://context7.com/vovchic17/aiosend/llms.txt Retrieves basic information about your Crypto Pay application using the `get_me` method. This is useful for verifying API token authentication and obtaining application details. ```python import asyncio from aiosend import CryptoPay async def main(): cp = CryptoPay(token="YOUR_TOKEN") # Get app information app = await cp.get_me() print(f"App ID: {app.app_id}") print(f"App Name: {app.name}") print(f"Payment Processing Bot: {app.payment_processing_bot_username}") asyncio.run(main()) ``` -------------------------------- ### GET /getBalance Source: https://github.com/vovchic17/aiosend/blob/dev/docs/api/index.md Retrieves the current balance of the application. ```APIDOC ## GET /getBalance ### Description Returns the current balance of the application for all supported assets. ### Method GET ### Endpoint /getBalance ### Parameters None ### Response #### Success Response (200) - **balances** (Array) - List of balances per asset. #### Response Example { "ok": true, "result": [ {"currency_code": "USDT", "available": "100.00"}, {"currency_code": "BTC", "available": "0.005"} ] } ``` -------------------------------- ### Basic aiosend Usage - Get App Info Source: https://github.com/vovchic17/aiosend/blob/dev/README.md This snippet demonstrates the basic asynchronous usage of the aiosend library to connect to the Crypto Pay API and retrieve information about the application. It requires an API token and uses asyncio for asynchronous execution. ```python import asyncio from aiosend import CryptoPay async def main(): cp = CryptoPay(token="TOKEN") app = await cp.get_me() print(app.name) # Your App's Name if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### aiosend with aiogram 3.x Integration Source: https://github.com/vovchic17/aiosend/blob/dev/README.md This example shows how to integrate aiosend with the aiogram 3.x framework for handling Telegram messages and payments. It includes creating an invoice, handling payment notifications, and setting up both the aiogram dispatcher and aiosend's polling mechanism. ```python import asyncio from aiogram import Bot, Dispatcher from aiosend import CryptoPay cp = CryptoPay("TOKEN") bot = Bot("TOKEN") dp = Dispatcher() @dp.message() async def get_invoice(message): invoice = await cp.create_invoice(1, "USDT") await message.answer(f"pay: {invoice.bot_invoice_url}") invoice.poll(message=message) @cp.invoice_paid() async def handle_payment(invoice, message): await message.answer(f"invoice #{invoice.invoice_id} has been paid") async def main(): await asyncio.gather( dp.start_polling(bot), cp.start_polling(), ) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### GET /getCurrencies Source: https://github.com/vovchic17/aiosend/blob/dev/docs/api/methods.md Retrieve a list of all supported fiat and cryptocurrency codes. ```APIDOC ## GET /getCurrencies ### Description Use this method to get a list of supported currencies. ### Method GET ### Endpoint /getCurrencies ### Response #### Success Response (200) - **currencies** (list[Currency]) - List of currency codes. ``` -------------------------------- ### GET /getStats Source: https://github.com/vovchic17/aiosend/blob/dev/docs/api/methods.md Retrieve application statistics for a specific time range. ```APIDOC ## GET /getStats ### Description Use this method to get app statistics. ### Method GET ### Endpoint /getStats ### Parameters #### Query Parameters - **start_at** (datetime) - Optional - Start date for statistics. - **end_at** (datetime) - Optional - End date for statistics. ### Response #### Success Response (200) - **stats** (AppStats) - Application statistics object. ``` -------------------------------- ### GET /getExchangeRates Source: https://github.com/vovchic17/aiosend/blob/dev/docs/api/methods.md Retrieve current exchange rates for supported currencies. ```APIDOC ## GET /getExchangeRates ### Description Use this method to get exchange rates of supported currencies. ### Method GET ### Endpoint /getExchangeRates ### Response #### Success Response (200) - **rates** (list[ExchangeRate]) - Array of exchange rate objects. ``` -------------------------------- ### GET /getInvoices Source: https://github.com/vovchic17/aiosend/blob/dev/docs/api/methods.md Retrieves a list of invoices created by your application. ```APIDOC ## GET /getInvoices ### Description Use this method to get invoices created by your app. ### Method GET ### Endpoint /getInvoices ### Parameters #### Query Parameters - **asset** (Asset) - Optional - Cryptocurrency code. - **fiat** (Fiat) - Optional - Fiat currency code. - **invoice_ids** (list[int]) - Optional - List of invoice IDs. - **status** (str) - Optional - Status of invoices (active, paid). - **offset** (int) - Optional - Offset for pagination. - **count** (int) - Optional - Number of invoices to return (1-1000). ### Response #### Success Response (200) - **invoices** (Array) - Array of Invoice objects. ``` -------------------------------- ### Integrate aiosend with aiogram 3.x Source: https://context7.com/vovchic17/aiosend/llms.txt Provides a complete example of integrating aiosend within an aiogram 3.x Telegram bot. It covers creating invoices from messages and handling payment status updates via events. ```python import asyncio from aiogram import Bot, Dispatcher from aiogram.types import Message from aiosend import CryptoPay from aiosend.types import Invoice cp = CryptoPay("CRYPTO_PAY_TOKEN") bot = Bot("TELEGRAM_BOT_TOKEN") dp = Dispatcher() @dp.message() async def create_payment(message: Message) -> None: invoice = await cp.create_invoice( amount=10.0, asset="USDT", description=f"Payment from {message.from_user.first_name}", payload=str(message.from_user.id), ) await message.answer( f"Please pay using this link:\n{invoice.mini_app_invoice_url}" ) invoice.poll(message=message) @cp.invoice_paid() async def handle_payment(invoice: Invoice, message: Message) -> None: await message.answer( f"Thank you! Payment of {invoice.amount} {invoice.asset} received!" ) @cp.invoice_expired() async def handle_expired(invoice: Invoice, message: Message) -> None: await message.answer("Your payment link has expired. Please try again.") async def main(): await asyncio.gather( dp.start_polling(bot), cp.start_polling(), ) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Get Check Image Preview Source: https://github.com/vovchic17/aiosend/blob/dev/docs/client/shortcuts.md The Check.get_image() method retrieves a preview image for a check, optionally converting it to a specified fiat currency. This is useful for visual representation of check details. ```python from aiosend import CryptoPay async def get_check_image(token: str, check_id: int, fiat: str = "USD"): cp = CryptoPay(token) check = await cp.get_check(check_id) image_url = await check.get_image(fiat) return image_url ``` -------------------------------- ### Get Application Statistics Source: https://context7.com/vovchic17/aiosend/llms.txt Retrieves volume and conversion statistics for the application. Supports fetching data for the last 24 hours or a custom date range. ```python import asyncio from datetime import datetime, timedelta from aiosend import CryptoPay async def main(): cp = CryptoPay(token="YOUR_TOKEN") # Get stats for last 24 hours (default) stats = await cp.get_stats() print(f"Volume: {stats.volume}") print(f"Conversion: {stats.conversion}") # Get stats for specific date range end_date = datetime.now() start_date = end_date - timedelta(days=7) weekly_stats = await cp.get_stats( start_at=start_date, end_at=end_date, ) asyncio.run(main()) ``` -------------------------------- ### Get Asset Balance with CryptoPay Source: https://github.com/vovchic17/aiosend/blob/dev/docs/client/tools.md Retrieves the current balance for a specified asset. It returns a Balance object and raises a CryptoPayError if the asset is not found. ```python import asyncio from aiosend import CryptoPay async def main() -> None: cp = CryptoPay(token="TOKEN") print(await cp.get_balance_by_asset("USDT")) # 1.2345 if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Create and Poll Telegram Bot Invoice with aiosend Source: https://github.com/vovchic17/aiosend/blob/dev/docs/integration_examples/pytba.md This Python code snippet demonstrates how to create a cryptocurrency invoice using aiosend's CryptoPay and send it to a Telegram user via a pyTelegramBotAPI bot. It also shows how to set up a listener for payment confirmations and start the bot's polling mechanism. ```python from telebot import TeleBot from telebot.types import Message from aiosend import CryptoPay from aiosend.types import Invoice cp = CryptoPay("TOKEN") bot = TeleBot("TOKEN") @bot.message_handler() def get_invoice(message: Message) -> None: invoice = cp.create_invoice(1, "USDT") bot.send_message( message.from_user.id, f"pay: {invoice.mini_app_invoice_url}", ) invoice.poll(user_id=message.from_user.id) @cp.invoice_paid() def handle_payment( invoice: Invoice, user_id: int, ) -> None: bot.send_message( user_id, f"payment received: {invoice.amount} {invoice.asset}", ) if __name__ == "__main__": cp.start_polling(bot.infinity_polling) ``` -------------------------------- ### Update Objects (Balance, Check, ExchangeRate, Invoice) Source: https://github.com/vovchic17/aiosend/blob/dev/docs/client/shortcuts.md These methods provide shortcuts for updating specific objects by calling their respective get methods from the CryptoPay class. They simplify the process of refreshing data for balances, checks, exchange rates, and invoices. The return type is None. ```python from aiosend import CryptoPay # Example for updating balance (similar for Check, ExchangeRate, Invoice) async def update_balance(token: str): cp = CryptoPay(token) await cp.get_balance().update() ``` -------------------------------- ### Get QR Code for Check and Invoice Source: https://github.com/vovchic17/aiosend/blob/dev/docs/client/shortcuts.md Access the 'qr' property of Check and Invoice objects to retrieve their respective QR code links. This allows for easy display and sharing of payment or check details. ```python from aiosend import CryptoPay async def get_qr_code(token: str, invoice_id: int): cp = CryptoPay(token) invoice = await cp.get_invoice(invoice_id) return invoice.qr ``` -------------------------------- ### Initialize CryptoPay Client with Network Source: https://github.com/vovchic17/aiosend/blob/dev/docs/api/network.md Demonstrates how to instantiate the CryptoPay client using either the MAINNET or TESTNET network configurations. The MAINNET is used by default if no network is specified. ```python from aiosend import MAINNET, TESTNET, CryptoPay main_client = CryptoPay( "TOKEN", MAINNET, ) test_client = CryptoPay( "TOKEN", TESTNET, ) ``` -------------------------------- ### GET /getTransfers Source: https://github.com/vovchic17/aiosend/blob/dev/docs/api/methods.md Retrieve a list of transfers created by your application. ```APIDOC ## GET /getTransfers ### Description Use this method to get transfers created by your app. ### Method GET ### Endpoint /getTransfers ### Parameters #### Query Parameters - **asset** (string) - Optional - Cryptocurrency code. - **transfer_ids** (list[int]) - Optional - Comma-separated list of transfer IDs. - **spend_id** (string) - Optional - Unique UTF-8 transfer string. - **offset** (int) - Optional - Pagination offset. - **count** (int) - Optional - Number of transfers to return (1-1000). ### Response #### Success Response (200) - **transfers** (list[Transfer]) - Array of transfer objects. ``` -------------------------------- ### Create Payment Invoice with create_invoice (Python) Source: https://context7.com/vovchic17/aiosend/llms.txt Demonstrates how to create payment invoices using the `create_invoice` method. Supports both cryptocurrency and fiat currencies, with options for descriptions, custom buttons, payloads, and expiration. ```python import asyncio from aiosend import CryptoPay from aiosend.enums import Asset, Fiat, CurrencyType, PaidBtnName async def main(): cp = CryptoPay(token="YOUR_TOKEN") # Simple crypto invoice invoice = await cp.create_invoice( amount=10.0, asset=Asset.USDT, ) print(f"Pay URL: {invoice.bot_invoice_url}") print(f"Mini App URL: {invoice.mini_app_invoice_url}") print(f"Invoice ID: {invoice.invoice_id}") # Detailed invoice with all options detailed_invoice = await cp.create_invoice( amount=25.0, asset=Asset.TON, description="Premium subscription - 1 month", hidden_message="Thank you for your purchase! Your subscription is now active.", paid_btn_name=PaidBtnName.OPEN_BOT, paid_btn_url="https://t.me/YourBot", payload="user_123_subscription_premium", allow_comments=True, allow_anonymous=False, expires_in=3600, # 1 hour expiration ) # Fiat invoice (price in USD, pay with crypto) fiat_invoice = await cp.create_invoice( amount=50.0, currency_type=CurrencyType.FIAT, fiat=Fiat.USD, accepted_assets=[Asset.USDT, Asset.TON, Asset.BTC], description="Product purchase - $50", ) # Invoice with auto-swap to specific asset swap_invoice = await cp.create_invoice( amount=100.0, asset=Asset.USDT, swap_to=Asset.TON, # Swap payment to TON after receipt description="Payment with auto-swap to TON", ) asyncio.run(main()) ``` -------------------------------- ### GET /getChecks Source: https://github.com/vovchic17/aiosend/blob/dev/docs/api/methods.md Retrieve a list of checks created by your application. ```APIDOC ## GET /getChecks ### Description Use this method to get checks created by your app. ### Method GET ### Endpoint /getChecks ### Parameters #### Query Parameters - **asset** (string) - Optional - Cryptocurrency code (e.g., USDT, TON). - **check_ids** (list[int]) - Optional - Comma-separated list of check IDs. - **status** (string) - Optional - Status of check (active, activated). - **offset** (int) - Optional - Offset for pagination, defaults to 0. - **count** (int) - Optional - Number of checks to return (1-1000), defaults to 100. ### Response #### Success Response (200) - **checks** (list[Check]) - Array of check objects. ``` -------------------------------- ### GET /getInvoices Source: https://context7.com/vovchic17/aiosend/llms.txt Retrieves a list of invoices created by the application with optional filtering and pagination. ```APIDOC ## GET /getInvoices ### Description Retrieves a list of invoices created by your application with optional filtering by status, asset, or ID. ### Method GET ### Endpoint /getInvoices ### Parameters #### Query Parameters - **asset** (string) - Optional - Filter by cryptocurrency asset - **status** (string) - Optional - Filter by invoice status (e.g., PAID, ACTIVE) - **invoice_ids** (list) - Optional - List of specific invoice IDs to retrieve - **offset** (integer) - Optional - Pagination offset - **count** (integer) - Optional - Number of records to return ### Response #### Success Response (200) - **invoices** (array) - List of invoice objects #### Response Example { "invoices": [ { "invoice_id": 123, "amount": 10.0, "asset": "USDT", "status": "PAID" } ] } ``` -------------------------------- ### Configure Webhook Integration with aiohttp Source: https://context7.com/vovchic17/aiosend/llms.txt Demonstrates how to set up a webhook manager using the aiohttp web framework to receive real-time payment notifications. It initializes the CryptoPay client with an AiohttpManager and defines an invoice_paid event handler. ```python import asyncio from aiohttp.web import Application, run_app from aiosend import CryptoPay from aiosend.types import Invoice from aiosend.webhook import AiohttpManager app = Application() cp = CryptoPay( token="YOUR_TOKEN", webhook_manager=AiohttpManager(app, "/webhook"), ) @cp.invoice_paid() async def handle_payment(invoice: Invoice) -> None: print(f"Payment received: {invoice.amount} {invoice.asset}") async def main(): invoice = await cp.create_invoice(1.0, "USDT") print(f"Invoice: {invoice.bot_invoice_url}") await run_app(app, port=8080) asyncio.run(main()) ``` -------------------------------- ### Implementing Class-Based Filters Source: https://github.com/vovchic17/aiosend/blob/dev/docs/events/filters.md Shows how to create filters using classes that implement the __call__ method, supporting both sync and async execution. ```python class MySyncFilter: def __init__(self, payload: str): self.payload = payload def __call__(self, invoice: Invoice) -> bool: return invoice.payload == self.payload class MyASyncFilter: def __init__(self, payload: str): self.payload = payload async def __call__(self, invoice: Invoice) -> bool: return invoice.payload == self.payload @cp.invoice_paid(MySyncFilter("product1")) async def handler1(invoice: Invoice) -> None: print(f"paid {invoice.amount} {invoice.asset} for product1") @cp.invoice_paid(MyASyncFilter("product2")) async def handler2(invoice: Invoice) -> None: print(f"paid {invoice.amount} {invoice.asset} for product2") ``` -------------------------------- ### Python: Initialize CryptoPay with Incorrect Network Source: https://github.com/vovchic17/aiosend/blob/dev/docs/client/hints_warns.md Demonstrates initializing the CryptoPay client with a token for one network (MAINNET) while specifying another (TESTNET). This will trigger a WrongNetworkError, indicating a mismatch between the token's network and the client's configured network. ```python from aiosend import CryptoPay, TESTNET cp = CryptoPay("MAINNET token", TESTNET) ``` ```bash aiosend.exceptions.WrongNetworkError: Authorization failed. Token is served by the MAINNET, you are using TESTNET ``` -------------------------------- ### GET /getInvoices Source: https://github.com/vovchic17/aiosend/blob/dev/docs/events/invoice_polling.md Retrieves invoice data to check for status updates. This method is utilized internally by the PollingManager to track when an invoice transitions to a PAID state. ```APIDOC ## GET /getInvoices ### Description Retrieves a list of invoices to monitor their status. The polling manager uses this to trigger 'invoice_paid' or 'invoice_expired' handlers based on the current status. ### Method GET ### Endpoint /getInvoices ### Parameters #### Query Parameters - **asset** (string) - Optional - Filter invoices by asset (e.g., USDT, BTC). - **invoice_ids** (list) - Optional - List of specific invoice IDs to retrieve. - **status** (string) - Optional - Filter by invoice status (e.g., PAID, ACTIVE). ### Request Example GET /getInvoices?status=ACTIVE ### Response #### Success Response (200) - **result** (array) - List of invoice objects containing status, amount, and asset information. #### Response Example { "ok": true, "result": [ { "invoice_id": 12345, "status": "ACTIVE", "amount": "1.0", "asset": "USDT" } ] } ``` -------------------------------- ### Initialize and Use PollingRouter Source: https://github.com/vovchic17/aiosend/blob/dev/docs/events/routers.md Demonstrates how to initialize a PollingRouter and register an event handler for the 'invoice_paid' event using a decorator. This is a common pattern for handling specific events in aiosend. ```python from aiosend import PollingRouter from aiosend.types import Invoice router = PollingRouter(name=__name__) @router.invoice_paid() def invoice_paid(invoice: Invoice) -> None: print(f"invoice_paid: {invoice.invoice_id}") ``` -------------------------------- ### Webhook Integration with FastAPI Source: https://context7.com/vovchic17/aiosend/llms.txt Demonstrates how to handle payment notifications via webhooks using the FastAPI framework, providing an alternative to polling. ```python import asyncio import uvicorn from fastapi import FastAPI from aiosend import CryptoPay from aiosend.types import Invoice from aiosend.webhook import FastAPIManager app = FastAPI() # Initialize with webhook manager cp = CryptoPay( token="YOUR_TOKEN", webhook_manager=FastAPIManager(app, "/crypto-pay-webhook"), ) @cp.invoice_paid() async def handle_payment(invoice: Invoice) -> None: print(f"Webhook: Invoice #{invoice.invoice_id} paid") print(f"Amount: {invoice.amount} {invoice.asset}") print(f"Payload: {invoice.payload}") async def create_invoice(): invoice = await cp.create_invoice( amount=10.0, asset="USDT", payload="order_12345", ) return invoice if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=8000) ``` -------------------------------- ### Implementing Function Filters Source: https://github.com/vovchic17/aiosend/blob/dev/docs/events/filters.md Demonstrates using standard synchronous and asynchronous functions, as well as lambdas, as filters for handlers. ```python def filter1(invoice: Invoice) -> bool: return invoice.payload == "product1" async def filter2(invoice: Invoice) -> bool: return invoice.payload == "product2" @cp.invoice_paid(filter1) async def handler1(invoice: Invoice) -> None: print(f"paid {invoice.amount} {invoice.asset} for product1") @cp.invoice_paid(filter2, lambda inv: inv.amount == 1) async def handler2(invoice: Invoice) -> None: print(f"paid {invoice.amount} {invoice.asset} for product2") ``` -------------------------------- ### Retrieve Exchange Rates and Convert Currencies Source: https://context7.com/vovchic17/aiosend/llms.txt Fetches current exchange rates between supported currencies and performs currency conversion calculations. Requires an initialized CryptoPay instance. ```python import asyncio from aiosend import CryptoPay async def main(): cp = CryptoPay(token="YOUR_TOKEN") # Get all exchange rates rates = await cp.get_exchange_rates() for rate in rates: print(f"{rate.source} -> {rate.target}: {rate.rate}") # Use exchange helper method for conversion usd_amount = await cp.exchange(10, "USDT", "USD") print(f"10 USDT = {usd_amount} USD") btc_in_usd = await cp.exchange(0.001, "BTC", "USD") print(f"0.001 BTC = {btc_in_usd} USD") asyncio.run(main()) ``` -------------------------------- ### Define and Use Custom PayloadData Class in Python Source: https://github.com/vovchic17/aiosend/blob/dev/docs/events/payload_data.md Demonstrates how to create a subclass of aiosend.PayloadData with a required prefix and an optional separator. It shows how to instantiate the class, pack its data into a string, and use it when creating an invoice. ```python from aiosend import PayloadData class MyData(PayloadData, prefix="md"): foo: str bar: int # Example usage: my_data = MyData(foo="foo", bar=123).pack() # await cp.create_invoice(1, "USDT", payload=my_data) ``` -------------------------------- ### Create Invoice with CryptoPay.create_invoice() Source: https://github.com/vovchic17/aiosend/blob/dev/docs/api/methods.md The createInvoice method allows for the creation of new invoices. It supports various parameters to specify the amount, currency, assets, descriptions, payment buttons, and expiration times. On success, it returns an Invoice object. ```python from aiosend import CryptoPay, Asset, CurrencyType, Fiat, PaidBtnName async def create_new_invoice( api_token: str, amount: float, asset: Asset = None, currency_type: CurrencyType = CurrencyType.CRYPTO, fiat: Fiat = None, accepted_assets: list[Asset] = None, swap_to: Asset = None, description: str = None, hidden_message: str = None, paid_btn_name: PaidBtnName = None, paid_btn_url: str = None, payload: str = None, allow_comments: bool = True, allow_anonymous: bool = True, expires_in: int = None ): bot = CryptoPay(api_token) invoice = await bot.create_invoice( amount=amount, asset=asset, currency_type=currency_type, fiat=fiat, accepted_assets=accepted_assets, swap_to=swap_to, description=description, hidden_message=hidden_message, paid_btn_name=paid_btn_name, paid_btn_url=paid_btn_url, payload=payload, allow_comments=allow_comments, allow_anonymous=allow_anonymous, expires_in=expires_in ) return invoice ``` -------------------------------- ### AiohttpSession Class Source: https://github.com/vovchic17/aiosend/blob/dev/docs/client/session.md The default HTTP session implementation in aiosend, which is a wrapper around aiohttp.ClientSession. ```APIDOC ## class aiosend.client.session.AiohttpSession ### Description Http session based on aiohttp. This class is a wrapper of aiohttp.ClientSession. ### Method `request(token, client, method)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "token": "string", "client": "object", "method": "string" } ``` ### Response #### Success Response (200) - **Type** (`TypeVar`(`_CryptoPayType`, bound= CryptoPayObject | list | bool)) - The result of the HTTP request. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Test Authentication with CryptoPay.get_me() Source: https://github.com/vovchic17/aiosend/blob/dev/docs/api/methods.md The getMe method is used to test your application's authentication token with the Crypto Pay API. It requires no parameters and returns basic information about the app upon successful authentication. ```python from aiosend import CryptoPay async def test_auth(api_token): bot = CryptoPay(api_token) app_info = await bot.get_me() print(app_info) ``` -------------------------------- ### POST /create_invoice Source: https://github.com/vovchic17/aiosend/blob/dev/docs/integration_examples/pyrogram.md Creates a new invoice for a specified amount and asset, returning an invoice object with payment details. ```APIDOC ## POST /create_invoice ### Description Creates a new invoice for a specified amount and asset. The returned object contains the mini_app_invoice_url for user payment. ### Method POST ### Endpoint /create_invoice ### Parameters #### Request Body - **amount** (float) - Required - The amount of the asset to be paid. - **asset** (string) - Required - The currency asset (e.g., "USDT", "BTC"). ### Request Example { "amount": 1, "asset": "USDT" } ### Response #### Success Response (200) - **invoice_id** (integer) - Unique identifier for the invoice. - **mini_app_invoice_url** (string) - URL for the user to complete the payment. #### Response Example { "invoice_id": 12345, "mini_app_invoice_url": "https://t.me/CryptoBot?start=pay-12345" } ```