Metadata-Version: 2.4
Name: inventpay
Version: 1.0.0
Summary: Official Python SDK for InventPay - Accept crypto payments with ease
Home-page: https://docs.inventpay.io
Author: InventPay
Author-email: support@inventpay.io
Project-URL: Documentation, https://docs.inventpay.io
Keywords: inventpay,cryptocurrency,payments,bitcoin,ethereum,crypto,sdk
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.7
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: requests>=2.25.0
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: keywords
Dynamic: license-file
Dynamic: project-url
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

```markdown
# 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](https://inventpay.io/dashboard).

### 2. Initialize the SDK

```python
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)
```python
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)
```python
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

```python
# 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

```python
# 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

```python
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**
```python
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**
```python
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**
```python
# 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

```python
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

```python
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

```python
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

```python
# 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

```python
# 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

```python
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

- **Documentation:** [https://docs.inventpay.io](https://docs.inventpay.io)
- **Dashboard:** [https://inventpay.io/dashboard](https://inventpay.io/dashboard)  
- **Email Support:** support@inventpay.io
- **GitHub Issues:** [Report bugs & features](https://github.com/inventpay/inventpay-python-sdk/issues)

## License

MIT License - see [LICENSE](LICENSE) for details.

---

**Ready to start?** [Get your API key](https://inventpay.io/dashboard) 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.
