### Webhook Setup with FastAPI Source: https://aiosend.readthedocs.io/en/latest/events/webhook Example demonstrating how to set up and use webhooks with FastAPI. ```APIDOC ## Webhook Setup with FastAPI ### Description This example illustrates the integration of aiosend webhooks with a FastAPI application. It requires installing the `aiosend[fastapi]` extra package and configuring the FastAPIManager. ### Method N/A (This is a usage example, not a direct API endpoint) ### Endpoint N/A (This is a usage example) ### Parameters N/A ### Request Example ```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) ``` ### Response N/A (This is a usage example) ``` -------------------------------- ### Webhook Setup with Flask Source: https://aiosend.readthedocs.io/en/latest/events/webhook Example demonstrating how to set up and use webhooks with Flask. ```APIDOC ## Webhook Setup with Flask ### Description This example provides a guide for using aiosend webhooks with a Flask application. It requires the `aiosend[flask]` extra package and the configuration of the FlaskManager. ### Method N/A (This is a usage example, not a direct API endpoint) ### Endpoint N/A (This is a usage example) ### Parameters N/A ### Request Example ```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() ``` ### Response N/A (This is a usage example) ``` -------------------------------- ### Webhook Setup with Aiohttp Source: https://aiosend.readthedocs.io/en/latest/events/webhook Example demonstrating how to set up and use webhooks with aiohttp web server. ```APIDOC ## Webhook Setup with Aiohttp ### Description This example shows how to integrate aiosend's webhook functionality with an aiohttp web server. It includes creating a CryptoPay instance with an AiohttpManager and defining a handler for invoice paid events. ### Method N/A (This is a usage example, not a direct API endpoint) ### Endpoint N/A (This is a usage example) ### Parameters N/A ### Request Example ```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()) ``` ### Response N/A (This is a usage example) ``` -------------------------------- ### Quick Start: Initialize CryptoPay Client and Get App Info (Python) Source: https://aiosend.readthedocs.io/en/latest/index This snippet demonstrates how to initialize the aiosend CryptoPay client with an API token and retrieve application information asynchronously. It requires the 'asyncio' and 'aiosend' libraries. ```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()) ``` -------------------------------- ### FastAPI Webhook Integration with aiosend Source: https://aiosend.readthedocs.io/en/latest/events/webhook Example showing aiosend webhook integration with a FastAPI web server. It requires installing the 'fastapi' extra package for aiosend. The example initializes CryptoPay with FastAPIManager and sets up an invoice payment handler. ```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) ``` -------------------------------- ### GET /getMe Source: https://aiosend.readthedocs.io/en/latest/api/methods Tests your app's authentication token and returns basic information about the app. Requires no parameters. ```APIDOC ## GET /getMe ### Description Tests your app's authentication token and returns basic information about the app. Requires no parameters. ### Method GET ### Endpoint /getMe ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **App** (object) - Basic information about the app. #### Response Example { "result": { "id": 12345, "name": "My App", "payment_provider_bot_username": "CryptoPayBot" } } ``` -------------------------------- ### Async pyTelegramBotAPI Usage Example with aiosend Source: https://aiosend.readthedocs.io/en/latest/integration_examples/pytba_async This example demonstrates how to integrate aiosend's CryptoPay functionality with an asynchronous pyTelegramBotAPI bot. It shows how to create an invoice using aiosend and send it to a user via Telegram, and how to handle payment notifications. Dependencies include 'telebot' and 'aiosend'. ```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()) ``` -------------------------------- ### aiogram 3.x Usage Example with aiosend Source: https://aiosend.readthedocs.io/en/latest/integration_examples/aiogram3 This Python code demonstrates how to integrate aiosend with aiogram 3.x to create cryptocurrency invoices and handle payment confirmations. It requires the aiogram and aiosend libraries. The example includes setting up the CryptoPay and Bot instances, defining message handlers for invoice creation, and an event handler for paid invoices. ```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()) ``` -------------------------------- ### Python Invoice Polling Example using aiosend Source: https://aiosend.readthedocs.io/en/latest/events/invoice_polling This Python code demonstrates how to set up invoice polling using the aiosend library. It includes creating an invoice, defining handlers for when an invoice is paid or expires, and starting the polling service. This snippet requires the 'aiosend' library and 'asyncio'. ```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()) ``` -------------------------------- ### aiohttp Webhook Integration with aiosend Source: https://aiosend.readthedocs.io/en/latest/events/webhook Example demonstrating how to use aiosend webhooks with an aiohttp web server. This involves initializing CryptoPay with AiohttpManager and defining a handler for invoice payment events. It requires the aiohttp library. ```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()) ``` -------------------------------- ### aiogram 2.x Usage Example with aiosend Source: https://aiosend.readthedocs.io/en/latest/integration_examples/aiogram2 This example demonstrates how to use aiosend with aiogram 2.x to create cryptocurrency invoices and handle payment notifications. It requires the aiogram and aiosend libraries. The function creates an invoice, sends a payment link to the user, and sets up handlers for payment confirmations. ```python import asyncio from aiogram import Bot, Dispatcher, executor from aiogram.types import Message from aiosend import CryptoPay from aiosend.types import Invoice cp = CryptoPay("TOKEN") bot = Bot("TOKEN") dp = Dispatcher(bot) @dp.message_handler() 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 on_startup(_) -> None: asyncio.create_task(cp.start_polling()) if __name__ == "__main__": executor.start_polling(dp, on_startup=on_startup) ``` -------------------------------- ### Pyrogram: Create and Handle CryptoPay Invoices Source: https://aiosend.readthedocs.io/en/latest/integration_examples/pyrogram This Python code snippet shows how to initialize Pyrogram and CryptoPay clients, create a payment invoice, and handle payment notifications. It requires Pyrogram and aiosend libraries and uses a CryptoPay API token. ```python from pyrogram import Client, filters from pyrogram.types import Message from aiosend import CryptoPay from aiosend.types import Invoice app = Client("my_account") cp = CryptoPay("TOKEN") @app.on_message(filters.private) async def get_invoice(client: Client, message: Message) -> None: invoice = await cp.create_invoice(1, "USDT") await message.reply_text( 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.reply_text( f"payment received: {invoice.amount} {invoice.asset}", ) cp.start_polling(app.start) ``` -------------------------------- ### Create Invoice and Handle Payment with Telethon and aiosend Source: https://aiosend.readthedocs.io/en/latest/integration_examples/telethon This example shows how to use Telethon to listen for new private messages and aiosend's CryptoPay to create a payment invoice. It also includes a callback to handle successful payments. Dependencies include 'telethon' and 'aiosend'. It takes an API ID, API Hash, and a CryptoPay token as input. The output includes sending an invoice URL to the user and a confirmation message upon payment. ```python from telethon import TelegramClient, events from telethon.events.newmessage import NewMessage from aiosend import CryptoPay from aiosend.types import Invoice api_id = 12345678 api_hash = "API HASH" cp = CryptoPay("TOKEN") client = TelegramClient("anon", api_id, api_hash) @client.on(events.NewMessage(func=lambda e: e.is_private)) async def get_invoice(message: NewMessage.Event) -> None: invoice = await cp.create_invoice(1, "USDT") await client.send_message( message.chat_id, f"pay: {invoice.mini_app_invoice_url}", ) invoice.poll(chat_id=message.chat_id) @cp.invoice_paid() async def handle_payment( invoice: Invoice, chat_id: int, ) -> None: await client.send_message( chat_id, f"payment received: {invoice.amount} {invoice.asset}", ) client.start() cp.start_polling() ``` -------------------------------- ### Create CryptoPay Invoice with python-telegram-bot Source: https://aiosend.readthedocs.io/en/latest/integration_examples/ptb This example demonstrates how to create a cryptocurrency invoice using aiosend's CryptoPay and integrate it with a python-telegram-bot application. It includes functions to create an invoice, send it to a user, and handle payment notifications. Dependencies include `aiosend` and `python-telegram-bot`. ```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()) ``` -------------------------------- ### Flask Webhook Integration with aiosend Source: https://aiosend.readthedocs.io/en/latest/events/webhook Demonstrates integrating aiosend webhooks with a Flask web server. Users need to install the 'flask' extra package. The code initializes CryptoPay using FlaskManager and defines a callback for invoice payment events. ```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() ``` -------------------------------- ### Python Example: Polling for Check Status Updates with aiosend Source: https://aiosend.readthedocs.io/en/latest/events/check_polling This Python code demonstrates how to set up and use the aiosend library for polling check status updates. It includes defining handlers for activated and expired checks, creating a new check, initiating polling for that check, and starting the polling manager. The code relies on the asyncio library for asynchronous operations and the aiosend library for its core functionalities. ```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()) ``` -------------------------------- ### Dependency Injection Example with aiosend CryptoPay Source: https://aiosend.readthedocs.io/en/latest/client/di This Python code demonstrates dependency injection using the aiosend library's CryptoPay client. It shows how to inject configuration parameters ('var1', 'var2', 'var3') into the client and its methods, making them available in asynchronous callback functions. This pattern enhances flexibility by decoupling object creation from their usage. ```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()) ``` -------------------------------- ### Create Telegram Payment Invoice with aiosend and pyTelegramBotAPI Source: https://aiosend.readthedocs.io/en/latest/integration_examples/pytba This example demonstrates how to create a cryptocurrency payment invoice using aiosend and send it to a Telegram user via pyTelegramBotAPI. It includes handling invoice creation, sending the invoice URL, and a callback for payment confirmation. Requires 'aiosend' and 'pyTelegramBotAPI' libraries. ```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) ``` -------------------------------- ### Configure Polling with aiosend CryptoPay Source: https://aiosend.readthedocs.io/en/latest/events/polling_config This Python code demonstrates how to initialize aiosend's CryptoPay with custom polling configurations. It includes setting up handlers for invoice payments and expirations, creating an invoice, and starting the polling mechanism to listen for payment events. ```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) # called after timeout (600s) or when invoice status is "expired" @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()) ``` -------------------------------- ### Invoice Paid Handler with Class Filters (Sync and Async) Source: https://aiosend.readthedocs.io/en/latest/events/filters This example demonstrates using classes with __call__ methods as filters for invoice payment events. 'MySyncFilter' uses a synchronous __call__ method, while 'MyASyncFilter' uses an asynchronous one. 'handler1' is triggered using an instance of 'MySyncFilter' for 'product1', and 'handler2' uses 'MyASyncFilter' for 'product2'. ```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") ``` -------------------------------- ### CryptoPay.get_stats() Source: https://aiosend.readthedocs.io/en/latest/api/methods Retrieves application statistics within a specified date range. Optional start and end dates can be provided. ```APIDOC ## GET /getStats ### Description Use this method to get app statistics. On success, returns `aiosend.types.AppStats`. ### Method GET ### Endpoint /getStats ### Parameters #### Query Parameters - **start_at** (datetime) - Optional. Date from which to start calculating statistics. Defaults to current date minus 24 hours. - **end_at** (datetime) - Optional. The date on which to finish calculating statistics. Defaults to current date. #### Request Body None ### Response #### Success Response (200) - **stats** (AppStats) - An object containing application statistics. #### Response Example ```json { "stats": { "revenue": { "currency": "USD", "total": 1000.00, "count": 10 }, "start_at": "2023-10-26T10:00:00Z", "end_at": "2023-10-27T10:00:00Z" } } ``` ``` -------------------------------- ### Create and Poll Invoices using aiosend Source: https://aiosend.readthedocs.io/en/latest/events/filters This code snippet demonstrates how to create multiple invoices using the CryptoPay client and then poll them. It initializes the CryptoPay client with a token, creates two invoices with different payloads, prints their bot invoice URLs, and starts polling for updates. It requires the 'asyncio' and 'aiosend' libraries. ```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()) ``` -------------------------------- ### aiosend Wrong Network Error Example Source: https://aiosend.readthedocs.io/en/latest/client/hints_warns Illustrates the aiosend.exceptions.WrongNetworkError that occurs when a token is associated with the mainnet but the client is initialized with TESTNET. ```python aiosend.exceptions.WrongNetworkError: Authorization failed. Token is served by the MAINNET, you are using TESTNET ``` -------------------------------- ### Invoice Paid Handler with Magic Filter Source: https://aiosend.readthedocs.io/en/latest/events/filters This example shows how to use MagicFilter from the 'magic_filter' library (or 'aiogram') to filter invoice payment events based on the payload. It defines two handlers, 'handler1' and 'handler2', each decorated with '@cp.invoice_paid'. 'handler1' is triggered when the payload is 'product1', and 'handler2' when it's 'product2'. This requires the 'magic_filter' library. ```python from magic_filter import F # or from aiogram import F @cp.invoice_paid(F.payload == "product1") async def handler1(invoice: Invoice) -> None: print(f"paid {invoice.amount} {invoice.asset} for product1") @cp.invoice_paid(F.payload == "product2") async def handler2(invoice: Invoice) -> None: print(f"paid {invoice.amount} {invoice.asset} for product2") ``` -------------------------------- ### Initialize CryptoPay with Testnet - aiosend Source: https://aiosend.readthedocs.io/en/latest/client/hints_warns Demonstrates initializing the CryptoPay client with a mainnet token but specifying the testnet environment. This can lead to a WrongNetworkError if the token is indeed for the mainnet. ```python from aiosend import CryptoPay, TESTNET cp = CryptoPay("MAINNET token", TESTNET) ``` -------------------------------- ### Instantiate CryptoPay Client with Mainnet and Testnet Source: https://aiosend.readthedocs.io/en/latest/api/network Demonstrates how to create instances of the CryptoPay client using the MAINNET and TESTNET configurations provided by aiosend. These networks are used for real cryptocurrency transactions and testing purposes, respectively. The MAINNET is the default network. ```python from aiosend import MAINNET, TESTNET, CryptoPay main_client = CryptoPay( "TOKEN", MAINNET, # MAINNET is default ) test_client = CryptoPay( "TOKEN", TESTNET, ) ``` -------------------------------- ### Shortcut Methods Source: https://aiosend.readthedocs.io/en/latest/client/index Offers shortcut methods for common operations on various objects like Balance, Check, ExchangeRate, and Invoice. ```APIDOC ## Shortcut Methods API ### Description This section outlines shortcut methods for managing objects within the AIOSend library. ### Updating Objects - `Balance.update()` - `Check.update()` - `ExchangeRate.update()` - `Invoice.update()` ### Deleting Objects - `Check.delete()` - `Invoice.delete()` ### Object QR Code - `Check.qr` - `Invoice.qr` ### Check Image - `Check.get_image()` ### Poll Objects - `Check.poll()` - `Invoice.poll()` ``` -------------------------------- ### Get CryptoPay Balance by Asset Source: https://aiosend.readthedocs.io/en/latest/client/tools Retrieves the balance for a specific asset using CryptoPay. This function wraps CryptoPay.get_balance() and returns a Balance object. It raises CryptoPayError if the specified 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()) ``` -------------------------------- ### Get Specific CryptoPay Check Source: https://aiosend.readthedocs.io/en/latest/client/tools Retrieves a single check or returns None if not found. This method is a wrapper for CryptoPay.get_checks() and can be used to update the status of an existing check or retrieve it by its ID. It returns a Check object or None. ```python # No usage example provided in the source text. ``` -------------------------------- ### Get Specific CryptoPay Invoice Source: https://aiosend.readthedocs.io/en/latest/client/tools Fetches a single invoice or returns None if not found. This method is a wrapper for CryptoPay.get_invoices() and can be used to update the status of an existing invoice or retrieve it by its ID. It returns an Invoice object or None. ```python import asyncio from aiosend import CryptoPay async def main() -> None: cp = CryptoPay(token="TOKEN") invoice = await cp.create_invoice(1, "TON") print(invoice.status) # active await asyncio.sleep(10) # payment new_invoice = await cp.get_invoice(invoice) print(new_invoice.status) # paid if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Updating Objects Source: https://aiosend.readthedocs.io/en/latest/client/shortcuts These methods are shortcuts for updating object information by fetching the latest data from the Crypto Pay API. ```APIDOC ## Updating Objects ### Balance.update() * **Description**: Shortcut for method `aiosend.CryptoPay.get_balance()`. Use this method to update the balance object. * **Source**: https://help.crypt.bot/crypto-pay-api#getBalance * **Method**: (Implied as internal method call within aiosend) * **Return Type**: `None` ### Check.update() * **Description**: Shortcut for method `aiosend.CryptoPay.get_checks()`. Use this method to update the check object. * **Source**: https://help.crypt.bot/crypto-pay-api#getChecks * **Method**: (Implied as internal method call within aiosend) * **Return Type**: `None` ### ExchangeRate.update() * **Description**: Shortcut for method `aiosend.CryptoPay.get_exchange_rates()`. Use this method to update the ExchangeRate object. * **Source**: https://help.crypt.crypt.bot/crypto-pay-api#getExchangeRates * **Method**: (Implied as internal method call within aiosend) * **Return Type**: `None` ### Invoice.update() * **Description**: Shortcut for method `aiosend.CryptoPay.get_invoices()`. Use this method to update the invoice object. * **Source**: https://help.crypt.bot/crypto-pay-api#getInvoices * **Method**: (Implied as internal method call within aiosend) * **Return Type**: `None` ``` -------------------------------- ### Custom WebhookManager Implementation Source: https://aiosend.readthedocs.io/en/latest/events/webhook Instructions and details on how to implement a custom webhook manager by inheriting from WebhookManager. ```APIDOC ## Custom WebhookManager Implementation ### Description This section details how to create and use your own webhook manager in aiosend. You can achieve this by inheriting from the `aiosend.webhook.WebhookManager` class and overriding the `register_handler` method. ### Method N/A (This is a conceptual guide, not a direct API endpoint) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ## Class: `WebhookManager` ### Description Base class for webhook managers. Provides the foundation for creating custom webhook integrations. ### Method `register_handler(self, feed_update)` #### Description Abstract method to be implemented by subclasses. This method is responsible for registering the webhook handler within the specific web server framework. #### Parameters * `handler` (object) - The web server handler object. #### Return Type `None` ## Class: `AiohttpManager` ### Description Webhook manager specifically designed for `aiohttp.web.Application`. ### Method `register_handler(self, feed_update)` #### Description Registers the webhook handler for an aiohttp application. #### Return Type `None` ## Class: `FastAPIManager` ### Description Webhook manager tailored for `fastapi.FastAPI` or `fastapi.APIRouter`. ### Method `register_handler(self, feed_update)` #### Description Registers the webhook handler for a FastAPI application or router. #### Return Type `None` ## Class: `FlaskManager` ### Description Webhook manager designed for `flask.Flask` applications. ### Method `register_handler(self, feed_update)` #### Description Registers the webhook handler for a Flask application. #### Return Type `None` ``` -------------------------------- ### AiohttpSession Class Source: https://aiosend.readthedocs.io/en/latest/client/session The default HTTP session implementation in aiosend, based on aiohttp.ClientSession. ```APIDOC ## AiohttpSession Class ### Description Http session based on aiohttp. This class is a wrapper of aiohttp.ClientSession. ### Class `aiosend.client.session.AiohttpSession` ### Parameters - **network**: (object) - Represents the network configuration. - **timeout** (int) - Optional - Timeout in seconds for requests. Defaults to 300. ### Methods #### `request(token, client, method)` ##### Description Make http request. ##### Method `async` ##### Parameters - **token**: (any) - Authentication token or credentials. - **client**: (any) - The client object making the request. - **method**: (any) - The HTTP method and details of the request. ##### Return Type `TypeVar`(`_CryptoPayType`, bound= CryptoPayObject | list | bool) ``` -------------------------------- ### Check Image Source: https://aiosend.readthedocs.io/en/latest/client/shortcuts Retrieve a preview image for a check. ```APIDOC ## Check Image ### Check.get_image(_fiat_) * **Description**: Get a preview image for a check. * **Parameters**: * `fiat` (str) - The fiat currency to use for the image conversion. * **Return Type**: `str` ``` -------------------------------- ### Tools Source: https://aiosend.readthedocs.io/en/latest/client/index Provides access to various tools for interacting with the Crypto Pay API, such as retrieving balances, invoices, and rates. ```APIDOC ## Tools API ### Description This section details the available tools for interacting with the Crypto Pay API. ### Methods - `CryptoPay.exchange()` - `CryptoPay.get_balance_by_asset()` - `CryptoPay.get_invoice()` - `CryptoPay.get_check()` - `CryptoPay.delete_all_checks()` - `CryptoPay.delete_all_invoices()` - `CryptoPay.get_rates_image()` ``` -------------------------------- ### Object QR Code Source: https://aiosend.readthedocs.io/en/latest/client/shortcuts Retrieve the QR code for check and invoice objects. ```APIDOC ## QR Code of Object ### _property _Check.qr _: str_ * **Description**: Get the QR code for a check. ### _property _Invoice.qr _: str_ * **Description**: Get the QR code for an invoice. ``` -------------------------------- ### Return Context Data from Filter as Handler Argument Source: https://aiosend.readthedocs.io/en/latest/events/filters This example demonstrates how a filter function can return a dictionary to provide context data to the handler. The 'myfilter' function checks if the invoice payload is None; if so, it returns False. Otherwise, it returns a dictionary {'payload': invoice.payload}. This dictionary's contents are then passed as arguments to 'handler1', specifically the 'payload' argument. ```python def myfilter(invoice: Invoice) -> bool | dict[str, object]: if invoice.payload is None: return False return {"payload": invoice.payload} @cp.invoice_paid(myfilter) async def handler1(invoice: Invoice, payload: str) -> None: print(f"paid #{invoice.invoice_id} paylaod: {payload}") ``` -------------------------------- ### Create and Use a PollingRouter Source: https://aiosend.readthedocs.io/en/latest/events/routers Demonstrates how to create an instance of PollingRouter and attach an event handler for the 'invoice_paid' event using a decorator. This router is part of the aiosend library for handling polling events. ```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}") ``` -------------------------------- ### Pack and Create Invoice with PayloadData Source: https://aiosend.readthedocs.io/en/latest/events/payload_data Shows how to instantiate a custom `PayloadData` subclass, pack it into a string format, and then use this packed data when creating an invoice. ```python my_data = MyData(foo="foo", bar=123).pack() await cp.create_invoice(1, "USDT", payload=my_data) ``` -------------------------------- ### Get Filter Result as Handler Argument using Magic Filter Source: https://aiosend.readthedocs.io/en/latest/events/filters This code shows how to use the 'as_' method from MagicFilter to capture the result of a filter and pass it as an argument to the handler. In 'handler1', 'F.payload.as_("payload")' makes the invoice's payload available as the 'payload' argument within the handler function. This simplifies accessing filter-derived data. ```python from magic_filter import F # or from aiogram import F @cp.invoice_paid(F.payload.as_("payload")) async def handler1(invoice: Invoice, payload: str) -> None: print(f"paid #{invoice.invoice_id} paylaod: {payload}") ``` -------------------------------- ### Session Management Source: https://aiosend.readthedocs.io/en/latest/client/index Details the session implementations, including AiohttpSession and BaseSession, for making HTTP requests. ```APIDOC ## Session API ### Description This section describes the session implementations used for making HTTP requests. ### AiohttpSession - `AiohttpSession.request()` ### BaseSession - `BaseSession.request()` ``` -------------------------------- ### BaseSession Class Source: https://aiosend.readthedocs.io/en/latest/client/session Abstract base class for implementing custom session classes in aiosend. ```APIDOC ## BaseSession Class ### Description Abstract session class. If you want to implement your own session class, you should inherit this class. ### Class `aiosend.client.session.BaseSession` ### Parameters - **network**: (object) - Represents the network configuration. - **timeout** (int) - Optional - Timeout in seconds for requests. Defaults to 300. ### Methods #### `_request(token, client, method)` ##### Description Make http request. This is an abstract method that must be implemented by subclasses. ##### Method `abstractmethod async` ##### Parameters - **token**: (any) - Authentication token or credentials. - **client**: (any) - The client object making the request. - **method**: (any) - The HTTP method and details of the request. ##### Return Type `TypeVar`(`_CryptoPayType`, bound= CryptoPayObject | list | bool) ``` -------------------------------- ### CryptoPay API Methods Source: https://aiosend.readthedocs.io/en/latest/api/index This section details the available methods for interacting with the Crypto Pay API, including creating and managing invoices, checks, and transfers, as well as retrieving balances and exchange rates. ```APIDOC ## CryptoPay API Methods ### Description This section details the available methods for interacting with the Crypto Pay API. ### Methods * `CryptoPay.get_me()` * `CryptoPay.create_invoice()` * `CryptoPay.delete_invoice()` * `CryptoPay.create_check()` * `CryptoPay.delete_check()` * `CryptoPay.transfer()` * `CryptoPay.get_invoices()` * `CryptoPay.get_checks()` * `CryptoPay.get_transfers()` * `CryptoPay.get_balance()` * `CryptoPay.get_exchange_rates()` * `CryptoPay.get_currencies()` * `CryptoPay.get_stats()` ``` -------------------------------- ### Initiate a Cryptocurrency Transfer with aiosend Source: https://aiosend.readthedocs.io/en/latest/api/methods Use the `transfer` method to send cryptocurrencies from your app's balance to a user. This method requires prior enabling in your app's security settings within @CryptoBot. It returns a `Transfer` object upon successful completion. Parameters include user ID, asset type, amount, an optional unique spend ID for idempotency, an optional comment for the user, and an option to disable user notifications. ```python from aiosend import CryptoPay async def perform_transfer(): pay = CryptoPay("YOUR_BOT_TOKEN") try: transfer = await pay.transfer( user_id=123456789, asset="USDT", amount=10.5, spend_id="random_unique_spend_id_123", comment="Thank you for your purchase!", disable_send_notification=False ) print(f"Transfer successful: {transfer}") except Exception as e: print(f"Transfer failed: {e}") ``` -------------------------------- ### CryptoPay.get_balance() Source: https://aiosend.readthedocs.io/en/latest/api/methods Retrieves the balances of your application. This method requires no parameters. ```APIDOC ## GET /getBalance ### Description Use this method to get balances of your app. Requires no parameters. Returns array of `aiosend.types.Balance`. ### Method GET ### Endpoint /getBalance ### Parameters #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **balances** (list[Balance]) - A list of account balances. #### Response Example ```json { "balances": [ { "currency": "USD", "available": "100.50", " 0": "0.00" } ] } ``` ``` -------------------------------- ### Deleting Objects Source: https://aiosend.readthedocs.io/en/latest/client/shortcuts Methods to delete specific objects created through the Crypto Pay API. ```APIDOC ## Deleting Objects ### Check.delete() * **Description**: Shortcut for method `aiosend.CryptoPay.delete_check()`. Use this method to delete a check created by your app. Returns `True` on success. * **Source**: https://help.crypt.bot/crypto-pay-api#deleteCheck * **Method**: (Implied as internal method call within aiosend) * **Return Type**: `bool` ### Invoice.delete() * **Description**: Shortcut for method `aiosend.CryptoPay.delete_invoice()`. Use this method to delete an invoice created by your app. Returns `True` on success. * **Source**: https://help.crypt.bot/crypto-pay-api#hwjK * **Method**: (Implied as internal method call within aiosend) * **Return Type**: `bool` ``` -------------------------------- ### Include Multiple Routers in a BaseRouter Source: https://aiosend.readthedocs.io/en/latest/events/routers Demonstrates the `include_routers` method of `BaseRouter` for including multiple routers simultaneously. This facilitates the aggregation of different routing logic into a single parent router. ```python include_routers(_* routers_) ```