Skip to main content

Official Python SDK for InventPay - Accept crypto payments with ease

Project description

# InventPay Python SDK

The official Python SDK for [InventPay](https://inventpay.io) - accept cryptocurrency payments in your Python applications with just a few lines of code.

## Features

- 💳 Accept Bitcoin, Ethereum, Litecoin, USDT payments
- 🔄 Create withdrawals to any wallet address  
- 💰 Check balances and transaction history
- 🔔 Webhook support for real-time notifications
- 🐍 Pythonic API with full type hints
- ⚡ Lightweight with minimal dependencies

## Installation

```bash
pip install inventpay

Quick Start

1. Get Your API Key

First, get your API key from the InventPay Dashboard.

2. Initialize the SDK

from inventpay import PaymentSDK, SDKConfig

# Initialize with your API key
sdk = PaymentSDK(
    SDKConfig(api_key="your-api-key-here")
)

# Test the connection
result = sdk.test_connection()
print(result['message'])  # "API connection successful"

3. Create Your First Payment

Option A: Direct Payment (specific cryptocurrency)

from inventpay import PaymentRequest

# Create a direct payment
payment = sdk.create_payment(
    PaymentRequest(
        amount=29.99,
        currency="USDT_BEP20",  # or "BTC", "ETH", "LTC", "USDT_ERC20"
        order_id="order-12345",
        description="Premium Plan"
    )
)

print(f"Payment ID: {payment.data['paymentId']}")
print(f"Amount: {payment.data['amount']} {payment.data['currency']}")
print(f"Address: {payment.data['address']}")
print(f"Invoice URL: {payment.data['invoiceUrl']}")

Option B: Multi-Currency Invoice (customer chooses)

from inventpay import InvoiceRequest

# Create an invoice (customer chooses currency)
invoice = sdk.create_invoice(
    InvoiceRequest(
        amount=49.99,
        order_id="order-67890", 
        description="E-commerce Purchase"
    )
)

print(f"Invoice URL: {invoice.data['invoiceUrl']}")
print(f"Available currencies: {list(invoice.data['conversionRates'].keys())}")

4. Check Payment Status

# Check any payment status (no API key needed)
status = sdk.get_payment_status("your-payment-id-here")

print(f"Status: {status.status}")  # PENDING, COMPLETED, EXPIRED, FAILED
print(f"Current Balance: {status.current_balance}")
print(f"Confirmations: {status.confirmations}")

Core Features

Managing Balances

# Get all balances
balances = sdk.get_balances()
for currency, info in balances.data['balances'].items():
    print(f"{currency}: {info['availableBalance']} available")

# Get specific currency balance  
usdt_balance = sdk.get_balance("USDT_BEP20")
print(f"USDT Balance: {usdt_balance.data['balance']['availableBalance']}")

Creating Withdrawals

from inventpay import WithdrawalRequest

withdrawal = sdk.create_withdrawal(
    WithdrawalRequest(
        amount=10.0,
        currency="USDT_BEP20",
        destination_address="0x1E3D6848dE165e64052f0F2A3dA8823A27CAc22D",
        description="Monthly payout"
    )
)

print(f"Withdrawal ID: {withdrawal.data['withdrawalId']}")
print(f"Status: {withdrawal.data['status']}")  # PENDING, PROCESSING, COMPLETED

Webhook Handling

Configure Webhooks

from inventpay import WebhookConfig

# Set your webhook URL
sdk.configure_webhook(
    WebhookConfig(webhook_url="https://yourapp.com/webhooks/inventpay")
)

# Test webhook delivery
test_result = sdk.test_webhook()
print(test_result['message'])  # "Webhook test successful"

Flask Webhook Handler

from flask import Flask, request, jsonify
from inventpay import verify_webhook_signature

app = Flask(__name__)
WEBHOOK_SECRET = "your-webhook-secret-from-dashboard"

@app.route('/webhooks/inventpay', methods=['POST'])
def handle_webhook():
    signature = request.headers.get('X-Webhook-Signature')
    payload = request.get_json()
    
    # Verify the webhook signature
    if not verify_webhook_signature(payload, signature, WEBHOOK_SECRET):
        return jsonify({'error': 'Invalid signature'}), 401
    
    # Handle different event types
    event_type = payload.get('event')
    data = payload.get('data', {})
    
    if event_type == 'payment.completed':
        print(f"Payment completed: {data['paymentId']}")
        # Update your database, send email, etc.
    elif event_type == 'payment.failed':
        print(f"Payment failed: {data['paymentId']}")
        # Handle failed payment
    
    return jsonify({'received': True})

if __name__ == '__main__':
    app.run(port=3000)

Django Webhook Handler

# views.py
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from inventpay import verify_webhook_signature
import json

@csrf_exempt
def inventpay_webhook(request):
    if request.method == 'POST':
        signature = request.headers.get('X-Webhook-Signature')
        payload = json.loads(request.body)
        
        if not verify_webhook_signature(payload, signature, "your-secret"):
            return JsonResponse({'error': 'Invalid signature'}, status=401)
        
        # Process webhook event
        event_type = payload.get('event')
        if event_type == 'payment.completed':
            # Handle completed payment
            pass
            
        return JsonResponse({'received': True})
    
    return JsonResponse({'error': 'Method not allowed'}, status=405)

Error Handling

from inventpay import PaymentSDKError, AuthenticationError, ValidationError

try:
    payment = sdk.create_payment(PaymentRequest(amount=25, currency="USDT_BEP20"))
    
except AuthenticationError as e:
    print(f"Invalid API key: {e.message}")
except ValidationError as e:
    print(f"Invalid request: {e.message} - {e.details}")
except PaymentSDKError as e:
    print(f"API error: {e.message} (Status: {e.status_code})")
except Exception as e:
    print(f"Unexpected error: {e}")

API Reference

Payment Methods

Method Description
create_payment() Create direct payment for specific cryptocurrency
create_invoice() Create multi-currency invoice
get_payment_status() Check payment status

Balance Methods

Method Description
get_balances() Get all currency balances
get_balance(currency) Get specific currency balance

Withdrawal Methods

Method Description
create_withdrawal() Create withdrawal to external wallet
get_withdrawal() Check withdrawal status

Webhook Methods

Method Description
configure_webhook() Set webhook URL
get_webhook_config() Get webhook configuration
get_webhook_deliveries() Get delivery history
test_webhook() Test webhook endpoint

Configuration

SDK Options

config = SDKConfig(
    api_key="your-api-key",           # Required
    base_url="https://api.inventpay.io",  # Optional
    timeout=30                        # Optional (seconds)
)

Supported Currencies

Payment Currencies:

  • BTC (Bitcoin)
  • ETH (Ethereum)
  • LTC (Litecoin)
  • USDT_ERC20 (USDT on Ethereum)
  • USDT_BEP20 (USDT on BSC)
  • MULTI (Multi-currency invoice)

Amount Currencies:

  • USD (US Dollars)
  • USDT (Tether)
  • BTC, ETH, LTC

Best Practices

1. Store API Keys Securely

import os
from inventpay import PaymentSDK, SDKConfig

sdk = PaymentSDK(SDKConfig(api_key=os.getenv('INVENTPAY_API_KEY')))

2. Handle Webhooks Properly

  • Always verify webhook signatures
  • Return 200 OK even if processing fails (to prevent retries)
  • Log all webhook events for debugging

3. Monitor Payment Status

# For critical payments, poll status until confirmed
payment_id = "your-payment-id"
max_attempts = 10

for attempt in range(max_attempts):
    status = sdk.get_payment_status(payment_id)
    if status.status == 'COMPLETED':
        print("Payment confirmed!")
        break
    elif status.status in ['EXPIRED', 'FAILED']:
        print("Payment failed")
        break
    else:
        time.sleep(30)  # Wait 30 seconds before checking again

Examples

Django E-commerce Integration

# views.py
from django.shortcuts import render
from django.http import JsonResponse
from inventpay import PaymentSDK, SDKConfig, PaymentRequest

def create_payment_view(request):
    if request.method == 'POST':
        sdk = PaymentSDK(SDKConfig(api_key=settings.INVENTPAY_API_KEY))
        
        try:
            payment = sdk.create_payment(
                PaymentRequest(
                    amount=request.POST['amount'],
                    currency="USDT_BEP20",
                    order_id=f"order-{request.user.id}-{int(time.time())}",
                    description=request.POST['description']
                )
            )
            
            return JsonResponse({
                'success': True,
                'payment_id': payment.data['paymentId'],
                'invoice_url': payment.data['invoiceUrl']
            })
            
        except Exception as e:
            return JsonResponse({'success': False, 'error': str(e)})
    
    return render(request, 'payment.html')

FastAPI Integration

from fastapi import FastAPI, HTTPException
from inventpay import PaymentSDK, SDKConfig, PaymentRequest

app = FastAPI()
sdk = PaymentSDK(SDKConfig(api_key="your-api-key"))

@app.post("/create-payment")
async def create_payment(amount: float, description: str):
    try:
        payment = sdk.create_payment(
            PaymentRequest(
                amount=amount,
                currency="USDT_BEP20",
                description=description
            )
        )
        return payment.data
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))

Support

License

MIT License - see LICENSE for details.


Ready to start? Get your API key and begin accepting crypto payments in minutes! 🚀


This README provides:

- **Quick start** with minimal code to get running
- **Clear examples** for all major features
- **Framework integrations** (Flask, Django, FastAPI)
- **Error handling** guidance
- **Best practices** for production use
- **Simple copy-paste** code snippets
- **Visual structure** with emojis and clear sections

It's designed to help users get started quickly while still providing comprehensive coverage of all SDK features.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

inventpay-1.0.0.tar.gz (13.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

inventpay-1.0.0-py3-none-any.whl (11.0 kB view details)

Uploaded Python 3

File details

Details for the file inventpay-1.0.0.tar.gz.

File metadata

  • Download URL: inventpay-1.0.0.tar.gz
  • Upload date:
  • Size: 13.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for inventpay-1.0.0.tar.gz
Algorithm Hash digest
SHA256 2a7e828ffa69ac3fb9c62dce3ca0bde984b9f52f8a72f29a2c199eb133701709
MD5 3205bf92979c01fe3b33d7525063a1fb
BLAKE2b-256 851e2a0510d1c65a6e82402a5ac0d33a48c7e0b02979e91b56de369d04410fa0

See more details on using hashes here.

File details

Details for the file inventpay-1.0.0-py3-none-any.whl.

File metadata

  • Download URL: inventpay-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 11.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for inventpay-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 b6959b53c773b17e4814fa4099a2196492d51251ec4b29781b2b2e821aac4fd4
MD5 9723be6d5d6224628c4f3ebb3dd67b75
BLAKE2b-256 210e49f6565d21db866e6db5e6b5652fd9f205d82c6ba6c3d28098caa493a2c0

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page