Authentication overview

CryptAPI provides a payment gateway solution for accepting various cryptocurrencies. Secure communication between your application and the CryptAPI platform is established primarily through API keys. These keys serve as credentials to authenticate your requests, ensuring that only authorized applications can initiate transactions or query data. Beyond simple request authentication, CryptAPI also emphasizes the validation of incoming callbacks using a secret key and HMAC-SHA512 hashing to guarantee the authenticity and integrity of payment notifications sent from CryptAPI to your system CryptAPI callback documentation.

The authentication process is designed to be straightforward for developers, integrating seamlessly with webhooks and direct API calls. CryptAPI's approach requires developers to actively manage and protect their API keys and secret keys, adhering to general API security best practices to prevent unauthorized access and potential vulnerabilities.

Supported authentication methods

CryptAPI primarily utilizes API keys for authenticating requests. This method involves including a unique key with each API call, which CryptAPI then uses to identify and authorize the calling application. For enhanced security, especially with incoming payment notifications (callbacks), CryptAPI implements a signature-based verification mechanism using a secret key and HMAC-SHA512 hashing. This ensures that callback data has not been tampered with and originates from CryptAPI.

Method When to Use Security Level
API Key (Query Parameter) For all outgoing API requests from your application to CryptAPI. Moderate – Identifies the calling application. Requires secure storage and transmission.
HMAC-SHA512 Signature (Callback Validation) For verifying the authenticity and integrity of incoming payment callbacks from CryptAPI to your application. High – Ensures data integrity and origin authenticity. Crucial for fraud prevention.

The API key is typically passed as a query parameter in HTTP GET requests or as part of the request body for POST requests. The HMAC-SHA512 signature, conversely, is sent in HTTP headers (or as part of the request body, depending on configuration) with callbacks and must be re-calculated and compared on your server using a shared secret key. This dual approach provides both client-side authentication for outgoing requests and server-side verification for incoming notifications, creating a robust security posture for transaction processing CryptAPI API reference.

Getting your credentials

To begin integrating with CryptAPI, you first need to obtain your API key and secret key from the CryptAPI dashboard. These credentials are fundamental for authenticating your application and securing your transactions.

  1. Sign Up/Log In: Navigate to the CryptAPI homepage and either create a new account or log in to your existing one.
  2. Access Dashboard: Once logged in, proceed to your CryptAPI dashboard.
  3. Locate API Settings: Within the dashboard, look for a section related to API settings, integrations, or developer tools. The exact path may vary slightly but is typically clearly labeled.
  4. Generate/Retrieve Keys: You will find your main API key listed here. For callback validation, a separate secret key (sometimes referred to as a "signature secret" or "callback secret") will also be available or can be generated. Ensure you note both securely.
  5. Configure Callbacks (Optional but Recommended): If you plan to receive payment notifications, configure your callback URL within the dashboard settings. This tells CryptAPI where to send transaction updates, which you will then verify using your secret key.

It's important to treat these keys as sensitive information. CryptAPI's documentation advises against hardcoding them directly into your application's source code and recommends using environment variables or a secure configuration management system instead. If you suspect your keys have been compromised, you should revoke them immediately and generate new ones through the CryptAPI dashboard.

Authenticated request example

Authenticating requests with CryptAPI involves including your API key in the request URL. For callback validation, you'll perform a server-side check using the provided signature and your secret key. Here's an example of how to request a new payment address using the CryptAPI API, and then how to validate an incoming callback in Python.

Requesting a Payment Address (Python)

This example demonstrates making a GET request to CryptAPI's create endpoint to generate a new payment address for a Bitcoin transaction, including the API key.


import requests

API_KEY = "YOUR_CRYPTAPI_API_KEY"
COIN = "btc" # e.g., btc, eth, ltc, etc.
CALLBACK_URL = "https://your-domain.com/cryptapi-callback"
ADDRESS = "YOUR_OWN_WALLET_ADDRESS" # Your wallet to receive funds

url = f"https://api.cryptapi.io/{COIN}/create/?callback={CALLBACK_URL}&address={ADDRESS}&apikey={API_KEY}"

try:
    response = requests.get(url)
    response.raise_for_status() # Raise an exception for HTTP errors
    data = response.json()
    print("Payment address created successfully:")
    print(f"Address: {data['address']}")
    print(f"QR Code: {data['qr_code']}")
except requests.exceptions.RequestException as e:
    print(f"Error making API request: {e}")
    if response is not None:
        print(f"Response content: {response.text}")

Validating a Callback (Python - Flask Example)

This example shows how to receive a callback from CryptAPI and validate its signature using HMAC-SHA512. This is crucial for security.


import hmac
import hashlib
import json
from flask import Flask, request, abort

app = Flask(__name__)

# Your CryptAPI Secret Key - MUST be stored securely (e.g., environment variable)
CRYPTAPI_SECRET = "YOUR_CRYPTAPI_SECRET_KEY"

@app.route('/cryptapi-callback', methods=['GET', 'POST'])
def cryptapi_callback():
    # CryptAPI typically sends callbacks as GET requests with parameters
    # or POST requests with form data/JSON.
    # For GET, parameters are in request.args.
    # For POST, check request.form or request.get_json().

    # Assuming GET request for callback, as per CryptAPI docs common practice
    params = request.args.to_dict() if request.method == 'GET' else request.form.to_dict()
    
    # Extract signature from parameters. CryptAPI usually sends it as 'signature'.
    received_signature = params.pop('signature', None)
    if not received_signature:
        print("Error: No signature received in callback.")
        abort(400) # Bad Request

    # Sort parameters alphabetically by key and concatenate values
    # This is critical for HMAC calculation to match CryptAPI's process.
    # Exclude the signature itself from the string to be signed.
    sorted_params_string = ''
    for key in sorted(params.keys()):
        sorted_params_string += str(params[key])

    # Calculate expected HMAC signature
    expected_signature = hmac.new(
        CRYPTAPI_SECRET.encode('utf-8'),
        sorted_params_string.encode('utf-8'),
        hashlib.sha512
    ).hexdigest()

    # Compare signatures
    if hmac.compare_digest(received_signature, expected_signature):
        print("Callback signature validated successfully!")
        # Process the payment details (e.g., update database)
        print(f"Received payment for: {params.get('value_coin')} {params.get('coin')}")
        # Return 200 OK to acknowledge receipt of the callback
        return "OK", 200
    else:
        print("Error: Invalid callback signature.")
        print(f"Received: {received_signature}")
        print(f"Expected: {expected_signature}")
        abort(403) # Forbidden

if __name__ == '__main__':
    # For development only. In production, use a WSGI server like Gunicorn/uWSGI.
    app.run(debug=True, port=5000)

This Flask example demonstrates a basic server that listens for CryptAPI callbacks. The critical part is the hmac.new calculation, where the CRYPTAPI_SECRET is used to hash a concatenated string of sorted callback parameters, which is then compared against the received_signature from CryptAPI. This process ensures the callback's authenticity.

Security best practices

Adhering to security best practices is paramount when integrating any payment gateway, especially one dealing with cryptocurrencies. For CryptAPI, focusing on key management and callback validation strengthens your application's security posture.

  • Secure Key Storage: Never hardcode your API keys or secret keys directly into your source code. Instead, utilize environment variables, secret management services (e.g., Google Cloud Secret Manager, AWS Secrets Manager), or secure configuration files that are not committed to version control. This prevents accidental exposure of credentials.

  • Restrict API Key Permissions: While CryptAPI API keys often have broad permissions, understand the scope of actions your key enables. If CryptAPI introduces more granular permission controls in the future, apply the principle of least privilege.

  • Validate All Callbacks: Implement robust server-side validation for every callback received from CryptAPI using the HMAC-SHA512 signature. This is the most critical step to prevent fraudulent transactions or state manipulation by ensuring the callback originates from CryptAPI and its data hasn't been tampered with. Do not process any payment notification unless its signature is successfully verified.

  • Use HTTPS for All Communications: Ensure all communication between your application and CryptAPI, including callbacks, occurs over HTTPS. This encrypts data in transit, protecting against eavesdropping and man-in-the-middle attacks. CryptAPI by default uses HTTPS for its API endpoints CryptAPI documentation.

  • Implement Rate Limiting and Monitoring: Monitor your API usage for unusual activity. Implement rate limiting on your callback endpoint to prevent denial-of-service attacks. Set up alerts for failed signature validations or unexpected callback patterns.

  • Regular Key Rotation: Periodically rotate your API and secret keys. This reduces the window of opportunity for a compromised key to be exploited. CryptAPI's dashboard should provide functionality for revoking old keys and generating new ones.

  • Error Handling and Logging: Implement comprehensive error handling for API calls and callback processing. Log relevant information (excluding sensitive data) to assist with debugging and security audits, but avoid logging raw API keys or secret keys.

  • Input Validation: Always validate and sanitize any data received from callbacks or user input before processing it to prevent injection attacks and other vulnerabilities.