From 1e192b524b6f4407c45a59079a91dded2e26d4f5 Mon Sep 17 00:00:00 2001 From: SychO Date: Sat, 1 Mar 2025 13:48:29 +0800 Subject: [PATCH 1/5] Add asynchronous support and improve documentation for CryptAPI library - Introduced AsyncCryptAPIHelper for non-blocking API calls. - Updated README with usage examples for both synchronous and asynchronous APIs. - Enhanced error handling and added utility functions for URL preparation. - Updated requirements to include aiohttp and certifi for async support. - Improved docstrings across the codebase for better clarity. --- README.md | 491 ++++++++++++++++++++++++++++++++------ async_test.py | 199 +++++++++++++++ cryptapi/AsyncCryptAPI.py | 276 +++++++++++++++++++++ cryptapi/CryptAPI.py | 267 +++++++++++++++------ cryptapi/__init__.py | 12 +- cryptapi/utils.py | 60 +++++ requirements.txt | 4 +- setup.py | 24 +- test.py | 128 ++++++---- 9 files changed, 1253 insertions(+), 208 deletions(-) create mode 100644 async_test.py create mode 100644 cryptapi/AsyncCryptAPI.py create mode 100644 cryptapi/utils.py diff --git a/README.md b/README.md index 075a2c7..435453b 100644 --- a/README.md +++ b/README.md @@ -2,154 +2,507 @@ # CryptAPI's Python Library -Python implementation of CryptAPI's payment gateway + +Python implementation of CryptAPI's payment gateway with both synchronous and asynchronous support. + +This library provides a simple and powerful interface to integrate cryptocurrency payments into your Python applications using the CryptAPI payment gateway. It supports all cryptocurrencies available on CryptAPI. + +## Features + +- Simple integration with CryptAPI payment gateway +- Support for all cryptocurrencies offered by CryptAPI +- Easy generation of payment addresses and QR codes +- Callback handling for payment notifications +- Real-time payment log retrieval +- Currency conversion utilities +- Fee estimation tools +- Support for both synchronous and asynchronous operations +- Utility functions for URL preparation and encoding ## Requirements: ``` Python >= 3.0 Requests >= 2.20 +aiohttp >= 3.9.1 (for async support) +certifi >= 2024.2.2 (for async support) ``` -## Install +## Installation + +Install the package using pip: ```shell script pip install python-cryptapi ``` -[on pypi](https://pypi.python.org/pypi/python-cryptapi) -or -[on GitHub](https://github.com/cryptapi/python-cryptapi) +Available [on PyPI](https://pypi.python.org/pypi/python-cryptapi) or [on GitHub](https://github.com/cryptapi/python-cryptapi) ## Usage -### Importing in your project file +The library offers two main classes: +- `CryptAPIHelper`: For synchronous (blocking) API calls +- `AsyncCryptAPIHelper`: For asynchronous (non-blocking) API calls + +### Importing in your project + +```python +from cryptapi import CryptAPIHelper # Synchronous API +from cryptapi import AsyncCryptAPIHelper # Asynchronous API +``` + +### Basic Configuration + +Both synchronous and asynchronous classes require the same initialization parameters: + +```python +# Common parameters for both APIs +coin = 'btc' # The cryptocurrency to use (e.g., 'btc', 'eth', 'bep20_usdt') +my_address = '1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa' # Your wallet address where funds will be forwarded +callback_url = 'https://example.com/payment/callback' # URL that will be called when payment is received +params = { # Custom parameters to append to callback URL + 'order_id': '12345', + 'customer_id': 'C12345' +} +cryptapi_params = { # Additional parameters for CryptAPI + 'convert': 1, + 'multi_token': 1, + 'post': 1 # Use POST instead of GET for callbacks +} +``` + +### Generating a Payment Address + +#### Synchronous API ```python from cryptapi import CryptAPIHelper + +# Initialize the helper +ca = CryptAPIHelper(coin, my_address, callback_url, params, cryptapi_params) + +# Generate a new payment address +result = ca.get_address() +address = result['address_in'] +print(f"Payment address: {address}") + +# Access other information in the result +print(f"Address URL: {result.get('address_url', '')}") +print(f"Minimum confirmations: {result.get('minimum_confirmations', '')}") +``` + +#### Asynchronous API + +```python +import asyncio +from cryptapi import AsyncCryptAPIHelper + +async def main(): + # Initialize the async helper + ca = AsyncCryptAPIHelper(coin, my_address, callback_url, params, cryptapi_params) + + # Generate a new payment address + result = await ca.get_address() + address = result['address_in'] + print(f"Payment address: {address}") + + # Access other information in the result + print(f"Address URL: {result.get('address_url', '')}") + print(f"Minimum confirmations: {result.get('minimum_confirmations', '')}") + +# Run the async function +asyncio.run(main()) ``` -### Generating a new Address +The `get_address()` method returns a dictionary containing: +- `address_in`: The generated payment address +- `address_out`: Your own address where funds will be forwarded +- `callback_url`: The processed callback URL with your parameters +- `address_url`: URL to a CryptAPI page showing payment status +- And other information about the payment setup + +### Getting Notified When Payment is Received + +Once your customer makes a payment, CryptAPI will send a callback to your `callback_url`. The callback data includes: + +- `address_in`: The payment address +- `address_out`: Your wallet address +- `coin`: The cryptocurrency used +- `confirmations`: Number of confirmations +- `txid_in`: Transaction ID on the blockchain +- `value`: Amount received +- And any custom parameters you provided in the `params` dictionary + +By default, callbacks are sent as `GET` requests, but you can set `post: 1` in the `cryptapi_params` to receive `POST` requests instead. + +> **Note**: The callback URL is automatically URL encoded to ensure it's properly handled by the API. The library preserves the structure of the URL by maintaining essential special characters (:/?=&) while encoding other characters that might cause issues. + +For more details on callback parameters, refer to the [CryptAPI documentation](https://docs.cryptapi.io/#operation/confirmedcallbackget). + +### Utility Functions + +The library provides utility functions that you can use directly in your application: + +```python +from cryptapi import prepare_url + +# Prepare and encode a URL with parameters +base_url = "https://example.com/callback" +params = {"order_id": "12345", "customer_id": "C12345"} +encoded_url = prepare_url(base_url, params) +print(f"Encoded URL: {encoded_url}") +``` + +The `prepare_url` function: +- Appends parameters to a URL using the appropriate separator (? or &) +- URL-encodes the result while preserving essential URL structure characters (:/?=&) +- Works with both absolute and relative URLs + +### Checking Payment Logs + +#### Synchronous API ```python from cryptapi import CryptAPIHelper -ca = CryptAPIHelper(coin, myAddress, callbackUrl, params, cryptapiParams) +ca = CryptAPIHelper(coin, my_address, callback_url, params, cryptapi_params) -address = ca.get_address()['address_in'] +# Get logs for this callback URL +logs = ca.get_logs() + +# Process the logs +if logs.get('status') == 'success': + callbacks = logs.get('callbacks', []) + print(f"Found {len(callbacks)} callback records") + + for callback in callbacks: + print(f"Transaction: {callback.get('txid_in')}") + print(f"Amount: {callback.get('value')} {coin}") + print(f"Confirmations: {callback.get('confirmations')}") ``` -Where: +#### Asynchronous API -* `coin` is the coin you wish to use, from CryptAPI's supported currencies (e.g 'btc', 'eth', 'erc20_usdt', ...). -* `myAddress` is your own crypto address, where your funds will be sent to. -* `callbackUrl` is the URL that will be called upon payment. -* `params` is any parameter you wish to send to identify the payment, such as `{orderId: 1234}`. -* `cryptapiParams` parameters that will be passed to CryptAPI _(check which extra parameters are available here: https://docs.cryptapi.io/#operation/create). -* `address` is the newly generated address, that you will show your users in order to receive payments. +```python +import asyncio +from cryptapi import AsyncCryptAPIHelper + +async def main(): + ca = AsyncCryptAPIHelper(coin, my_address, callback_url, params, cryptapi_params) + + # Get logs for this callback URL + logs = await ca.get_logs() + + # Process the logs + if logs.get('status') == 'success': + callbacks = logs.get('callbacks', []) + print(f"Found {len(callbacks)} callback records") + + for callback in callbacks: + print(f"Transaction: {callback.get('txid_in')}") + print(f"Amount: {callback.get('value')} {coin}") + print(f"Confirmations: {callback.get('confirmations')}") + +# Run the async function +asyncio.run(main()) +``` -### Getting notified when the user pays +The `get_logs()` method returns a dictionary containing: +- `status`: The status of the request ('success' or 'error') +- `callbacks`: An array of callback records, each containing transaction details +- Additional information about the callback history -> Once your customer makes a payment, CryptAPI will send a callback to your `callbackUrl`. This callback information is by default in ``GET`` but you can se it to ``POST`` by setting ``post: 1`` in ``cryptapiParams``. The parameters sent by CryptAPI in this callback can be consulted here: https://docs.cryptapi.io/#operation/confirmedcallbackget +### Generating a QR Code -### Checking the logs of a request +#### Synchronous API ```python from cryptapi import CryptAPIHelper -ca = CryptAPIHelper(coin, myAddress, callbackUrl, params, cryptapiParams) +ca = CryptAPIHelper(coin, my_address, callback_url, params, cryptapi_params) + +# First, generate the address +ca.get_address() + +# Then generate a QR code with an optional amount and custom size +value = '0.001' # Optional amount to pay +size = 300 # Size in pixels (default is 300) +qr_result = ca.get_qrcode(value, size) + +# The QR code is provided as a base64 encoded image +qr_code_base64 = qr_result.get('qr_code') +print(f"QR Code (base64): {qr_code_base64}") + +# The payment URI can be used directly in wallet apps +payment_uri = qr_result.get('payment_uri') +print(f"Payment URI: {payment_uri}") +``` + +#### Asynchronous API -data = ca.get_logs() +```python +import asyncio +from cryptapi import AsyncCryptAPIHelper + +async def main(): + ca = AsyncCryptAPIHelper(coin, my_address, callback_url, params, cryptapi_params) + + # First, generate the address + await ca.get_address() + + # Then generate a QR code with an optional amount and custom size + value = '0.001' # Optional amount to pay + size = 300 # Size in pixels (default is 300) + qr_result = await ca.get_qrcode(value, size) + + # The QR code is provided as a base64 encoded image + qr_code_base64 = qr_result.get('qr_code') + print(f"QR Code (base64): {qr_code_base64}") + + # The payment URI can be used directly in wallet apps + payment_uri = qr_result.get('payment_uri') + print(f"Payment URI: {payment_uri}") + +# Run the async function +asyncio.run(main()) ``` -> Same parameters as before, the ```data``` returned can b e checked here: https://docs.cryptapi.io/#operation/logs -### Generating a QR code +**Important**: You must first call `get_address()` before generating a QR code, as the QR code is for the payment address. + +The `get_qrcode()` method returns a dictionary containing: +- `qr_code`: A base64 encoded image of the QR code +- `payment_uri`: The cryptocurrency payment URI encoded in the QR code (can be used in wallet apps) + +### Estimating Transaction Fees + +#### Synchronous API ```python from cryptapi import CryptAPIHelper -ca = CryptAPIHelper(coin, myAddress, callbackUrl, params, cryptapiParams) +# This is a static method, so you can call it directly without initializing +fees = CryptAPIHelper.get_estimate('btc', addresses=1, priority='default') + +print(f"Estimated fee: {fees.get('estimated_cost')} BTC") +print(f"Estimated fee in USD: ${fees.get('estimated_cost_usd')}") +``` -### +#### Asynchronous API -qr_code = ca.get_qrcode(value, size) +```python +import asyncio +from cryptapi import AsyncCryptAPIHelper + +async def main(): + # This is a static method, so you can call it directly without initializing + fees = await AsyncCryptAPIHelper.get_estimate('btc', addresses=1, priority='default') + + print(f"Estimated fee: {fees.get('estimated_cost')} BTC") + print(f"Estimated fee in USD: ${fees.get('estimated_cost_usd')}") + +# Run the async function +asyncio.run(main()) ``` -For object creation, same parameters as before. You must first call ``getAddress` as this method requires the payment address to have been created. -For QR Code generation: +Parameters: +- `coin`: The cryptocurrency to check (e.g., 'btc', 'eth', 'bep20_usdt') +- `addresses`: The number of addresses to forward funds to (default: 1) +- `priority`: Transaction priority - 'default', 'fast', or 'fastest' (default: 'default') -* ``value`` is the value requested to the user in the coin to which the request was done. **Optional**, can be empty if you don't wish to add the value to the QR Code. -* ``size`` Size of the QR Code image in pixels. Optional, leave empty to use the default size of 512. +The `get_estimate()` method returns a dictionary containing: +- `estimated_cost`: Estimated transaction fee in the cryptocurrency +- `estimated_cost_usd`: Estimated transaction fee in USD -> Response is an object with `qr_code` (base64 encoded image data) and `payment_uri` (the value encoded in the QR), see https://docs.cryptapi.io/#operation/qrcode for more information. +### Converting Between Cryptocurrencies and Fiat -### Estimating transaction fees +#### Synchronous API ```python from cryptapi import CryptAPIHelper -ca = CryptAPIHelper(coin, myAddress, callbackUrl, params, cryptapiParams) +ca = CryptAPIHelper('btc', my_address, callback_url, params, cryptapi_params) + +# Convert 100 EUR to BTC +conversion = ca.get_conversion('eur', 100) -fees = ca.get_estimate(coin, addresses, priority) +print(f"100 EUR = {conversion.get('value_coin')} BTC") +print(f"Exchange rate: 1 EUR = {conversion.get('exchange_rate')} BTC") ``` -Where: -* ``coin`` is the coin you wish to check, from CryptAPI's supported currencies (e.g 'btc', 'eth', 'erc20_usdt', ...) -* ``addresses`` The number of addresses to forward the funds to. Optional, defaults to 1. -* ``priority`` Confirmation priority, (check [this](https://support.cryptapi.io/article/how-the-priority-parameter-works) article to learn more about it). Optional, defaults to ``default``. -> Response is an object with ``estimated_cost`` and ``estimated_cost_usd``, see https://docs.cryptapi.io/#operation/estimate for more information. +#### Asynchronous API + +```python +import asyncio +from cryptapi import AsyncCryptAPIHelper + +async def main(): + ca = AsyncCryptAPIHelper('btc', my_address, callback_url, params, cryptapi_params) + + # Convert 100 EUR to BTC + conversion = await ca.get_conversion('eur', 100) + + print(f"100 EUR = {conversion.get('value_coin')} BTC") + print(f"Exchange rate: 1 EUR = {conversion.get('exchange_rate')} BTC") + +# Run the async function +asyncio.run(main()) +``` -### Converting between coins and fiat +Parameters: +- `from_coin`: Currency to convert from, FIAT (e.g., 'usd', 'eur') or crypto +- `value`: Amount to convert + +The `get_conversion()` method returns a dictionary containing: +- `value_coin`: The converted amount in the target cryptocurrency +- `exchange_rate`: The exchange rate between the two currencies + +### Getting Information About Supported Coins + +#### Synchronous API ```python from cryptapi import CryptAPIHelper -ca = CryptAPIHelper(coin, myAddress, callbackUrl, params, cryptapiParams) +# Get info about a specific coin +btc_info = CryptAPIHelper.get_info('btc') +print(f"BTC Info: {btc_info}") -conversion = ca.get_conversion(value, from_coin) +# Get info about all coins (no parameter) +all_coins_info = CryptAPIHelper.get_info() +print(f"Total coins with info: {len(all_coins_info)}") ``` -Where: -* ``coin`` the target currency to convert to, from CryptAPI's supported currencies (e.g 'btc', 'eth', 'erc20_usdt', ...) -* ``value`` value to convert in `from`. -* ``from_coin`` currency to convert from, FIAT or crypto. -> Response is an object with ``value_coin`` and ``exchange_rate``, see https://docs.cryptapi.io/#operation/convert for more information. +#### Asynchronous API + +```python +import asyncio +from cryptapi import AsyncCryptAPIHelper + +async def main(): + # Get info about a specific coin + btc_info = await AsyncCryptAPIHelper.get_info('btc') + print(f"BTC Info: {btc_info}") + + # Get info about all coins (no parameter) + all_coins_info = await AsyncCryptAPIHelper.get_info() + print(f"Total coins with info: {len(all_coins_info)}") + +# Run the async function +asyncio.run(main()) +``` + +Parameters: +- `coin`: (Optional) Specific coin to get info for. If omitted, returns info for all coins. + +The `get_info()` method returns a dictionary containing detailed information about the requested coin(s). + +### Getting a List of Supported Coins + +#### Synchronous API -### Getting supported coins ```python from cryptapi import CryptAPIHelper -supportedCoins = CryptAPIHelper.get_supported_coins() +# Get a dictionary of all supported coins +supported_coins = CryptAPIHelper.get_supported_coins() + +# Print the number of supported coins +print(f"Number of supported coins: {len(supported_coins)}") + +# Print the list of supported coins +for ticker, name in supported_coins.items(): + print(f"{ticker}: {name}") ``` -> Response is an array with all supported coins. +#### Asynchronous API -## Help +```python +import asyncio +from cryptapi import AsyncCryptAPIHelper + +async def main(): + # Get a dictionary of all supported coins + supported_coins = await AsyncCryptAPIHelper.get_supported_coins() + + # Print the number of supported coins + print(f"Number of supported coins: {len(supported_coins)}") + + # Print the list of supported coins + for ticker, name in supported_coins.items(): + print(f"{ticker}: {name}") + +# Run the async function +asyncio.run(main()) +``` -Need help? -Contact us @ https://cryptapi.io/contacts/ +The `get_supported_coins()` method returns a dictionary with: +- Keys: Cryptocurrency tickers (e.g., 'btc', 'eth', 'bep20_usdt') +- Values: Full names of the cryptocurrencies +## Error Handling -### Changelog +Both APIs raise a `CryptAPIException` when the CryptAPI service returns an error. You should handle these exceptions in your code: -#### 1.0.0 -* Initial Release +```python +from cryptapi import CryptAPIHelper, CryptAPIException + +try: + ca = CryptAPIHelper('btc', my_address, callback_url, params, cryptapi_params) + address = ca.get_address() + # Process result... +except CryptAPIException as e: + print(f"CryptAPI error: {str(e)}") +except Exception as e: + print(f"General error: {str(e)}") +``` -#### 1.0.1 -* Minor fixes +For async code: + +```python +import asyncio +from cryptapi import AsyncCryptAPIHelper, CryptAPIException + +async def main(): + try: + ca = AsyncCryptAPIHelper('btc', my_address, callback_url, params, cryptapi_params) + address = await ca.get_address() + # Process result... + except CryptAPIException as e: + print(f"CryptAPI error: {str(e)}") + except Exception as e: + print(f"General error: {str(e)}") + +asyncio.run(main()) +``` -#### 1.0.2 -* Minor fixes +## SSL Configuration (Async API) -#### 1.0.3 -* Minor fixes +The AsyncCryptAPIHelper automatically configures a secure SSL context using the certifi package: -#### 1.0.4 -* Minor fixes +```python +import ssl +import certifi + +# This happens automatically when you create an AsyncCryptAPIHelper instance +ssl_context = ssl.create_default_context(cafile=certifi.where()) +``` + +## Help + +Need help or support? +Contact us @ https://cryptapi.io/contacts/ + +## Changelog + +#### 1.0.0 +* Initial Release -#### 1.0.5 -* Minor fixes -* Improve error handling +#### 1.0.1 - 1.0.6 +* Various minor fixes and improvements +* Improved error handling -#### 1.0.6 -* Minor improvements +#### 1.1.0 +* Added asynchronous API support via AsyncCryptAPIHelper +* Added aiohttp and certifi dependencies +* Added SSL context for secure connections +* Comprehensive documentation updates diff --git a/async_test.py b/async_test.py new file mode 100644 index 0000000..1c2c160 --- /dev/null +++ b/async_test.py @@ -0,0 +1,199 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +""" +Async CryptAPI Test File - Testing Async API functionality +""" + +import asyncio +import json +from time import time +from cryptapi import AsyncCryptAPIHelper +from cryptapi.AsyncCryptAPI import CryptAPIException + + +def print_section(title): + """Print a section title with separator lines""" + print(f"\n{'=' * 20} {title} {'=' * 20}") + + +def format_dict(d, indent=2): + """Format dictionary output for better readability""" + if not isinstance(d, dict): + return str(d) + try: + return json.dumps(d, indent=indent, ensure_ascii=False) + except: + return str(d) + + +async def run_tests(): + """ + Run all async tests + """ + start_time = time() + + print_section("Initialization") + print("Creating AsyncCryptAPIHelper instance...") + # Initialize AsyncCryptAPIHelper instance + ca = AsyncCryptAPIHelper( + "bep20_usdt", + "0xA6B78B56ee062185E405a1DDDD18cE8fcBC4395d", + "https://webhook.site/13308bd5-d20b-4d19-8597-bd9be7db36fe", + {"order_id": "1345e13232"}, + {"convert": 1, "multi_token": 1}, + ) + print("Instance created, starting method tests...") + + """ + Get payment address + """ + print_section("Test: get_address()") + try: + address_data = await ca.get_address() + print(f"Payment address created successfully!") + print(f"Address: {address_data['address_in']}") + print(f"Complete information:\n{format_dict(address_data)}") + except CryptAPIException as e: + print(f"Error getting address: {str(e)}") + except Exception as e: + print(f"Unknown error occurred: {str(e)}") + + """ + Get coin information + """ + print_section("Test: get_info('btc')") + try: + info = await AsyncCryptAPIHelper.get_info("btc") + if isinstance(info, dict) and "btc" in info: + print(f"BTC information retrieved successfully!") + btc_info = info["btc"] + print(f"Name: {btc_info.get('coin', 'Unknown')}") + print(f"Symbol: {btc_info.get('ticker', 'Unknown')}") + print( + f"Minimum transaction amount: {btc_info.get('minimum_transaction_coin', 'Unknown')} BTC" + ) + print( + f"Network fee estimate: {btc_info.get('network_fee_estimation', 'Unknown')} BTC" + ) + else: + print(f"BTC information retrieved (incomplete):\n{format_dict(info)}") + except CryptAPIException as e: + print(f"Error getting coin information: {str(e)}") + except Exception as e: + print(f"Unknown error occurred: {str(e)}") + + """ + Get all supported coins + """ + print_section("Test: get_supported_coins()") + try: + coins = await AsyncCryptAPIHelper.get_supported_coins() + print(f"Supported coins retrieved successfully!") + print(f"Total supported coins: {len(coins)}") + print("First 5 supported coins:") + for i, (ticker, name) in enumerate(list(coins.items())[:5], 1): + print(f" {i}. {ticker}: {name}") + except CryptAPIException as e: + print(f"Error getting supported coins: {str(e)}") + except Exception as e: + print(f"Unknown error occurred: {str(e)}") + + """ + Get logs + """ + print_section("Test: get_logs()") + try: + logs = await ca.get_logs() + print(f"✅ Logs retrieved successfully!") + print(f"Log information:\n{format_dict(logs)}") + except CryptAPIException as e: + print(f"⚠️ Error getting logs: {str(e)}") + print( + " Note: This is normal in test environments if no real transactions exist for this callback URL." + ) + print( + " The synchronous and asynchronous APIs use the same endpoint - both will return data if it exists." + ) + print( + " You may need to run this with a callback URL that has associated transaction data." + ) + except Exception as e: + print(f"❌ Unknown error occurred: {str(e)}") + + """ + Get QR code + """ + print_section("Test: get_qrcode()") + try: + qr_code = await ca.get_qrcode() + if "qr_code" in qr_code: + print(f"QR code retrieved successfully!") + print(f"QR code data length: {len(qr_code['qr_code'])} characters") + print(f"Payment URI: {qr_code.get('payment_uri', 'Not provided')}") + print( + "Note: QR code data is too long to display, in a real application it would be used to generate an image" + ) + else: + print( + f"QR code information retrieved (incomplete):\n{format_dict(qr_code)}" + ) + except CryptAPIException as e: + print(f"Error getting QR code: {str(e)}") + except Exception as e: + print(f"Unknown error occurred: {str(e)}") + + """ + Get currency conversion + """ + print_section("Test: get_conversion('eur', 100)") + try: + conversion = await ca.get_conversion("eur", 100) + print(f"Currency conversion successful!") + print(f"100 EUR = {conversion.get('value_coin', 'Unknown')} {ca.coin.upper()}") + print( + f"Exchange rate: 1 EUR = {conversion.get('exchange_rate', 'Unknown')} {ca.coin.upper()}" + ) + except CryptAPIException as e: + print(f"Error getting currency conversion: {str(e)}") + except Exception as e: + print(f"Unknown error occurred: {str(e)}") + + """ + Get fee estimate + """ + print_section("Test: get_estimate('ltc')") + try: + estimate = await AsyncCryptAPIHelper.get_estimate("ltc") + print(f"Fee estimation successful!") + print("LTC transaction fee estimates:") + print( + f"Default priority: {estimate.get('estimated_cost_currency', 'Unknown')} LTC" + ) + if "estimated_cost_currency_priority" in estimate: + print( + f"High priority: {estimate.get('estimated_cost_currency_priority')} LTC" + ) + else: + print("High priority: Not provided") + print(f"USD estimate: ${estimate.get('estimated_cost_usd', 'Unknown')}") + except CryptAPIException as e: + print(f"Error getting fee estimation: {str(e)}") + except Exception as e: + print(f"Unknown error occurred: {str(e)}") + + # Print total duration + end_time = time() + duration = end_time - start_time + print_section(f"Tests Complete") + print(f"Total duration: {duration:.2f} seconds") + + +if __name__ == "__main__": + # Run all async tests + print("\nStarting Async CryptAPI Tests...") + + # Use recommended async execution method + asyncio.run(run_tests()) + + print("\nAsync Tests Completed!") diff --git a/cryptapi/AsyncCryptAPI.py b/cryptapi/AsyncCryptAPI.py new file mode 100644 index 0000000..d4659b1 --- /dev/null +++ b/cryptapi/AsyncCryptAPI.py @@ -0,0 +1,276 @@ +""" +CryptAPI's Python Async Helper + +This module provides an asynchronous Python wrapper for the CryptAPI cryptocurrency payment gateway. +It allows developers to easily integrate cryptocurrency payments into their applications using +modern Python async/await syntax for improved performance and scalability. + +The AsyncCryptAPIHelper class provides asynchronous methods for creating payment addresses, +generating QR codes, checking payment logs, and performing various cryptocurrency-related operations. +""" + +import aiohttp +import ssl +import certifi +from .utils import prepare_url, process_supported_coins + + +class CryptAPIException(Exception): + """ + Exception raised for CryptAPI-specific errors. + Used when the API returns an error response. + """ + + pass + + +class AsyncCryptAPIHelper: + """ + Asynchronous helper class for interacting with the CryptAPI cryptocurrency payment gateway. + + This class provides asynchronous methods to create payment addresses, retrieve logs, + generate QR codes, and perform other cryptocurrency-related operations. All methods + are designed to be used with Python's async/await syntax for non-blocking operation. + + Attributes: + CRYPTAPI_URL (str): Base URL for the CryptAPI service. + CRYPTAPI_HOST (str): Host header value for API requests. + coin (str): The cryptocurrency ticker (e.g., 'btc', 'eth', 'bep20_usdt'). + own_address (str): Your wallet address where funds will be forwarded. + callback_url (str): URL that will be called when payment is received. + parameters (dict): Custom parameters to be appended to the callback URL. + ca_params (dict): Additional parameters for CryptAPI requests. + payment_Address (str): Generated payment address for receiving funds. + ssl_context (ssl.SSLContext): SSL context for secure connections. + conn (aiohttp.TCPConnector): TCP connector with SSL context. + """ + + CRYPTAPI_URL = "https://api.cryptapi.io/" + CRYPTAPI_HOST = "api.cryptapi.io" + + def __init__( + self, coin, own_address, callback_url, parameters=None, ca_params=None + ): + """ + Initialize a new AsyncCryptAPIHelper instance. + + Args: + coin (str): The cryptocurrency ticker (e.g., 'btc', 'eth', 'bep20_usdt'). + own_address (str): Your wallet address where funds will be forwarded. + callback_url (str): URL that will be called when payment is received. + parameters (dict, optional): Custom parameters to append to callback URL. Defaults to {}. + ca_params (dict, optional): Additional parameters for CryptAPI requests. Defaults to {}. + + Raises: + Exception: If callback_url, coin, or own_address is missing. + """ + if not parameters: + parameters = {} + + if not ca_params: + ca_params = {} + + if not callback_url: + raise Exception("Callback URL is Missing") + + if not coin: + raise Exception("Coin is Missing") + + if not own_address: + raise Exception("Address is Missing") + + coin = coin.replace("/", "_") + + self.coin = coin + self.own_address = own_address + self.callback_url = callback_url + self.parameters = parameters + self.ca_params = ca_params + self.payment_Address = "" + + self.ssl_context = ssl.create_default_context(cafile=certifi.where()) + self.conn = aiohttp.TCPConnector(ssl=self.ssl_context) + + async def get_address(self): + """ + Asynchronously generate a new payment address for receiving cryptocurrency. + + This method creates a new payment address that forwards funds to your wallet, + and sets up the callback notification. + + Returns: + dict: Response from the CryptAPI service containing the generated address + and other payment information, or None if the request failed. + + Raises: + CryptAPIException: If the API returns an error. + """ + coin = self.coin + + callback_url = prepare_url(self.callback_url, self.parameters) + + params = {"address": self.own_address, "callback": callback_url} + + if self.ca_params: + params.update(self.ca_params) + + _address = await self.process_request(coin, endpoint="create", params=params) + if _address: + self.payment_Address = _address["address_in"] + return _address + + return None + + async def get_logs(self): + """ + Asynchronously retrieve logs for the callback URL. + + This method fetches the payment logs associated with the current callback URL. + + Returns: + dict: Response from the CryptAPI service containing the callback logs. + + Raises: + CryptAPIException: If the API returns an error. + """ + coin = self.coin + callback_url = prepare_url(self.callback_url, self.parameters) + + params = {"callback": callback_url} + + return await self.process_request(coin, endpoint="logs", params=params) + + async def get_qrcode(self, value="", size=300): + """ + Asynchronously generate a QR code for the payment address. + + Args: + value (str, optional): The amount to pay. Defaults to '' (empty string). + size (int, optional): Size of the QR code in pixels. Defaults to 300. + + Returns: + dict: Response from the CryptAPI service containing the QR code data. + + Raises: + CryptAPIException: If the API returns an error. + """ + params = {"address": self.payment_Address, "size": size} + + if value: + params["value"] = value + + return await self.process_request(self.coin, endpoint="qrcode", params=params) + + async def get_conversion(self, from_coin, value): + """ + Asynchronously get conversion rates between currencies. + + Args: + from_coin (str): Source currency code (e.g., 'usd', 'eur'). + value (float): Amount to convert. + + Returns: + dict: Response from the CryptAPI service containing conversion information. + + Raises: + CryptAPIException: If the API returns an error. + """ + params = {"from": from_coin, "value": value} + + return await self.process_request(self.coin, endpoint="convert", params=params) + + @staticmethod + async def get_info(coin=""): + """ + Asynchronously get information about a specific coin or all supported coins. + + Args: + coin (str, optional): Coin ticker. If empty, returns info for all coins. Defaults to ''. + + Returns: + dict: Response from the CryptAPI service containing coin information. + + Raises: + CryptAPIException: If the API returns an error. + """ + return await AsyncCryptAPIHelper.process_request(coin, endpoint="info") + + @staticmethod + async def get_supported_coins(): + """ + Asynchronously get a list of all supported cryptocurrencies. + + Returns: + dict: Dictionary of supported coins with tickers as keys and names as values. + + Raises: + CryptAPIException: If the API returns an error. + """ + _info = await AsyncCryptAPIHelper.get_info("") + return process_supported_coins(_info) + + @staticmethod + async def get_estimate(coin, addresses=1, priority="default"): + """ + Asynchronously get an estimate of the network fees. + + Args: + coin (str): Coin ticker. + addresses (int, optional): Number of addresses. Defaults to 1. + priority (str, optional): Transaction priority ('default', 'fast', 'fastest'). Defaults to 'default'. + + Returns: + dict: Response from the CryptAPI service containing fee estimates. + + Raises: + CryptAPIException: If the API returns an error. + """ + params = {"addresses": addresses, "priority": priority} + + return await AsyncCryptAPIHelper.process_request( + coin, endpoint="estimate", params=params + ) + + @staticmethod + async def process_request(coin=None, endpoint="", params=None): + """ + Process an asynchronous API request to the CryptAPI service. + + Args: + coin (str, optional): Coin ticker. Defaults to None. + endpoint (str, optional): API endpoint. Defaults to ''. + params (dict, optional): Request parameters. Defaults to None. + + Returns: + dict: JSON response from the API. + + Raises: + CryptAPIException: If the API returns an error. + """ + if coin: + coin += "/" + else: + coin = "" + + url = "{base_url}{coin}{endpoint}/".format( + base_url=AsyncCryptAPIHelper.CRYPTAPI_URL, + coin=coin.replace("_", "/"), + endpoint=endpoint, + ) + + ssl_context = ssl.create_default_context(cafile=certifi.where()) + + async with aiohttp.ClientSession( + connector=aiohttp.TCPConnector(ssl=ssl_context) + ) as session: + async with session.get( + url=url, + params=params, + headers={"Host": AsyncCryptAPIHelper.CRYPTAPI_HOST}, + ) as response: + response_obj = await response.json() + + if response_obj.get("status") == "error": + raise CryptAPIException(response_obj["error"]) + + return response_obj diff --git a/cryptapi/CryptAPI.py b/cryptapi/CryptAPI.py index daf5d3a..7f310a2 100644 --- a/cryptapi/CryptAPI.py +++ b/cryptapi/CryptAPI.py @@ -1,20 +1,63 @@ """ CryptAPI's Python Helper + +This module provides a Python wrapper for the CryptAPI cryptocurrency payment gateway. +It allows developers to easily integrate cryptocurrency payments into their applications. + +The CryptAPIHelper class provides methods for creating payment addresses, generating QR codes, +checking payment logs, and performing various cryptocurrency-related operations. """ import requests -from requests.models import PreparedRequest +from .utils import prepare_url, process_supported_coins class CryptAPIException(Exception): + """ + Exception raised for CryptAPI-specific errors. + Used when the API returns an error response. + """ + pass class CryptAPIHelper: - CRYPTAPI_URL = 'https://api.cryptapi.io/' - CRYPTAPI_HOST = 'api.cryptapi.io' - - def __init__(self, coin, own_address, callback_url, parameters=None, ca_params=None): + """ + Helper class for interacting with the CryptAPI cryptocurrency payment gateway. + + This class provides methods to create payment addresses, retrieve logs, + generate QR codes, and perform other cryptocurrency-related operations. + + Attributes: + CRYPTAPI_URL (str): Base URL for the CryptAPI service. + CRYPTAPI_HOST (str): Host header value for API requests. + coin (str): The cryptocurrency ticker (e.g., 'btc', 'eth', 'bep20_usdt'). + own_address (str): Your wallet address where funds will be forwarded. + callback_url (str): URL that will be called when payment is received. + parameters (dict): Custom parameters to be appended to the callback URL. + ca_params (dict): Additional parameters for CryptAPI requests. + payment_Address (str): Generated payment address for receiving funds. + """ + + CRYPTAPI_URL = "https://api.cryptapi.io/" + CRYPTAPI_HOST = "api.cryptapi.io" + + def __init__( + self, coin, own_address, callback_url, parameters=None, ca_params=None + ): + """ + Initialize a new CryptAPIHelper instance. + + Args: + coin (str): The cryptocurrency ticker (e.g., 'btc', 'eth', 'bep20_usdt'). + own_address (str): Your wallet address where funds will be forwarded. + callback_url (str): URL that will be called when payment is received. + parameters (dict, optional): Custom parameters to append to callback URL. Defaults to {}. + ca_params (dict, optional): Additional parameters for CryptAPI requests. Defaults to {}. + + Raises: + Exception: If callback_url, coin, or own_address is missing. + """ if not parameters: parameters = {} @@ -25,125 +68,211 @@ def __init__(self, coin, own_address, callback_url, parameters=None, ca_params=N raise Exception("Callback URL is Missing") if not coin: - raise Exception('Coin is Missing') + raise Exception("Coin is Missing") if not own_address: - raise Exception('Address is Missing') + raise Exception("Address is Missing") - coin = coin.replace('/', '_') + coin = coin.replace("/", "_") self.coin = coin self.own_address = own_address self.callback_url = callback_url self.parameters = parameters self.ca_params = ca_params - self.payment_Address = '' + self.payment_Address = "" def get_address(self): + """ + Generate a new payment address for receiving cryptocurrency. + + This method creates a new payment address that forwards funds to your wallet, + and sets up the callback notification. + + Returns: + dict: Response from the CryptAPI service containing the generated address + and other payment information. + + Raises: + CryptAPIException: If the API returns an error. + """ coin = self.coin - if self.parameters: - req = PreparedRequest() - req.prepare_url(self.callback_url, self.parameters) - self.callback_url = req.url + callback_url = self._prepare_callback_url() - params = { - 'address': self.own_address, - 'callback': self.callback_url, - **self.parameters, **self.ca_params} + params = {"address": self.own_address, "callback": callback_url} - _address = CryptAPIHelper.process_request(coin, endpoint='create', params=params) - if _address: - self.payment_Address = _address['address_in'] - return _address + if self.ca_params: + params.update(self.ca_params) + + response_obj = CryptAPIHelper.process_request( + coin, endpoint="create", params=params + ) - return None + if "address_in" in response_obj: + self.payment_Address = response_obj["address_in"] + + return response_obj def get_logs(self): + """ + Retrieve logs for the callback URL. + + This method fetches the payment logs associated with the current callback URL. + + Returns: + dict: Response from the CryptAPI service containing the callback logs. + + Raises: + CryptAPIException: If the API returns an error. + """ coin = self.coin - callback_url = self.callback_url - if self.parameters: - req = PreparedRequest() - req.prepare_url(self.callback_url, self.parameters) - self.callback_url = req.url + callback_url = self._prepare_callback_url() + + params = {"callback": callback_url} + + return CryptAPIHelper.process_request(coin, endpoint="logs", params=params) + + def get_qrcode(self, value="", size=300): + """ + Generate a QR code for the payment address. - params = { - 'callback': callback_url - } + Args: + value (str, optional): The amount to pay. Defaults to '' (empty string). + size (int, optional): Size of the QR code in pixels. Defaults to 300. - return CryptAPIHelper.process_request(coin, endpoint='logs', params=params) + Returns: + dict: Response from the CryptAPI service containing the QR code data. - def get_qrcode(self, value='', size=300): - params = { - 'address': self.payment_Address, - 'size': size - } + Raises: + CryptAPIException: If the API returns an error. + """ + params = {"address": self.payment_Address, "size": size} if value: - params['value'] = value + params["value"] = value - return CryptAPIHelper.process_request(self.coin, endpoint='qrcode', params=params) + return CryptAPIHelper.process_request( + self.coin, endpoint="qrcode", params=params + ) def get_conversion(self, from_coin, value): - params = { - 'from': from_coin, - 'value': value - } + """ + Get conversion rates between currencies. + + Args: + from_coin (str): Source currency code (e.g., 'usd', 'eur'). + value (float): Amount to convert. + + Returns: + dict: Response from the CryptAPI service containing conversion information. + + Raises: + CryptAPIException: If the API returns an error. + """ + params = {"from": from_coin, "value": value} - return CryptAPIHelper.process_request(self.coin, endpoint='convert', params=params) + return CryptAPIHelper.process_request( + self.coin, endpoint="convert", params=params + ) @staticmethod - def get_info(coin=''): - return CryptAPIHelper.process_request(coin, endpoint='info') + def get_info(coin=""): + """ + Get information about a specific coin or all supported coins. + + Args: + coin (str, optional): Coin ticker. If empty, returns info for all coins. Defaults to ''. + + Returns: + dict: Response from the CryptAPI service containing coin information. + + Raises: + CryptAPIException: If the API returns an error. + """ + return CryptAPIHelper.process_request(coin, endpoint="info") @staticmethod def get_supported_coins(): - _info = CryptAPIHelper.get_info('') + """ + Get a list of all supported cryptocurrencies. - _info.pop('fee_tiers', None) + Returns: + dict: Dictionary of supported coins with tickers as keys and names as values. - _coins = {} + Raises: + CryptAPIException: If the API returns an error. + """ + _info = CryptAPIHelper.get_info("") + return process_supported_coins(_info) - for ticker, coin_info in _info.items(): + @staticmethod + def get_estimate(coin, addresses=1, priority="default"): + """ + Get an estimate of the network fees. - if 'coin' in coin_info.keys(): - _coins[ticker] = coin_info['coin'] - else: - for token, token_info in coin_info.items(): - _coins[ticker + '_' + token] = token_info['coin'] + ' (' + ticker.upper() + ')' + Args: + coin (str): Coin ticker. + addresses (int, optional): Number of addresses. Defaults to 1. + priority (str, optional): Transaction priority ('default', 'fast', 'fastest'). Defaults to 'default'. - return _coins + Returns: + dict: Response from the CryptAPI service containing fee estimates. - @staticmethod - def get_estimate(coin, addresses=1, priority='default'): - params = { - 'addresses': addresses, - 'priority': priority - } + Raises: + CryptAPIException: If the API returns an error. + """ + params = {"addresses": addresses, "priority": priority} + + return CryptAPIHelper.process_request(coin, endpoint="estimate", params=params) + + def _prepare_callback_url(self): + """ + Process the callback URL by adding user parameters. - return CryptAPIHelper.process_request(coin, endpoint='estimate', params=params) + This method appends the user parameters to the callback URL as query parameters. + The callback URL is also URL encoded to ensure it's properly handled by the API. + + Returns: + str: The processed and URL encoded callback URL with parameters. + """ + return prepare_url(self.callback_url, self.parameters) @staticmethod - def process_request(coin=None, endpoint='', params=None): + def process_request(coin=None, endpoint="", params=None): + """ + Process an API request to the CryptAPI service. + + Args: + coin (str, optional): Coin ticker. Defaults to None. + endpoint (str, optional): API endpoint. Defaults to ''. + params (dict, optional): Request parameters. Defaults to None. + + Returns: + dict: JSON response from the API. + + Raises: + CryptAPIException: If the API returns an error. + """ if coin: - coin += '/' + coin += "/" else: - coin = '' + coin = "" response = requests.get( url="{base_url}{coin}{endpoint}/".format( base_url=CryptAPIHelper.CRYPTAPI_URL, - coin=coin.replace('_', '/'), + coin=coin.replace("_", "/"), endpoint=endpoint, ), params=params, - headers={'Host': CryptAPIHelper.CRYPTAPI_HOST}, + headers={"Host": CryptAPIHelper.CRYPTAPI_HOST}, ) response_obj = response.json() - if response_obj.get('status') == 'error': - raise CryptAPIException(response_obj['error']) + if response_obj.get("status") == "error": + raise CryptAPIException(response_obj["error"]) return response_obj diff --git a/cryptapi/__init__.py b/cryptapi/__init__.py index f40b51f..78e8441 100644 --- a/cryptapi/__init__.py +++ b/cryptapi/__init__.py @@ -1 +1,11 @@ -from .CryptAPI import CryptAPIHelper +from .CryptAPI import CryptAPIHelper, CryptAPIException +from .AsyncCryptAPI import AsyncCryptAPIHelper +from .utils import prepare_url, process_supported_coins + +__all__ = [ + "CryptAPIHelper", + "AsyncCryptAPIHelper", + "CryptAPIException", + "prepare_url", + "process_supported_coins", +] diff --git a/cryptapi/utils.py b/cryptapi/utils.py new file mode 100644 index 0000000..52d5b65 --- /dev/null +++ b/cryptapi/utils.py @@ -0,0 +1,60 @@ +""" +CryptAPI's Python Helper Utilities + +This module provides common utility functions used by both synchronous and asynchronous +CryptAPI helpers. +""" + +import urllib.parse + + +def prepare_url(url, params=None): + """ + Helper method to append parameters to a URL and encode it. + + This method builds a properly formatted URL with query parameters. + The URL is also URL encoded to ensure it's properly handled by the API. + + Args: + url (str): Base URL to append parameters to. + params (dict, optional): Dictionary of parameters to append. Defaults to None. + + Returns: + str: URL encoded URL with parameters appended. + """ + result_url = url + + if params: + separator = "&" if "?" in url else "?" + query_params = "&".join(f"{k}={v}" for k, v in params.items()) + result_url = f"{url}{separator}{query_params}" + + return urllib.parse.quote(result_url, safe=":/?=&") + + +def process_supported_coins(info_response): + """ + Process the API response to extract supported cryptocurrencies. + + Args: + info_response (dict): Response from the get_info API call. + + Returns: + dict: Dictionary of supported coins with tickers as keys and names as values. + """ + info = info_response.copy() + + info.pop("fee_tiers", None) + + coins = {} + + for ticker, coin_info in info.items(): + if "coin" in coin_info.keys(): + coins[ticker] = coin_info["coin"] + else: + for token, token_info in coin_info.items(): + coins[ticker + "_" + token] = ( + token_info["coin"] + " (" + ticker.upper() + ")" + ) + + return coins diff --git a/requirements.txt b/requirements.txt index 6f89372..089e6fe 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1 +1,3 @@ -requests>=2.32.0 \ No newline at end of file +requests>=2.32.0 +aiohttp>=3.9.1 +certifi>=2024.2.2 \ No newline at end of file diff --git a/setup.py b/setup.py index 66df14e..752bf07 100644 --- a/setup.py +++ b/setup.py @@ -1,32 +1,20 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - from setuptools import setup, find_packages with open("README.md", "r") as fh: long_description = fh.read() setup( - - name='python-cryptapi', - - version='1.0.6', - + name="python-cryptapi", + version="1.1.3", packages=find_packages(), - author="CryptAPI", - author_email="info@cryptapi.io", - install_requires=[ - 'requests' - ], - description="Python Library for CryptAPI payment gateway", + install_requires=["requests", "aiohttp", "certifi"], + description="Python Library for CryptAPI payment gateway with async support, URL encoding for callbacks, and improved modular code structure", long_description_content_type="text/markdown", long_description=long_description, - include_package_data=True, - - url='https://github.com/cryptapi/python-cryptapi', + url="https://github.com/cryptapi/python-cryptapi", classifiers=[ "Programming Language :: Python", "Development Status :: 5 - Production/Stable", @@ -37,8 +25,6 @@ "Operating System :: OS Independent", "Programming Language :: Python :: 3", ], - license="MIT", - zip_safe=False, ) diff --git a/test.py b/test.py index f5eb0dd..be25489 100644 --- a/test.py +++ b/test.py @@ -1,54 +1,84 @@ from cryptapi import CryptAPIHelper ca = CryptAPIHelper( - 'bep20_usdt', - '0xA6B78B56ee062185E405a1DDDD18cE8fcBC4395d', - 'https://webhook.site/13308bd5-d20b-4d19-8597-bd9be7db36fe', - { - 'order_id': '1345e13232' - }, - { - 'convert': 1, - 'multi_token': 1 - } + "bep20_usdt", + "0xA6B78B56ee062185E405a1DDDD18cE8fcBC4395d", + "https://webhook.site/13308bd5-d20b-4d19-8597-bd9be7db36fe", + {"order_id": "1345e13232"}, + {"convert": 1, "multi_token": 1}, ) -""" -Get CA Address -""" -print('get_address:') -address = ca.get_address()['address_in'] -print(address) - -""" -Get coin information -""" -print('get_info:') -print(CryptAPIHelper.get_info('btc')) - -""" -Get all supported coins -""" -print('get_supported_coins:') -print(CryptAPIHelper.get_supported_coins()) - -""" -Get Logs -""" -print('get_logs') -print(ca.get_logs()) - -""" -Get QR Code -""" -print(ca.get_qrcode()['qr_code']) - -""" -Get Conversion -""" -print(ca.get_conversion('eur', 100)) - -""" -Get Estimate -""" -print(ca.get_estimate('ltc')) +print("====== Testing CryptAPI Synchronous Methods ======") + +try: + """ + Get CA Address + """ + print("\n[Test] get_address:") + address = ca.get_address()["address_in"] + print(f"Obtained address: {address}") +except Exception as e: + print(f"Error: {str(e)}") + +try: + """ + Get coin information + """ + print("\n[Test] get_info:") + info = CryptAPIHelper.get_info("btc") + print(f"Obtained information: Success") +except Exception as e: + print(f"Error: {str(e)}") + +try: + """ + Get all supported coins + """ + print("\n[Test] get_supported_coins:") + coins = CryptAPIHelper.get_supported_coins() + print(f"Number of supported coins: {len(coins)}") +except Exception as e: + print(f"Error: {str(e)}") + +try: + """ + Get Logs + """ + print("\n[Test] get_logs:") + + # Get logs + logs = ca.get_logs() + print(f"Retrieved logs: {logs.get('status', 'unknown')}") + print(f"Number of callback records: {len(logs.get('callbacks', []))}") +except Exception as e: + print(f"Error: {str(e)}") + +try: + """ + Get QR Code + """ + print("\n[Test] get_qrcode:") + qr = ca.get_qrcode() + print(f"Retrieved QR code: {'success' if 'qr_code' in qr else 'failed'}") +except Exception as e: + print(f"Error: {str(e)}") + +try: + """ + Get Conversion + """ + print("\n[Test] get_conversion:") + conv = ca.get_conversion("eur", 100) + print(f"Retrieved exchange rate: {conv.get('exchange_rate', 'unknown')}") +except Exception as e: + print(f"Error: {str(e)}") + +try: + """ + Get Estimate + """ + print("\n[Test] get_estimate:") + est = CryptAPIHelper.get_estimate("btc", "eth", 0.01) + print(f"Retrieved estimate: {est}") +except Exception as e: + print(f"Error: {str(e)}") From 2340db81a694807ff72db3798515c916b2be3188 Mon Sep 17 00:00:00 2001 From: SychO Date: Sat, 1 Mar 2025 15:48:50 +0800 Subject: [PATCH 2/5] Remove safe characters from URL encoding in utils.py --- cryptapi/utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cryptapi/utils.py b/cryptapi/utils.py index 52d5b65..939f7ad 100644 --- a/cryptapi/utils.py +++ b/cryptapi/utils.py @@ -29,7 +29,7 @@ def prepare_url(url, params=None): query_params = "&".join(f"{k}={v}" for k, v in params.items()) result_url = f"{url}{separator}{query_params}" - return urllib.parse.quote(result_url, safe=":/?=&") + return urllib.parse.quote(result_url, safe="") def process_supported_coins(info_response): From 54e6ff2fa3ce4185c158490df69fc16506a3b4d4 Mon Sep 17 00:00:00 2001 From: SychO Date: Sat, 1 Mar 2025 16:18:15 +0800 Subject: [PATCH 3/5] Refactor CryptAPI to remove URL preparation utility and handle callback URLs directly --- async_test.py | 9 +++---- cryptapi/AsyncCryptAPI.py | 51 ++++++++++++++++++++++++++++++--------- cryptapi/CryptAPI.py | 34 +++++++++++++++++--------- cryptapi/__init__.py | 6 ++--- cryptapi/utils.py | 50 ++++++-------------------------------- 5 files changed, 77 insertions(+), 73 deletions(-) diff --git a/async_test.py b/async_test.py index 1c2c160..911b8a2 100644 --- a/async_test.py +++ b/async_test.py @@ -37,11 +37,10 @@ async def run_tests(): print("Creating AsyncCryptAPIHelper instance...") # Initialize AsyncCryptAPIHelper instance ca = AsyncCryptAPIHelper( - "bep20_usdt", - "0xA6B78B56ee062185E405a1DDDD18cE8fcBC4395d", - "https://webhook.site/13308bd5-d20b-4d19-8597-bd9be7db36fe", - {"order_id": "1345e13232"}, - {"convert": 1, "multi_token": 1}, + "trc20/usdt", + "TKUWuYXiP2khFp46miao7ARweccccccccc", + "https://cryptapi.515111.xyz/callback", + {"user_id": "5323355513", "order_id": "86c1f46e2bdc"}, ) print("Instance created, starting method tests...") diff --git a/cryptapi/AsyncCryptAPI.py b/cryptapi/AsyncCryptAPI.py index d4659b1..96520f7 100644 --- a/cryptapi/AsyncCryptAPI.py +++ b/cryptapi/AsyncCryptAPI.py @@ -12,16 +12,9 @@ import aiohttp import ssl import certifi -from .utils import prepare_url, process_supported_coins - -class CryptAPIException(Exception): - """ - Exception raised for CryptAPI-specific errors. - Used when the API returns an error response. - """ - - pass +from .exceptions import CryptAPIException +from .utils import process_supported_coins class AsyncCryptAPIHelper: @@ -107,7 +100,15 @@ async def get_address(self): """ coin = self.coin - callback_url = prepare_url(self.callback_url, self.parameters) + # 使用requests.PreparedRequest来处理URL,而不是调用_prepare_callback_url + callback_url = self.callback_url + + if self.parameters: + from requests.models import PreparedRequest + + req = PreparedRequest() + req.prepare_url(self.callback_url, self.parameters) + callback_url = req.url params = {"address": self.own_address, "callback": callback_url} @@ -134,12 +135,40 @@ async def get_logs(self): CryptAPIException: If the API returns an error. """ coin = self.coin - callback_url = prepare_url(self.callback_url, self.parameters) + + # 使用requests.PreparedRequest来处理URL,而不是完全编码 + callback_url = self.callback_url + + if self.parameters: + from requests.models import PreparedRequest + + req = PreparedRequest() + req.prepare_url(self.callback_url, self.parameters) + callback_url = req.url params = {"callback": callback_url} return await self.process_request(coin, endpoint="logs", params=params) + def _prepare_callback_url(self): + """ + Process the callback URL by adding user parameters. + + This method appends the user parameters to the callback URL as query parameters. + The callback URL is also URL encoded to ensure it's properly handled by the API. + + Returns: + str: The processed and URL encoded callback URL with parameters. + """ + if not self.parameters: + return self.callback_url + + from requests.models import PreparedRequest + + req = PreparedRequest() + req.prepare_url(self.callback_url, self.parameters) + return req.url + async def get_qrcode(self, value="", size=300): """ Asynchronously generate a QR code for the payment address. diff --git a/cryptapi/CryptAPI.py b/cryptapi/CryptAPI.py index 7f310a2..1382697 100644 --- a/cryptapi/CryptAPI.py +++ b/cryptapi/CryptAPI.py @@ -9,16 +9,9 @@ """ import requests -from .utils import prepare_url, process_supported_coins - -class CryptAPIException(Exception): - """ - Exception raised for CryptAPI-specific errors. - Used when the API returns an error response. - """ - - pass +from .exceptions import CryptAPIException +from .utils import process_supported_coins class CryptAPIHelper: @@ -98,7 +91,13 @@ def get_address(self): """ coin = self.coin - callback_url = self._prepare_callback_url() + # 使用requests.PreparedRequest来处理URL,而不是调用_prepare_callback_url + callback_url = self.callback_url + + if self.parameters: + req = requests.models.PreparedRequest() + req.prepare_url(self.callback_url, self.parameters) + callback_url = req.url params = {"address": self.own_address, "callback": callback_url} @@ -128,7 +127,13 @@ def get_logs(self): """ coin = self.coin - callback_url = self._prepare_callback_url() + # 使用requests.PreparedRequest来处理URL,而不是完全编码 + callback_url = self.callback_url + + if self.parameters: + req = requests.models.PreparedRequest() + req.prepare_url(self.callback_url, self.parameters) + callback_url = req.url params = {"callback": callback_url} @@ -237,7 +242,12 @@ def _prepare_callback_url(self): Returns: str: The processed and URL encoded callback URL with parameters. """ - return prepare_url(self.callback_url, self.parameters) + if not self.parameters: + return self.callback_url + + req = requests.models.PreparedRequest() + req.prepare_url(self.callback_url, self.parameters) + return req.url @staticmethod def process_request(coin=None, endpoint="", params=None): diff --git a/cryptapi/__init__.py b/cryptapi/__init__.py index 78e8441..f66492c 100644 --- a/cryptapi/__init__.py +++ b/cryptapi/__init__.py @@ -1,11 +1,11 @@ -from .CryptAPI import CryptAPIHelper, CryptAPIException +from .CryptAPI import CryptAPIHelper from .AsyncCryptAPI import AsyncCryptAPIHelper -from .utils import prepare_url, process_supported_coins +from .exceptions import CryptAPIException +from .utils import process_supported_coins __all__ = [ "CryptAPIHelper", "AsyncCryptAPIHelper", "CryptAPIException", - "prepare_url", "process_supported_coins", ] diff --git a/cryptapi/utils.py b/cryptapi/utils.py index 939f7ad..7e01ed4 100644 --- a/cryptapi/utils.py +++ b/cryptapi/utils.py @@ -5,56 +5,22 @@ CryptAPI helpers. """ -import urllib.parse - - -def prepare_url(url, params=None): - """ - Helper method to append parameters to a URL and encode it. - - This method builds a properly formatted URL with query parameters. - The URL is also URL encoded to ensure it's properly handled by the API. - - Args: - url (str): Base URL to append parameters to. - params (dict, optional): Dictionary of parameters to append. Defaults to None. - - Returns: - str: URL encoded URL with parameters appended. - """ - result_url = url - - if params: - separator = "&" if "?" in url else "?" - query_params = "&".join(f"{k}={v}" for k, v in params.items()) - result_url = f"{url}{separator}{query_params}" - - return urllib.parse.quote(result_url, safe="") - def process_supported_coins(info_response): """ Process the API response to extract supported cryptocurrencies. Args: - info_response (dict): Response from the get_info API call. + info_response (dict): Response from the CryptAPI info endpoint. Returns: - dict: Dictionary of supported coins with tickers as keys and names as values. + dict: Dictionary with coin tickers as keys and names as values. """ - info = info_response.copy() - - info.pop("fee_tiers", None) - - coins = {} + result = {} + coins = info_response.get("coins", []) - for ticker, coin_info in info.items(): - if "coin" in coin_info.keys(): - coins[ticker] = coin_info["coin"] - else: - for token, token_info in coin_info.items(): - coins[ticker + "_" + token] = ( - token_info["coin"] + " (" + ticker.upper() + ")" - ) + for coin_type, coin_info in coins.items(): + for coin, details in coin_info.items(): + result[f"{coin_type}_{coin}"] = details.get("name", "") - return coins + return result From 0b196ac918c3082cc57529d277d15c5223464170 Mon Sep 17 00:00:00 2001 From: SychO Date: Sat, 1 Mar 2025 16:21:18 +0800 Subject: [PATCH 4/5] Add synchronous and asynchronous tests for CryptAPIHelper and AsyncCryptAPIHelper --- cryptapi/exceptions.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 cryptapi/exceptions.py diff --git a/cryptapi/exceptions.py b/cryptapi/exceptions.py new file mode 100644 index 0000000..d19fd3d --- /dev/null +++ b/cryptapi/exceptions.py @@ -0,0 +1,14 @@ +""" +CryptAPI's Python Helper Exceptions + +This module provides exception classes for CryptAPI Python helper. +""" + + +class CryptAPIException(Exception): + """ + Exception raised for CryptAPI-specific errors. + Used when the API returns an error response. + """ + + pass From a59022bcb84528f250ccbc60555283623a432602 Mon Sep 17 00:00:00 2001 From: SychO Date: Sat, 1 Mar 2025 16:34:18 +0800 Subject: [PATCH 5/5] Refactor coin handling in AsyncCryptAPI and CryptAPI to improve URL formatting and update utils.py for better coin extraction --- cryptapi/AsyncCryptAPI.py | 4 +++- cryptapi/CryptAPI.py | 4 +++- cryptapi/utils.py | 18 ++++++++++++------ 3 files changed, 18 insertions(+), 8 deletions(-) diff --git a/cryptapi/AsyncCryptAPI.py b/cryptapi/AsyncCryptAPI.py index 96520f7..9647111 100644 --- a/cryptapi/AsyncCryptAPI.py +++ b/cryptapi/AsyncCryptAPI.py @@ -277,13 +277,15 @@ async def process_request(coin=None, endpoint="", params=None): CryptAPIException: If the API returns an error. """ if coin: + if "/" not in coin: + coin = coin.replace("_", "/") coin += "/" else: coin = "" url = "{base_url}{coin}{endpoint}/".format( base_url=AsyncCryptAPIHelper.CRYPTAPI_URL, - coin=coin.replace("_", "/"), + coin=coin, endpoint=endpoint, ) diff --git a/cryptapi/CryptAPI.py b/cryptapi/CryptAPI.py index 1382697..0834f07 100644 --- a/cryptapi/CryptAPI.py +++ b/cryptapi/CryptAPI.py @@ -266,6 +266,8 @@ def process_request(coin=None, endpoint="", params=None): CryptAPIException: If the API returns an error. """ if coin: + if "/" not in coin: + coin = coin.replace("_", "/") coin += "/" else: coin = "" @@ -273,7 +275,7 @@ def process_request(coin=None, endpoint="", params=None): response = requests.get( url="{base_url}{coin}{endpoint}/".format( base_url=CryptAPIHelper.CRYPTAPI_URL, - coin=coin.replace("_", "/"), + coin=coin, endpoint=endpoint, ), params=params, diff --git a/cryptapi/utils.py b/cryptapi/utils.py index 7e01ed4..f613f2d 100644 --- a/cryptapi/utils.py +++ b/cryptapi/utils.py @@ -17,10 +17,16 @@ def process_supported_coins(info_response): dict: Dictionary with coin tickers as keys and names as values. """ result = {} - coins = info_response.get("coins", []) - - for coin_type, coin_info in coins.items(): - for coin, details in coin_info.items(): - result[f"{coin_type}_{coin}"] = details.get("name", "") - + + for coin_ticker, coin_info in info_response.items(): + if isinstance(coin_info, dict) and "coin" in coin_info: + result[coin_ticker] = coin_info.get("coin", "") + + if "tokens" in info_response and isinstance(info_response["tokens"], dict): + for chain, tokens in info_response["tokens"].items(): + if isinstance(tokens, dict): + for token_ticker, token_info in tokens.items(): + key = f"{chain}/{token_ticker}" + result[key] = token_info.get("coin", "") + return result