### Async Quick Start with CryptoPay Source: https://github.com/medovi40k/crypto-pay-api/blob/master/README.md Asynchronous example demonstrating how to create an invoice and print its payment URL. Requires an active asyncio event loop. Ensure you replace 'YOUR_TOKEN' with your actual API token. ```python import asyncio from crypto_pay_api import CryptoPayAsync, CryptoPayConfig async def main(): cfg = CryptoPayConfig(token="YOUR_TOKEN") async with CryptoPayAsync(cfg) as cp: invoice = await cp.create_invoice(asset="USDT", amount=5) print(invoice["pay_url"]) asyncio.run(main()) ``` -------------------------------- ### Sync Quick Start with CryptoPay Source: https://github.com/medovi40k/crypto-pay-api/blob/master/README.md Synchronous example demonstrating how to create an invoice and print its payment URL. The client is used as a context manager to ensure the HTTP session is closed properly. Replace 'YOUR_TOKEN' with your actual API token. ```python from crypto_pay_api import CryptoPay, CryptoPayConfig cfg = CryptoPayConfig(token="YOUR_TOKEN") with CryptoPay(cfg) as cp: invoice = cp.create_invoice(asset="USDT", amount=5) print(invoice["pay_url"]) ``` -------------------------------- ### Install cryptopay-python-sdk Source: https://github.com/medovi40k/crypto-pay-api/blob/master/README.md Install the SDK using pip. This command installs the package and its dependencies. ```bash pip install cryptopay-python-sdk ``` -------------------------------- ### CryptoPay Configuration Options Source: https://github.com/medovi40k/crypto-pay-api/blob/master/README.md Example showing how to configure the CryptoPay client with various options including token, network, timeout, and base URL override. The token is mandatory and can be obtained from @CryptoBot on Telegram. ```python from crypto_pay_api import CryptoPayConfig cfg = CryptoPayConfig( token="YOUR_TOKEN", # required — get it from @CryptoBot on Telegram network="mainnet", # "mainnet" (default) or "testnet" timeout=20.0, # request timeout in seconds (default: 20.0) base_url_override=None, # override the API base URL if needed ) ``` -------------------------------- ### Get App Info using Synchronous Client Source: https://context7.com/medovi40k/crypto-pay-api/llms.txt Retrieve basic information about your Crypto Pay app. Requires a valid API token. ```python from crypto_pay_api import CryptoPay, CryptoPayConfig with CryptoPay(CryptoPayConfig(token="1234:AABBccDDee")) as cp: app = cp.get_me() print(app["app_id"]) print(app["name"]) print(app["payment_processing_bot_username"]) ``` -------------------------------- ### Get Asset Balances using Synchronous Client Source: https://context7.com/medovi40k/crypto-pay-api/llms.txt Fetch the available balances for all supported assets in your app's wallet. The result is a list of dictionaries. ```python with CryptoPay(CryptoPayConfig(token="1234:AABBccDDee")) as cp: balances = cp.get_balance() # balances is a list of dicts for b in balances: print(f"{b['currency_code']}: {b['available']}") # Example output: # USDT: 150.50 # TON: 20.000000000 # BTC: 0.00123456 ``` -------------------------------- ### Get Exchange Rates using Synchronous Client Source: https://context7.com/medovi40k/crypto-pay-api/llms.txt Retrieve current exchange rates for all supported cryptocurrency and fiat pairs. Useful for displaying prices or converting amounts. ```python with CryptoPay(CryptoPayConfig(token="1234:AABBccDDee")) as cp: rates = cp.get_exchange_rates() for r in rates: if r["source"] == "USDT" and r["target"] == "USD": print(f"1 USDT = {r['rate']} USD") # 1 USDT = 1.0002 USD ``` -------------------------------- ### Get Supported Currencies Source: https://context7.com/medovi40k/crypto-pay-api/llms.txt Retrieves metadata for all supported crypto and fiat currencies. The result is a dictionary where keys are currency codes and values contain details like decimals and fiat status. ```python with CryptoPay(CryptoPayConfig(token="1234:AABBccDDee")) as cp: currencies = cp.get_currencies() # currencies is a dict; iterate supported assets for code, info in currencies.items(): print(f"{code}: decimals={info.get('decimals')}, is_fiat={info.get('is_fiat')}") # USDT: decimals=2, is_fiat=False # USD: decimals=2, is_fiat=True ``` -------------------------------- ### Verify Webhook Signature Source: https://github.com/medovi40k/crypto-pay-api/blob/master/README.md Example of how to verify incoming webhook signatures from Crypto Pay using the `verify_webhook_signature` helper function. This is crucial for ensuring the authenticity of webhook requests. Ensure `request.body` and `request.headers` are correctly accessed from your web framework. ```python from crypto_pay_api import verify_webhook_signature is_valid = verify_webhook_signature( token="YOUR_TOKEN", raw_body=request.body, # raw bytes signature_header=request.headers["crypto-pay-api-signature"], ) if not is_valid: return 403 ``` -------------------------------- ### Get App Statistics Source: https://context7.com/medovi40k/crypto-pay-api/llms.txt Fetches aggregated payment statistics for a specified date range using ISO 8601 datetime strings. Provides insights into total volume, conversion rates, and unique user counts. ```python with CryptoPay(CryptoPayConfig(token="1234:AABBccDDee")) as cp: stats = cp.get_stats( start_at="2024-01-01T00:00:00Z", end_at="2024-01-31T23:59:59Z", ) print(stats["volume"]) print(stats["conversion"]) print(stats["unique_users_count"]) ``` -------------------------------- ### Initialize Synchronous CryptoPay Client with Context Manager Source: https://context7.com/medovi40k/crypto-pay-api/llms.txt Use the `with` statement for automatic session management. This is the recommended approach for the synchronous client. ```python from crypto_pay_api import CryptoPay, CryptoPayConfig cfg = CryptoPayConfig(token="1234:AABBccDDee") # Recommended: context manager (auto-closes session) with CryptoPay(cfg) as cp: me = cp.get_me() print(me["name"]) ``` -------------------------------- ### Initialize Asynchronous CryptoPay Client with Custom httpx.AsyncClient Source: https://context7.com/medovi40k/crypto-pay-api/llms.txt Pass a pre-configured `httpx.AsyncClient` to the asynchronous client. The client will not close this custom client. ```python # Bring your own httpx.AsyncClient import httpx async def custom_client(): async with httpx.AsyncClient(timeout=30) as client: cp = CryptoPayAsync(cfg, client=client) me = await cp.get_me() ``` -------------------------------- ### Initialize Asynchronous CryptoPay Client with Async Context Manager Source: https://context7.com/medovi40k/crypto-pay-api/llms.txt Use `async with` for automatic session management in asynchronous code. This is the recommended approach for `CryptoPayAsync`. ```python import asyncio from crypto_pay_api import CryptoPayAsync, CryptoPayConfig cfg = CryptoPayConfig(token="1234:AABBccDDee") async def main(): # Recommended: async context manager async with CryptoPayAsync(cfg) as cp: me = await cp.get_me() print(me["name"]) ``` -------------------------------- ### Initialize Synchronous CryptoPay Client Manually Source: https://context7.com/medovi40k/crypto-pay-api/llms.txt Manually manage the lifecycle of the synchronous client. Ensure `close()` is called to release resources. ```python # Manual lifecycle cp = CryptoPay(cfg) try: me = cp.get_me() finally: cp.close() ``` -------------------------------- ### Create Payment Invoice (Async) Source: https://context7.com/medovi40k/crypto-pay-api/llms.txt Asynchronously creates a payment invoice, supporting both crypto and fiat currencies. Optional parameters include auto-swap, expiry, callbacks, and custom payloads. Requires `asyncio` and `CryptoPayAsync`. ```python import asyncio from crypto_pay_api import CryptoPayAsync, CryptoPayConfig async def main(): async with CryptoPayAsync(CryptoPayConfig(token="1234:AABBccDDee")) as cp: # Simple crypto invoice invoice = await cp.create_invoice(asset="USDT", amount=10.0) print(invoice["invoice_id"]) print(invoice["pay_url"]) print(invoice["status"]) # Fiat invoice (any accepted crypto, auto-swaps to USDT) fiat_invoice = await cp.create_invoice( currency_type="fiat", fiat="USD", amount=25.00, accepted_assets="USDT,TON,BTC", swap_to="USDT", description="Order #1042 — Premium subscription", hidden_message="Thank you! Your account is now active.", paid_btn_name="openBot", paid_btn_url="https://t.me/MyBot?start=order1042", payload='{"order_id": 1042, "user_id": 555}', allow_comments=True, allow_anonymous=False, expires_in=3600, ) print(fiat_invoice["pay_url"]) asyncio.run(main()) ``` -------------------------------- ### Initialize Asynchronous CryptoPay Client Manually Source: https://context7.com/medovi40k/crypto-pay-api/llms.txt Manually manage the lifecycle of the asynchronous client. Ensure `aclose()` is called for proper cleanup. ```python # Manual lifecycle async def manual(): cp = CryptoPayAsync(cfg) try: me = await cp.get_me() finally: await cp.aclose() ``` -------------------------------- ### Initialize Synchronous CryptoPay Client with Custom Session Source: https://context7.com/medovi40k/crypto-pay-api/llms.txt Pass a pre-configured `requests.Session` to the synchronous client. The client will not close this session automatically. ```python # Bring your own session (session is NOT closed by the client) import requests session = requests.Session() session.proxies = {"https": "http://proxy:8080"} cp = CryptoPay(cfg, session=session) ``` -------------------------------- ### Configure CryptoPayConfig for Testnet Source: https://context7.com/medovi40k/crypto-pay-api/llms.txt Initialize the configuration object for the testnet environment. Use this for development and sandbox testing. ```python # Testnet (development / sandbox) cfg_test = CryptoPayConfig( token="1234:TestTokenHere", network="testnet", ) # Resolves to: https://testnet-pay.crypt.bot ``` -------------------------------- ### Configure CryptoPayConfig for Mainnet Source: https://context7.com/medovi40k/crypto-pay-api/llms.txt Initialize the configuration object for the mainnet environment. The API token is required and can be obtained from @CryptoBot. ```python from crypto_pay_api import CryptoPayConfig # Mainnet (production) cfg = CryptoPayConfig( token="1234:AABBccDDee", # required — from @CryptoBot network="mainnet", # "mainnet" (default) or "testnet" timeout=20.0, # HTTP timeout in seconds (default: 20.0) base_url_override=None, # override base URL, e.g. for proxies ) ``` -------------------------------- ### Handle API Errors with `CryptoPayAPIError` and `CryptoPayHTTPError` Source: https://context7.com/medovi40k/crypto-pay-api/llms.txt Demonstrates how to catch and handle specific exceptions raised by the Crypto Pay SDK. `CryptoPayAPIError` is for API-level errors (e.g., `ok: false`), while `CryptoPayHTTPError` is for network or HTTP-related issues. Both inherit from `CryptoPayError`. ```python from crypto_pay_api import ( CryptoPay, CryptoPayConfig, CryptoPayAPIError, CryptoPayHTTPError, CryptoPayError, ) cfg = CryptoPayConfig(token="1234:AABBccDDee") with CryptoPay(cfg) as cp: try: invoice = cp.create_invoice(asset="USDT", amount=999999) except CryptoPayAPIError as e: # API returned ok=false — logical error from the server print(f"API error code: {e.error_code}") # e.g. "BALANCE_TOO_SMALL" print(f"Full response: {e.raw}") # {"ok": False, "error": {...}} except CryptoPayHTTPError as e: # Network error, timeout, or HTTP 4xx/5xx print(f"HTTP/network error: {e}") except CryptoPayError as e: # Catch-all for any SDK error print(f"Unexpected SDK error: {e}") ``` -------------------------------- ### CryptoPay: get_me() Source: https://context7.com/medovi40k/crypto-pay-api/llms.txt Retrieves basic information about the app associated with the API token. ```APIDOC ## get_me() ### Description Returns basic information about the app associated with the API token. ### Method `get_me()` ### Parameters None ### Request Example ```python from crypto_pay_api import CryptoPay, CryptoPayConfig with CryptoPay(CryptoPayConfig(token="1234:AABBccDDee")) as cp: app = cp.get_me() print(app["app_id"]) print(app["name"]) print(app["payment_processing_bot_username"]) ``` ### Response #### Success Response Returns a dictionary containing app information. - **app_id** (int) - The unique identifier for the application. - **name** (str) - The name of the application. - **payment_processing_bot_username** (str) - The username of the payment processing bot. #### Response Example ```json { "app_id": 12345, "name": "My Payment App", "payment_processing_bot_username": "CryptoBot" } ``` ``` -------------------------------- ### App Methods Source: https://github.com/medovi40k/crypto-pay-api/blob/master/README.md Methods for retrieving information about the associated app. ```APIDOC ## App Methods | Method | Description | |---|---| | `get_me()` | Returns basic info about the app associated with the token | | `get_balance()` | Returns list of balance objects per asset | | `get_exchange_rates()` | Returns current exchange rates | | `get_currencies()` | Returns list of supported currencies | | `get_stats(*, start_at, end_at)` | Returns app statistics for a given date range | ``` -------------------------------- ### Handle Async Errors with CryptoPayAPIError Source: https://context7.com/medovi40k/crypto-pay-api/llms.txt Demonstrates how to handle specific API errors, such as an invalid user ID, using a try-except block with CryptoPayAPIError. Ensure the CryptoPayAPIError class is imported. ```python import asyncio from crypto_pay_api import CryptoPayAsync, CryptoPayAPIError async def main(): async with CryptoPayAsync(cfg) as cp: try: await cp.transfer( user_id=0, # invalid user asset="USDT", amount=10, spend_id="test-001", ) except CryptoPayAPIError as e: print(e.error_code) # "INVALID_USER" asyncio.run(main()) ``` -------------------------------- ### List Transfers with `get_transfers()` Source: https://context7.com/medovi40k/crypto-pay-api/llms.txt Returns a filtered list of past transfers. Supports filtering by asset, IDs, `spend_id`, and pagination. Use this to review transaction history or look up specific transfers. ```python with CryptoPay(CryptoPayConfig(token="1234:AABBccDDee")) as cp: # All USDT transfers transfers = cp.get_transfers(asset="USDT", count=25) for t in transfers: print(t["transfer_id"], t["amount"], t["status"]) # Look up by your idempotency key by_spend_id = cp.get_transfers(spend_id="payout-order-789") # Look up specific transfer IDs specific = cp.get_transfers(transfer_ids=[445566, 445567]) ``` -------------------------------- ### create_invoice() Source: https://context7.com/medovi40k/crypto-pay-api/llms.txt Creates a payment invoice. Supports crypto and fiat invoices with various customization options like auto-swap, expiry, and callbacks. ```APIDOC ## create_invoice() ### Description Creates a payment invoice and returns its data including a `pay_url` the payer opens in Telegram. Supports crypto and fiat invoices, optional auto-swap, expiry, callbacks, and custom payloads. ### Method POST (assumed) ### Endpoint `/invoices` (assumed) ### Parameters #### Request Body - **asset** (string) - Optional - The crypto asset to be paid (e.g., `USDT`). Required if `currency_type` is not `fiat`. - **amount** (number) - Required - The amount to be paid. - **currency_type** (string) - Optional - Type of currency, either `crypto` (default) or `fiat`. - **fiat** (string) - Optional - The fiat currency code (e.g., `USD`). Required if `currency_type` is `fiat`. - **accepted_assets** (string) - Optional - Comma-separated list of crypto assets accepted for payment (e.g., `USDT,TON,BTC`). - **swap_to** (string) - Optional - The crypto asset to which all payments should be swapped. - **description** (string) - Optional - Description of the invoice. - **hidden_message** (string) - Optional - A message shown to the user after successful payment. - **paid_btn_name** (string) - Optional - Text for the button on the success screen (e.g., `openBot`). - **paid_btn_url** (string) - Optional - URL for the button on the success screen. - **payload** (string) - Optional - Custom data to be sent with the invoice, max 4 KB. - **allow_comments** (boolean) - Optional - Whether to allow comments on the invoice. - **allow_anonymous** (boolean) - Optional - Whether to allow anonymous payments. - **expires_in** (integer) - Optional - The number of seconds until the invoice expires. ### Request Example ```json { "asset": "USDT", "amount": 10.0 } ``` ```json { "currency_type": "fiat", "fiat": "USD", "amount": 25.00, "accepted_assets": "USDT,TON,BTC", "swap_to": "USDT", "description": "Order #1042 — Premium subscription", "hidden_message": "Thank you! Your account is now active.", "paid_btn_name": "openBot", "paid_btn_url": "https://t.me/MyBot?start=order1042", "payload": "{\"order_id\": 1042, \"user_id\": 555}", "allow_comments": true, "allow_anonymous": false, "expires_in": 3600 } ``` ### Response #### Success Response (200) - **invoice_id** (integer) - The unique ID of the created invoice. - **pay_url** (string) - The URL the payer opens in Telegram to pay the invoice. - **status** (string) - The current status of the invoice (e.g., `active`). ### Response Example ```json { "invoice_id": 987654, "pay_url": "https://t.me/CryptoBot?start=...", "status": "active" } ``` ``` -------------------------------- ### CryptoPay: get_balance() Source: https://context7.com/medovi40k/crypto-pay-api/llms.txt Retrieves a list of asset balances available in the app wallet. ```APIDOC ## get_balance() ### Description Returns a list of balance objects, one per supported asset, showing available funds in the app wallet. ### Method `get_balance()` ### Parameters None ### Request Example ```python with CryptoPay(CryptoPayConfig(token="1234:AABBccDDee")) as cp: balances = cp.get_balance() for b in balances: print(f"{b['currency_code']}: {b['available']}") ``` ### Response #### Success Response Returns a list of dictionaries, where each dictionary represents the balance for a specific asset. - **currency_code** (str) - The code of the currency (e.g., "USDT", "TON", "BTC"). - **available** (str) - The available amount of the currency. #### Response Example ```json [ { "currency_code": "USDT", "available": "150.50" }, { "currency_code": "TON", "available": "20.000000000" }, { "currency_code": "BTC", "available": "0.00123456" } ] ``` ``` -------------------------------- ### create_check() Source: https://context7.com/medovi40k/crypto-pay-api/llms.txt Creates a one-time crypto check (a claimable voucher). Optionally pins it to a specific Telegram user. ```APIDOC ## create_check() ### Description Creates a one-time crypto check (a claimable voucher). Optionally pins it to a specific Telegram user (by ID or username). ### Method POST (assumed) ### Endpoint `/checks` (assumed) ### Parameters #### Request Body - **asset** (string) - Required - The crypto asset for the check (e.g., `TON`). - **amount** (number) - Required - The amount of the check. - **pin_to_username** (string) - Optional - The username of the Telegram user to pin the check to. - **pin_to_user_id** (integer) - Optional - The user ID of the Telegram user to pin the check to. ### Request Example ```json { "asset": "TON", "amount": 5.0 } ``` ```json { "asset": "USDT", "amount": 20.0, "pin_to_username": "johndoe" } ``` ### Response #### Success Response (200) - **check_id** (integer) - The unique ID of the created check. - **bot_check_url** (string) - The Telegram URL to claim the check. ### Response Example ```json { "check_id": 112233, "bot_check_url": "https://t.me/CryptoBot?start=..." } ``` ``` -------------------------------- ### Create Crypto Check Source: https://context7.com/medovi40k/crypto-pay-api/llms.txt Creates a one-time crypto check (voucher) that can be claimed. Optionally, it can be pinned to a specific Telegram user by username or user ID. ```python with CryptoPay(CryptoPayConfig(token="1234:AABBccDDee")) as cp: # General check (anyone can claim) check = cp.create_check(asset="TON", amount=5.0) print(check["check_id"]) print(check["bot_check_url"]) # Pinned to a specific user pinned_check = cp.create_check( asset="USDT", amount=20.0, pin_to_username="johndoe", ) print(pinned_check["bot_check_url"]) ``` -------------------------------- ### get_currencies() Source: https://context7.com/medovi40k/crypto-pay-api/llms.txt Returns metadata for all currencies (crypto and fiat) accepted by the platform. This method is useful for understanding the available assets for transactions. ```APIDOC ## get_currencies() ### Description Returns metadata for all currencies (crypto and fiat) accepted by the platform. ### Method GET (assumed, based on function name and return type) ### Endpoint `/currencies` (assumed) ### Parameters None ### Response #### Success Response (200) - **currencies** (dict) - A dictionary where keys are currency codes and values are objects containing currency metadata (e.g., `decimals`, `is_fiat`). ### Response Example ```json { "USDT": {"decimals": 2, "is_fiat": false}, "USD": {"decimals": 2, "is_fiat": true} } ``` ``` -------------------------------- ### Deterministic JSON Serialization with `canonical_json_bytes()` Source: https://context7.com/medovi40k/crypto-pay-api/llms.txt If your framework does not expose raw request bytes, use this helper to re-serialize a parsed object into canonical compact JSON bytes for signature verification. This is crucial when the raw request body is not directly accessible. ```python from crypto_pay_api import verify_webhook_signature, canonical_json_bytes # When raw bytes are unavailable — re-serialize the parsed dict parsed_body = {"update_type": "invoice_paid", "payload": {"invoice_id": 987654}} raw_bytes = canonical_json_bytes(parsed_body) # b'{"update_type":"invoice_paid","payload":{"invoice_id":987654}}' is_valid = verify_webhook_signature( token="1234:AABBccDDee", raw_body=raw_bytes, signature_header="abc123def456...", ) ``` -------------------------------- ### Error Handling: CryptoPayAPIError and CryptoPayHTTPError Source: https://context7.com/medovi40k/crypto-pay-api/llms.txt `CryptoPayAPIError` is raised when the API returns `ok: false` (e.g., invalid token, bad parameters, insufficient balance). `CryptoPayHTTPError` is raised for network failures or non-2xx HTTP responses. Both inherit from `CryptoPayError`. ```APIDOC ## Error Handling ### `CryptoPayAPIError` and `CryptoPayHTTPError` `CryptoPayAPIError` is raised when the API returns `ok: false` (e.g., invalid token, bad parameters, insufficient balance). `CryptoPayHTTPError` is raised for network failures or non-2xx HTTP responses. Both inherit from `CryptoPayError`. ### Request Example ```python from crypto_pay_api import ( CryptoPay, CryptoPayConfig, CryptoPayAPIError, CryptoPayHTTPError, CryptoPayError, ) cfg = CryptoPayConfig(token="1234:AABBccDDee") with CryptoPay(cfg) as cp: try: invoice = cp.create_invoice(asset="USDT", amount=999999) except CryptoPayAPIError as e: # API returned ok=false — logical error from the server print(f"API error code: {e.error_code}") # e.g. "BALANCE_TOO_SMALL" print(f"Full response: {e.raw}") # {"ok": False, "error": {...}} except CryptoPayHTTPError as e: # Network error, timeout, or HTTP 4xx/5xx print(f"HTTP/network error: {e}") except CryptoPayError as e: # Catch-all for any SDK error print(f"Unexpected SDK error: {e}") ``` ``` -------------------------------- ### Check Methods Source: https://github.com/medovi40k/crypto-pay-api/blob/master/README.md Methods for managing payment checks. ```APIDOC ### Checks | Method | Description | |---|---| | `create_check(*, asset, amount, pin_to_user_id, pin_to_username)` | Create a check | | `delete_check(check_id)` | Delete a check by ID | | `get_checks(*, asset, check_ids, status, offset, count)` | List checks with optional filters | ``` -------------------------------- ### Invoice Methods Source: https://github.com/medovi40k/crypto-pay-api/blob/master/README.md Methods for managing payment invoices. ```APIDOC ## Invoices | Method | Description | |---|---| | `create_invoice(*, amount, ...)` | Create a payment invoice | | `delete_invoice(invoice_id)` | Delete an invoice by ID | | `get_invoices(*, asset, fiat, invoice_ids, status, offset, count)` | List invoices with optional filters | **`create_invoice` parameters:** | Parameter | Type | Description | |---|---|---| | `amount` | `str \| float` | Amount to charge (required) | | `currency_type` | `"crypto" \| "fiat"` | Type of currency (optional) | | `asset` | `str` | Crypto asset, e.g. `"USDT"`, `"TON"` | | `fiat` | `str` | Fiat currency code, e.g. `"USD"` | | `accepted_assets` | `str` | Comma-separated accepted assets (for fiat invoices) | | `swap_to` | `str` | Auto-swap received asset to this asset | | `description` | `str` | Invoice description shown to the payer | | `hidden_message` | `str` | Message shown after payment | | `paid_btn_name` | `str` | Label for the button after payment | | `paid_btn_url` | `str` | URL for the button after payment | | `payload` | `str` | Custom string attached to the invoice (max 4kb) | | `allow_comments` | `bool` | Allow payer to leave a comment | | `allow_anonymous` | `bool` | Allow anonymous payments | | `expires_in` | `int` | Invoice lifetime in seconds | ``` -------------------------------- ### CryptoPay: get_exchange_rates() Source: https://context7.com/medovi40k/crypto-pay-api/llms.txt Retrieves current exchange rates for all supported crypto/fiat pairs. ```APIDOC ## get_exchange_rates() ### Description Returns exchange rates for all supported crypto/fiat pairs. Useful for displaying prices in fiat or converting amounts. ### Method `get_exchange_rates()` ### Parameters None ### Request Example ```python with CryptoPay(CryptoPayConfig(token="1234:AABBccDDee")) as cp: rates = cp.get_exchange_rates() for r in rates: if r["source"] == "USDT" and r["target"] == "USD": print(f"1 USDT = {r['rate']} USD") ``` ### Response #### Success Response Returns a list of dictionaries, where each dictionary represents an exchange rate. - **source** (str) - The source currency code. - **target** (str) - The target currency code. - **rate** (str) - The exchange rate. #### Response Example ```json [ { "source": "USDT", "target": "USD", "rate": "1.0002" }, { "source": "BTC", "target": "USDT", "rate": "65000.50" } ] ``` ``` -------------------------------- ### List Invoices Source: https://context7.com/medovi40k/crypto-pay-api/llms.txt Retrieves a filtered list of invoices. Supports filtering by asset, fiat currency, specific IDs, status, and pagination parameters like `count` and `offset`. ```python with CryptoPay(CryptoPayConfig(token="1234:AABBccDDee")) as cp: # All active USDT invoices active = cp.get_invoices(asset="USDT", status="active", count=25, offset=0) for inv in active: print(inv["invoice_id"], inv["amount"], inv["status"]) # Look up specific invoices by ID list specific = cp.get_invoices(invoice_ids=[987654, 987655, 987656]) for inv in specific: print(inv["invoice_id"], inv["status"]) # All paid USD fiat invoices paid_fiat = cp.get_invoices(fiat="USD", status="paid") ``` -------------------------------- ### Transfer Methods Source: https://github.com/medovi40k/crypto-pay-api/blob/master/README.md Methods for sending coins to Telegram users and listing transfers. ```APIDOC ### Transfers | Method | Description | |---|---| | `transfer(*, user_id, asset, amount, spend_id, comment, disable_send_notification)` | Send coins to a Telegram user | | `get_transfers(*, asset, transfer_ids, spend_id, offset, count)` | List transfers with optional filters | ``` -------------------------------- ### get_stats() Source: https://context7.com/medovi40k/crypto-pay-api/llms.txt Returns aggregated payment statistics for a specified date range. Useful for tracking platform usage and financial performance. ```APIDOC ## get_stats() ### Description Returns aggregated payment statistics for a specified date range (ISO 8601 datetime strings). ### Method GET (assumed) ### Endpoint `/stats` (assumed) ### Parameters #### Query Parameters - **start_at** (string) - Required - The start of the date range in ISO 8601 format. - **end_at** (string) - Required - The end of the date range in ISO 8601 format. ### Response #### Success Response (200) - **volume** (number) - Total paid volume within the specified range. - **conversion** (number) - Conversion rate. - **unique_users_count** (integer) - Number of unique users. ### Response Example ```json { "volume": 1500.75, "conversion": 0.95, "unique_users_count": 120 } ``` ``` -------------------------------- ### Handle CryptoPay API and HTTP Errors in Python Source: https://github.com/medovi40k/crypto-pay-api/blob/master/README.md Use this snippet to catch and process both API-level errors (e.g., invalid parameters) and network/HTTP errors when making requests to the CryptoPay API. It shows how to access specific error details like error codes and raw responses. ```python from crypto_pay_api import CryptoPayAPIError, CryptoPayHTTPError try: invoice = cp.create_invoice(asset="USDT", amount=5) except CryptoPayAPIError as e: # API returned ok=false (e.g. invalid token, bad params) print(e.error_code) # string error code from the API print(e.raw) # full raw response dict except CryptoPayHTTPError as e: # Network error or non-2xx HTTP response print(e) ``` -------------------------------- ### get_invoices() Source: https://context7.com/medovi40k/crypto-pay-api/llms.txt Retrieves a filtered list of invoices. Supports filtering by asset, fiat, specific IDs, status, and pagination. ```APIDOC ## get_invoices() ### Description Retrieves a filtered list of invoices. Supports filtering by asset, fiat, specific IDs, status, and pagination. ### Method GET (assumed) ### Endpoint `/invoices` (assumed) ### Parameters #### Query Parameters - **asset** (string) - Optional - Filter by crypto asset (e.g., `USDT`). - **fiat** (string) - Optional - Filter by fiat currency (e.g., `USD`). - **status** (string) - Optional - Filter by invoice status (e.g., `active`, `paid`). - **invoice_ids** (list of integers) - Optional - Filter by a list of specific invoice IDs. - **count** (integer) - Optional - Number of invoices to return per page (default 100). - **offset** (integer) - Optional - Offset for pagination. ### Response #### Success Response (200) - **invoices** (list of objects) - A list of invoice objects, each containing details like `invoice_id`, `amount`, and `status`. ### Response Example ```json [ { "invoice_id": 987654, "amount": 10.0, "status": "active" }, { "invoice_id": 987655, "amount": 20.0, "status": "paid" } ] ``` ``` -------------------------------- ### Send Coins to a Telegram User with `transfer()` Source: https://context7.com/medovi40k/crypto-pay-api/llms.txt Transfers cryptocurrency to a Telegram user's Crypto Bot wallet. Requires a unique `spend_id` per logical operation to guarantee idempotency. Use this for payouts or bonuses. ```python import asyncio from crypto_pay_api import CryptoPayAsync, CryptoPayConfig async def main(): async with CryptoPayAsync(CryptoPayConfig(token="1234:AABBccDDee")) as cp: result = await cp.transfer( user_id=123456789, # recipient Telegram user_id asset="USDT", amount=15.0, spend_id="payout-order-789", # unique idempotency key (your system) comment="Referral bonus payout", disable_send_notification=False, # notify recipient in Telegram ) print(result["transfer_id"]) print(result["status"]) asyncio.run(main()) ``` -------------------------------- ### Validate Incoming Webhooks with `verify_webhook_signature()` Source: https://context7.com/medovi40k/crypto-pay-api/llms.txt Verifies the HMAC-SHA256 signature on incoming Crypto Pay webhook requests to authenticate events. The secret key is derived as `SHA256(app_token)`. Use this inside any web framework webhook handler before processing events. ```python # Example: FastAPI webhook handler from fastapi import FastAPI, Request, HTTPException from crypto_pay_api import verify_webhook_signature app = FastAPI() TOKEN = "1234:AABBccDDee" @app.post("/webhook/cryptopay") async def cryptopay_webhook(request: Request): raw_body = await request.body() signature = request.headers.get("crypto-pay-api-signature", "") if not verify_webhook_signature( token=TOKEN, raw_body=raw_body, # raw bytes — do NOT parse before verifying signature_header=signature, ): raise HTTPException(status_code=403, detail="Invalid signature") payload = await request.json() update_type = payload.get("update_type") # e.g. "invoice_paid" invoice = payload.get("payload", {}) print(f"Invoice {invoice.get('invoice_id')} is now {invoice.get('status')}") return {"ok": True} ``` -------------------------------- ### canonical_json_bytes() — Deterministic JSON Serialization Source: https://context7.com/medovi40k/crypto-pay-api/llms.txt If your framework does not expose raw request bytes (e.g., it parses JSON before your code runs), use this helper to re-serialize the parsed object into canonical compact JSON bytes for signature verification. ```APIDOC ## canonical_json_bytes() ### Description If your framework does not expose raw request bytes (e.g., it parses JSON before your code runs), use this helper to re-serialize the parsed object into canonical compact JSON bytes for signature verification. ### Method `canonical_json_bytes` ### Parameters #### Arguments - **data** (dict) - Required - The Python dictionary to serialize. ### Response Returns the canonical compact JSON bytes representation of the input dictionary. ### Request Example ```python from crypto_pay_api import verify_webhook_signature, canonical_json_bytes # When raw bytes are unavailable — re-serialize the parsed dict parsed_body = {"update_type": "invoice_paid", "payload": {"invoice_id": 987654}} raw_bytes = canonical_json_bytes(parsed_body) # b'{"update_type":"invoice_paid","payload":{"invoice_id":987654}}' is_valid = verify_webhook_signature( token="1234:AABBccDDee", raw_body=raw_bytes, signature_header="abc123def456...", ) ``` ``` -------------------------------- ### get_checks() Source: https://context7.com/medovi40k/crypto-pay-api/llms.txt Returns a filtered list of checks with optional filtering by asset, IDs, status, and pagination. ```APIDOC ## get_checks() ### Description Returns a filtered list of checks with optional filtering by asset, IDs, status (`"active"` or `"activated"`), and pagination. ### Method GET (assumed) ### Endpoint `/checks` (assumed) ### Parameters #### Query Parameters - **asset** (string) - Optional - Filter by crypto asset (e.g., `USDT`). - **status** (string) - Optional - Filter by check status (`active` or `activated`). - **check_ids** (list of integers) - Optional - Filter by a list of specific check IDs. - **count** (integer) - Optional - Number of checks to return per page (default 100). - **offset** (integer) - Optional - Offset for pagination. ### Response #### Success Response (200) - **checks** (list of objects) - A list of check objects, each containing details like `check_id`, `asset`, and `amount`. ### Response Example ```json [ { "check_id": 112233, "asset": "TON", "amount": 5.0, "status": "active" }, { "check_id": 112234, "asset": "USDT", "amount": 20.0, "status": "activated" } ] ``` ``` -------------------------------- ### get_transfers() — List Transfers Source: https://context7.com/medovi40k/crypto-pay-api/llms.txt Returns a filtered list of past transfers with optional filtering by asset, IDs, `spend_id`, and pagination. ```APIDOC ## get_transfers() ### Description Returns a filtered list of past transfers with optional filtering by asset, IDs, `spend_id`, and pagination. ### Method `get_transfers` ### Parameters #### Query Parameters - **asset** (string) - Optional - Filter transfers by asset (e.g., "USDT"). - **count** (integer) - Optional - The number of transfers to retrieve per page. - **spend_id** (string) - Optional - Filter transfers by your unique idempotency key. - **transfer_ids** (list of integers) - Optional - Filter transfers by a list of specific transfer IDs. ### Response #### Success Response (200) - **transfer_id** (string) - The unique identifier for the transfer. - **amount** (float) - The amount of cryptocurrency transferred. - **status** (string) - The status of the transfer. ### Request Example ```python # All USDT transfers transfers = cp.get_transfers(asset="USDT", count=25) for t in transfers: print(t["transfer_id"], t["amount"], t["status"]) # Look up by your idempotency key by_spend_id = cp.get_transfers(spend_id="payout-order-789") # Look up specific transfer IDs specific = cp.get_transfers(transfer_ids=[445566, 445567]) ``` ``` -------------------------------- ### verify_webhook_signature() — Validate Incoming Webhooks Source: https://context7.com/medovi40k/crypto-pay-api/llms.txt Verifies the HMAC-SHA256 signature on incoming Crypto Pay webhook requests. The secret key is derived as `SHA256(app_token)`. Use this inside any web framework webhook handler to authenticate events before processing them. ```APIDOC ## verify_webhook_signature() ### Description Verifies the HMAC-SHA256 signature on incoming Crypto Pay webhook requests. The secret key is derived as `SHA256(app_token)`. Use this inside any web framework webhook handler to authenticate events before processing them. ### Method `verify_webhook_signature` ### Parameters #### Arguments - **token** (string) - Required - Your Crypto Pay API token. - **raw_body** (bytes) - Required - The raw bytes of the incoming webhook request body. - **signature_header** (string) - Required - The value of the `crypto-pay-api-signature` header from the request. ### Response Returns `True` if the signature is valid, `False` otherwise. ### Request Example ```python # Example: FastAPI webhook handler from fastapi import FastAPI, Request, HTTPException from crypto_pay_api import verify_webhook_signature app = FastAPI() TOKEN = "1234:AABBccDDee" @app.post("/webhook/cryptopay") async def cryptopay_webhook(request: Request): raw_body = await request.body() signature = request.headers.get("crypto-pay-api-signature", "") if not verify_webhook_signature( token=TOKEN, raw_body=raw_body, signature_header=signature, ): raise HTTPException(status_code=403, detail="Invalid signature") payload = await request.json() update_type = payload.get("update_type") # e.g. "invoice_paid" invoice = payload.get("payload", {{}}) print(f"Invoice {invoice.get('invoice_id')} is now {invoice.get('status')}") return {"ok": True} ``` ``` -------------------------------- ### List Checks Source: https://context7.com/medovi40k/crypto-pay-api/llms.txt Retrieves a filtered list of checks. Supports filtering by asset, check IDs, status (`"active"` or `"activated"`), and pagination. ```python with CryptoPay(CryptoPayConfig(token="1234:AABBccDDee")) as cp: # All active checks checks = cp.get_checks(status="active", count=50) for c in checks: print(c["check_id"], c["asset"], c["amount"]) # Already-activated (claimed) checks claimed = cp.get_checks(status="activated", asset="USDT") # Look up specific checks specific = cp.get_checks(check_ids=[112233, 112234]) ``` -------------------------------- ### transfer() — Send Coins to a Telegram User Source: https://context7.com/medovi40k/crypto-pay-api/llms.txt Transfers cryptocurrency to a Telegram user's Crypto Bot wallet. Requires a unique `spend_id` per logical operation to guarantee idempotency. ```APIDOC ## transfer() ### Description Transfers cryptocurrency to a Telegram user's Crypto Bot wallet. Requires a unique `spend_id` per logical operation to guarantee idempotency. ### Method `transfer` ### Parameters #### Path Parameters - **user_id** (integer) - Required - The recipient Telegram user ID. - **asset** (string) - Required - The asset to transfer (e.g., "USDT"). - **amount** (float) - Required - The amount of cryptocurrency to transfer. - **spend_id** (string) - Required - A unique idempotency key generated by your system. - **comment** (string) - Optional - A comment for the transfer. - **disable_send_notification** (boolean) - Optional - Whether to disable sending a notification to the recipient in Telegram. ### Response #### Success Response (200) - **transfer_id** (string) - The unique identifier for the transfer. - **status** (string) - The status of the transfer (e.g., "completed"). ### Request Example ```python result = await cp.transfer( user_id=123456789, asset="USDT", amount=15.0, spend_id="payout-order-789", comment="Referral bonus payout", disable_send_notification=False, ) print(result["transfer_id"]) print(result["status"]) ``` ``` -------------------------------- ### Delete Invoice Source: https://context7.com/medovi40k/crypto-pay-api/llms.txt Deletes an active invoice by its ID. Returns `True` if the deletion was successful. ```python with CryptoPay(CryptoPayConfig(token="1234:AABBccDDee")) as cp: deleted = cp.delete_invoice(987654) print(deleted) # True ``` -------------------------------- ### delete_invoice() Source: https://context7.com/medovi40k/crypto-pay-api/llms.txt Deletes an active invoice by its ID. Returns `True` on success. ```APIDOC ## delete_invoice() ### Description Deletes an active invoice by its ID. Returns `True` on success. ### Method DELETE (assumed) ### Endpoint `/invoices/{invoice_id}` (assumed) ### Parameters #### Path Parameters - **invoice_id** (integer) - Required - The ID of the invoice to delete. ### Response #### Success Response (200) - **result** (boolean) - `True` if the invoice was successfully deleted, `False` otherwise. ### Response Example ```json { "result": true } ``` ``` -------------------------------- ### Delete Check Source: https://context7.com/medovi40k/crypto-pay-api/llms.txt Deletes an active check by its ID before it has been claimed. Returns `True` if the deletion was successful. ```python with CryptoPay(CryptoPayConfig(token="1234:AABBccDDee")) as cp: deleted = cp.delete_check(112233) print(deleted) # True ``` -------------------------------- ### delete_check() Source: https://context7.com/medovi40k/crypto-pay-api/llms.txt Deletes an active check by its ID before it has been claimed. ```APIDOC ## delete_check() ### Description Deletes an active check by its ID before it has been claimed. ### Method DELETE (assumed) ### Endpoint `/checks/{check_id}` (assumed) ### Parameters #### Path Parameters - **check_id** (integer) - Required - The ID of the check to delete. ### Response #### Success Response (200) - **result** (boolean) - `True` if the check was successfully deleted, `False` otherwise. ### Response Example ```json { "result": true } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.