stacks-pay-python


Namestacks-pay-python JSON
Version 1.0.0 PyPI version JSON
download
home_pageNone
SummaryOfficial Python SDK for StacksPay - Accept Bitcoin and STX payments
upload_time2025-09-04 15:54:35
maintainerNone
docs_urlNone
authorNone
requires_python>=3.8
licenseMIT
keywords bitcoin stacks sbtc payments crypto gateway api sdk
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # sBTC Gateway Python SDK

[![PyPI version](https://badge.fury.io/py/sbtc-gateway.svg)](https://badge.fury.io/py/sbtc-gateway)
[![Python CI](https://github.com/TheSoftNode/sbtc-payment-gateway/workflows/Python%20CI/badge.svg)](https://github.com/TheSoftNode/sbtc-payment-gateway/actions)

Official Python SDK for the sBTC Payment Gateway. Accept Bitcoin and STX payments with ease.

## Features

✅ **Payment Management**: Create, retrieve, list, cancel, and refund payments  
✅ **Merchant API**: Get and update merchant information  
✅ **Webhook Management**: Create and manage webhooks for real-time notifications  
✅ **API Key Management**: Generate and manage API keys  
✅ **Webhook Utils**: Verify webhook signatures securely  
✅ **Error Handling**: Comprehensive error types and handling  
✅ **Type Hints**: Full type hint support for better IDE experience  
✅ **Async Support**: Compatible with async/await patterns  
✅ **Automatic Retries**: Built-in retry logic with exponential backoff  
✅ **Rate Limiting**: Automatic handling of rate limits

## Installation

```bash
pip install sbtc-gateway
```

## Quick Start

```python
import sbtc_gateway

# Initialize the client
client = sbtc_gateway.SBTCGateway('sk_test_your_api_key_here')

# Create a payment
payment = client.payments.create(sbtc_gateway.PaymentRequest(
    amount=50000,  # 0.0005 BTC in satoshis
    currency='sbtc',
    description='Premium subscription',
    customer=sbtc_gateway.Customer(
        email='customer@example.com',
        name='John Doe'
    )
))

print(payment.payment_url)  # Send this URL to your customer
print(payment.qr_code)      # Or show this QR code
```

## API Reference

### Payments

#### Create a Payment

```python
from sbtc_gateway import PaymentRequest, Customer

payment = client.payments.create(PaymentRequest(
    amount=50000,
    currency='sbtc',
    description='Premium subscription',
    customer=Customer(
        email='customer@example.com',
        name='John Doe'
    ),
    webhook_url='https://yoursite.com/webhook',
    redirect_url='https://yoursite.com/success',
    expires_in=3600,  # 1 hour
    metadata={
        'order_id': 'order_123',
        'user_id': '456'
    }
))
```

#### Retrieve a Payment

```python
payment = client.payments.retrieve('payment_id')
```

#### List Payments

```python
result = client.payments.list(
    page=1,
    limit=10,
    status='completed',
    customer_email='customer@example.com'
)

payments = result['payments']
pagination = result['pagination']
```

#### Cancel a Payment

```python
payment = client.payments.cancel('payment_id')
```

#### Refund a Payment

```python
# Full refund
refund = client.payments.refund('payment_id')

# Partial refund
refund = client.payments.refund('payment_id', amount=25000)
```

### Webhooks

#### Create a Webhook

```python
from sbtc_gateway import WebhookRequest

webhook = client.webhooks.create(WebhookRequest(
    url='https://yoursite.com/webhook',
    events=['payment.completed', 'payment.failed'],
    description='Main webhook endpoint'
))
```

#### List Webhooks

```python
result = client.webhooks.list(page=1, limit=10)
webhooks = result['webhooks']
pagination = result['pagination']
```

#### Update a Webhook

```python
webhook = client.webhooks.update('webhook_id', {
    'url': 'https://newsite.com/webhook',
    'events': ['payment.completed']
})
```

#### Delete a Webhook

```python
client.webhooks.delete('webhook_id')
```

#### Test a Webhook

```python
result = client.webhooks.test('webhook_id')
```

#### Get Webhook Statistics

```python
stats = client.webhooks.get_stats('webhook_id')
```

### API Keys

#### Generate an API Key

```python
from sbtc_gateway import APIKeyRequest

result = client.api_keys.generate(APIKeyRequest(
    name='Production API Key',
    permissions=['payments:read', 'payments:write'],
    expires_at='2024-12-31T23:59:59Z'
))

api_key = result['api_key']
key = result['key']  # Save this key securely - it won't be shown again
```

#### List API Keys

```python
result = client.api_keys.list(
    page=1,
    limit=10,
    status='active'
)

api_keys = result['api_keys']
pagination = result['pagination']
```

#### Update an API Key

```python
api_key = client.api_keys.update('key_id', {
    'name': 'Updated Key Name',
    'permissions': ['payments:read']
})
```

#### Deactivate an API Key

```python
api_key = client.api_keys.deactivate('key_id')
```

#### Get API Key Usage

```python
usage = client.api_keys.get_usage('key_id')
```

### Merchant

#### Get Current Merchant

```python
merchant = client.merchant.get_current()
```

#### Update Merchant Information

```python
merchant = client.merchant.update({
    'name': 'Updated Business Name',
    'business_type': 'e-commerce',
    'website': 'https://mybusiness.com',
    'stacks_address': 'SP2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKNRV9EJ7',
    'bitcoin_address': '1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa'
})
```

### Webhook Verification

```python
from sbtc_gateway import WebhookUtils
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/webhook', methods=['POST'])
def webhook_handler():
    signature = request.headers.get('X-Signature')
    payload = request.get_data(as_text=True)
    secret = 'your_webhook_secret'

    try:
        # Verify the webhook signature
        is_valid = WebhookUtils.verify_signature(payload, signature, secret)

        if not is_valid:
            return jsonify({'error': 'Invalid signature'}), 400

        # Parse the event
        event = WebhookUtils.parse_event(payload)

        # Handle the event
        if event.type == 'payment.completed':
            print(f'Payment completed: {event.data.payment.id}')
        elif event.type == 'payment.failed':
            print(f'Payment failed: {event.data.payment.id}')

        return jsonify({'status': 'success'}), 200

    except Exception as e:
        print(f'Webhook error: {e}')
        return jsonify({'error': 'Error processing webhook'}), 400
```

## Error Handling

```python
from sbtc_gateway import SBTCGateway, SBTCGatewayError, APIError, AuthenticationError

client = SBTCGateway('sk_test_key')

try:
    payment = client.payments.create(payment_data)
except AuthenticationError as e:
    print(f'Authentication failed: {e.message}')
except APIError as e:
    print(f'API Error: {e.message}')
    print(f'Error Code: {e.code}')
    print(f'Details: {e.details}')
except SBTCGatewayError as e:
    print(f'SDK Error: {e.message}')
except Exception as e:
    print(f'Unexpected error: {e}')
```

## Configuration

### Custom Base URL (for testing)

```python
client = SBTCGateway(
    'sk_test_key',
    base_url='https://api.staging.sbtc-gateway.com',
    timeout=60,  # 60 seconds
    retries=5
)
```

### Environment Variables

```bash
export SBTC_GATEWAY_API_KEY=sk_live_your_api_key_here
export SBTC_GATEWAY_BASE_URL=https://api.sbtc-gateway.com
```

```python
import os
from sbtc_gateway import SBTCGateway

client = SBTCGateway(
    os.environ['SBTC_GATEWAY_API_KEY'],
    base_url=os.environ.get('SBTC_GATEWAY_BASE_URL')
)
```

## Django Integration

```python
# settings.py
SBTC_GATEWAY_API_KEY = 'sk_live_your_api_key_here'

# views.py
from django.conf import settings
from sbtc_gateway import SBTCGateway

client = SBTCGateway(settings.SBTC_GATEWAY_API_KEY)

def create_payment(request):
    payment = client.payments.create({
        'amount': 50000,
        'currency': 'sbtc',
        'description': 'Django payment'
    })
    return JsonResponse({'payment_url': payment.payment_url})
```

## FastAPI Integration

```python
from fastapi import FastAPI
from sbtc_gateway import SBTCGateway, PaymentRequest

app = FastAPI()
client = SBTCGateway('sk_test_key')

@app.post("/create-payment")
async def create_payment(payment_data: PaymentRequest):
    payment = client.payments.create(payment_data)
    return {"payment_url": payment.payment_url}
```

## Testing

```bash
# Install development dependencies
pip install -e ".[dev]"

# Run tests
pytest

# Run tests with coverage
pytest --cov=sbtc_gateway
```

## Type Safety

This SDK includes comprehensive type hints for better IDE support:

```python
from sbtc_gateway import (
    SBTCGateway,
    Payment,
    PaymentRequest,
    Webhook,
    APIKey
)

client: SBTCGateway = SBTCGateway('sk_test_key')

# Type-safe payment creation
payment_data: PaymentRequest = PaymentRequest(
    amount=50000,
    currency='sbtc',
    description='Test payment'
)

payment: Payment = client.payments.create(payment_data)
```

## Examples

See the [examples directory](./examples) for complete examples:

- [Basic Payment Flow](./examples/basic_payment.py)
- [Django Integration](./examples/django_example.py)
- [FastAPI Integration](./examples/fastapi_example.py)
- [Webhook Handler](./examples/webhook_handler.py)

## API Compatibility

This SDK is compatible with sBTC Gateway API v1. All endpoints and features are supported:

- **Base URL**: `https://api.sbtc-gateway.com`
- **Authentication**: Bearer token (API key)
- **Format**: JSON REST API
- **Rate Limits**: Automatic handling with retries

## Support

- **Documentation**: [https://docs.sbtc-gateway.com](https://docs.sbtc-gateway.com)
- **Issues**: [GitHub Issues](https://github.com/TheSoftNode/sbtc-payment-gateway/issues)
- **Support**: support@sbtc-gateway.com

## Contributing

1. Fork the repository
2. Create a feature branch: `git checkout -b feature-name`
3. Make your changes and add tests
4. Ensure tests pass: `pytest`
5. Create a pull request

## License

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

---

Made with ❤️ by the sBTC Gateway team

Official Python SDK for the sBTC Payment Gateway. Accept Bitcoin and STX payments with ease.

## Installation

```bash
pip install sbtc-gateway
```

## Quick Start

```python
import sbtc_gateway

# Initialize the client
client = sbtc_gateway.SBTCGateway('sk_live_your_api_key_here')

# Create a payment
payment = client.payments.create(sbtc_gateway.PaymentRequest(
    amount=50000,  # 50,000 satoshis
    currency='sbtc',
    description='Premium subscription',
    customer=sbtc_gateway.Customer(
        email='customer@example.com',
        name='John Doe'
    )
))

print(f"Payment URL: {payment.payment_url}")
```

## API Reference

### Initialize Client

```python
import sbtc_gateway

client = sbtc_gateway.SBTCGateway(
    api_key='sk_live_your_api_key_here',
    base_url='https://api.sbtc-gateway.com',  # optional
    timeout=30,  # optional, seconds
    retries=3   # optional, retry attempts
)
```

### Payments API

#### Create Payment

```python
from sbtc_gateway import PaymentRequest, Customer

payment = client.payments.create(PaymentRequest(
    amount=50000,  # Amount in satoshis
    currency='sbtc',  # 'sbtc', 'btc', or 'stx'
    description='Payment description',
    customer=Customer(
        email='customer@example.com',
        name='John Doe'
    ),
    metadata={
        'order_id': 'order_12345',
        'user_id': 'user_67890'
    },
    webhook_url='https://yourapp.com/webhooks/payment',
    redirect_url='https://yourapp.com/success'
))
```

#### Retrieve Payment

```python
payment = client.payments.retrieve('pay_1234567890')
```

#### List Payments

```python
result = client.payments.list(
    page=1,
    limit=20,
    status='completed',
    customer_email='customer@example.com'
)

payments = result.payments
pagination = result.pagination
```

#### Cancel Payment

```python
payment = client.payments.cancel('pay_1234567890')
```

### Merchant API

#### Get Current Merchant

```python
merchant = client.merchant.get_current()
```

#### Update Merchant

```python
merchant = client.merchant.update(
    name='New Business Name',
    website='https://newwebsite.com'
)
```

### Webhook Utilities

#### Verify Webhook Signature

```python
from flask import Flask, request
import sbtc_gateway

app = Flask(__name__)

@app.route('/webhooks/sbtc', methods=['POST'])
def handle_webhook():
    signature = request.headers.get('X-SBTC-Signature')
    payload = request.get_data(as_text=True)
    secret = 'your_webhook_secret'

    try:
        event = sbtc_gateway.WebhookUtils.verify_and_parse_event(
            payload, signature, secret
        )

        if event.type == 'payment.completed':
            print(f'Payment completed: {event.data.payment.id}')
        elif event.type == 'payment.failed':
            print(f'Payment failed: {event.data.payment.id}')

        return 'OK', 200
    except sbtc_gateway.ValidationError as e:
        print(f'Webhook verification failed: {e}')
        return 'Invalid signature', 400
```

## Error Handling

```python
import sbtc_gateway

try:
    payment = client.payments.create(sbtc_gateway.PaymentRequest(
        amount=50000,
        currency='sbtc',
        description='Test payment'
    ))
except sbtc_gateway.AuthenticationError as e:
    print(f'Authentication error: {e.message}')
except sbtc_gateway.ValidationError as e:
    print(f'Validation error: {e.message}')
except sbtc_gateway.APIError as e:
    print(f'API error: {e.message}')
    print(f'Error code: {e.code}')
    print(f'Details: {e.details}')
except sbtc_gateway.NetworkError as e:
    print(f'Network error: {e.message}')
```

## Webhooks

Handle real-time payment updates:

```python
from flask import Flask, request
import sbtc_gateway

app = Flask(__name__)

@app.route('/webhooks/sbtc', methods=['POST'])
def handle_webhook():
    signature = request.headers.get('X-SBTC-Signature')
    payload = request.get_data(as_text=True)

    try:
        event = sbtc_gateway.WebhookUtils.verify_and_parse_event(
            payload,
            signature,
            'your_webhook_secret'
        )

        if event.type == 'payment.created':
            # Payment initiated
            pass
        elif event.type == 'payment.paid':
            # Payment received (but not confirmed)
            pass
        elif event.type == 'payment.completed':
            # Payment confirmed and completed
            fulfill_order(event.data.payment)
        elif event.type == 'payment.failed':
            # Payment failed
            notify_customer(event.data.payment)
        elif event.type == 'payment.expired':
            # Payment expired
            cleanup_order(event.data.payment)

        return {'status': 'success'}, 200

    except sbtc_gateway.ValidationError:
        return {'error': 'Invalid signature'}, 400

def fulfill_order(payment):
    print(f'Fulfilling order for payment: {payment.id}')

def notify_customer(payment):
    print(f'Notifying customer about failed payment: {payment.id}')

def cleanup_order(payment):
    print(f'Cleaning up expired payment: {payment.id}')
```

## Testing

Use test API keys for development:

```python
# Test API key (starts with sk_test_)
client = sbtc_gateway.SBTCGateway('sk_test_your_test_key_here')

# All payments will use Bitcoin testnet and Stacks testnet
payment = client.payments.create(sbtc_gateway.PaymentRequest(
    amount=10000,  # 0.0001 BTC
    currency='sbtc',
    description='Test payment'
))
```

## Environment Variables

Create a `.env` file:

```bash
# Production
SBTC_API_KEY=sk_live_your_live_key_here
SBTC_WEBHOOK_SECRET=whsec_your_webhook_secret

# Development
SBTC_API_KEY=sk_test_your_test_key_here
SBTC_WEBHOOK_SECRET=whsec_your_test_webhook_secret
```

Use with python-dotenv:

```python
import os
from dotenv import load_dotenv
import sbtc_gateway

load_dotenv()

client = sbtc_gateway.SBTCGateway(os.getenv('SBTC_API_KEY'))
```

## Django Integration

```python
# settings.py
SBTC_API_KEY = os.getenv('SBTC_API_KEY')
SBTC_WEBHOOK_SECRET = os.getenv('SBTC_WEBHOOK_SECRET')

# views.py
from django.conf import settings
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
import sbtc_gateway

client = sbtc_gateway.SBTCGateway(settings.SBTC_API_KEY)

@csrf_exempt
@require_http_methods(["POST"])
def webhook_handler(request):
    signature = request.META.get('HTTP_X_SBTC_SIGNATURE')
    payload = request.body.decode('utf-8')

    try:
        event = sbtc_gateway.WebhookUtils.verify_and_parse_event(
            payload, signature, settings.SBTC_WEBHOOK_SECRET
        )

        # Handle the event
        handle_payment_event(event)

        return JsonResponse({'status': 'success'})
    except sbtc_gateway.ValidationError:
        return JsonResponse({'error': 'Invalid signature'}, status=400)
```

## FastAPI Integration

```python
from fastapi import FastAPI, HTTPException, Header, Request
import sbtc_gateway

app = FastAPI()
client = sbtc_gateway.SBTCGateway('sk_live_your_api_key_here')

@app.post("/webhooks/sbtc")
async def webhook_handler(
    request: Request,
    x_sbtc_signature: str = Header(None)
):
    payload = await request.body()

    try:
        event = sbtc_gateway.WebhookUtils.verify_and_parse_event(
            payload.decode('utf-8'),
            x_sbtc_signature,
            'your_webhook_secret'
        )

        # Handle the event
        await handle_payment_event(event)

        return {"status": "success"}
    except sbtc_gateway.ValidationError:
        raise HTTPException(status_code=400, detail="Invalid signature")
```

## Support

- **Documentation**: https://docs.sbtc-gateway.com
- **API Reference**: https://docs.sbtc-gateway.com/api
- **GitHub Issues**: https://github.com/TheSoftNode/sbtc-payment-gateway/issues
- **Email Support**: developers@sbtc-gateway.com

## License

MIT License. See [LICENSE](LICENSE) for details.

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "stacks-pay-python",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": "StacksPay Team <developers@stackspay.com>",
    "keywords": "bitcoin, stacks, sbtc, payments, crypto, gateway, api, sdk",
    "author": null,
    "author_email": "StacksPay Team <developers@stackspay.com>",
    "download_url": "https://files.pythonhosted.org/packages/78/5a/c651aa4ae9ecab3da1ddd0bbd28ace3626e26a782faac18f6850aaaa3504/stacks_pay_python-1.0.0.tar.gz",
    "platform": null,
    "description": "# sBTC Gateway Python SDK\n\n[![PyPI version](https://badge.fury.io/py/sbtc-gateway.svg)](https://badge.fury.io/py/sbtc-gateway)\n[![Python CI](https://github.com/TheSoftNode/sbtc-payment-gateway/workflows/Python%20CI/badge.svg)](https://github.com/TheSoftNode/sbtc-payment-gateway/actions)\n\nOfficial Python SDK for the sBTC Payment Gateway. Accept Bitcoin and STX payments with ease.\n\n## Features\n\n\u2705 **Payment Management**: Create, retrieve, list, cancel, and refund payments  \n\u2705 **Merchant API**: Get and update merchant information  \n\u2705 **Webhook Management**: Create and manage webhooks for real-time notifications  \n\u2705 **API Key Management**: Generate and manage API keys  \n\u2705 **Webhook Utils**: Verify webhook signatures securely  \n\u2705 **Error Handling**: Comprehensive error types and handling  \n\u2705 **Type Hints**: Full type hint support for better IDE experience  \n\u2705 **Async Support**: Compatible with async/await patterns  \n\u2705 **Automatic Retries**: Built-in retry logic with exponential backoff  \n\u2705 **Rate Limiting**: Automatic handling of rate limits\n\n## Installation\n\n```bash\npip install sbtc-gateway\n```\n\n## Quick Start\n\n```python\nimport sbtc_gateway\n\n# Initialize the client\nclient = sbtc_gateway.SBTCGateway('sk_test_your_api_key_here')\n\n# Create a payment\npayment = client.payments.create(sbtc_gateway.PaymentRequest(\n    amount=50000,  # 0.0005 BTC in satoshis\n    currency='sbtc',\n    description='Premium subscription',\n    customer=sbtc_gateway.Customer(\n        email='customer@example.com',\n        name='John Doe'\n    )\n))\n\nprint(payment.payment_url)  # Send this URL to your customer\nprint(payment.qr_code)      # Or show this QR code\n```\n\n## API Reference\n\n### Payments\n\n#### Create a Payment\n\n```python\nfrom sbtc_gateway import PaymentRequest, Customer\n\npayment = client.payments.create(PaymentRequest(\n    amount=50000,\n    currency='sbtc',\n    description='Premium subscription',\n    customer=Customer(\n        email='customer@example.com',\n        name='John Doe'\n    ),\n    webhook_url='https://yoursite.com/webhook',\n    redirect_url='https://yoursite.com/success',\n    expires_in=3600,  # 1 hour\n    metadata={\n        'order_id': 'order_123',\n        'user_id': '456'\n    }\n))\n```\n\n#### Retrieve a Payment\n\n```python\npayment = client.payments.retrieve('payment_id')\n```\n\n#### List Payments\n\n```python\nresult = client.payments.list(\n    page=1,\n    limit=10,\n    status='completed',\n    customer_email='customer@example.com'\n)\n\npayments = result['payments']\npagination = result['pagination']\n```\n\n#### Cancel a Payment\n\n```python\npayment = client.payments.cancel('payment_id')\n```\n\n#### Refund a Payment\n\n```python\n# Full refund\nrefund = client.payments.refund('payment_id')\n\n# Partial refund\nrefund = client.payments.refund('payment_id', amount=25000)\n```\n\n### Webhooks\n\n#### Create a Webhook\n\n```python\nfrom sbtc_gateway import WebhookRequest\n\nwebhook = client.webhooks.create(WebhookRequest(\n    url='https://yoursite.com/webhook',\n    events=['payment.completed', 'payment.failed'],\n    description='Main webhook endpoint'\n))\n```\n\n#### List Webhooks\n\n```python\nresult = client.webhooks.list(page=1, limit=10)\nwebhooks = result['webhooks']\npagination = result['pagination']\n```\n\n#### Update a Webhook\n\n```python\nwebhook = client.webhooks.update('webhook_id', {\n    'url': 'https://newsite.com/webhook',\n    'events': ['payment.completed']\n})\n```\n\n#### Delete a Webhook\n\n```python\nclient.webhooks.delete('webhook_id')\n```\n\n#### Test a Webhook\n\n```python\nresult = client.webhooks.test('webhook_id')\n```\n\n#### Get Webhook Statistics\n\n```python\nstats = client.webhooks.get_stats('webhook_id')\n```\n\n### API Keys\n\n#### Generate an API Key\n\n```python\nfrom sbtc_gateway import APIKeyRequest\n\nresult = client.api_keys.generate(APIKeyRequest(\n    name='Production API Key',\n    permissions=['payments:read', 'payments:write'],\n    expires_at='2024-12-31T23:59:59Z'\n))\n\napi_key = result['api_key']\nkey = result['key']  # Save this key securely - it won't be shown again\n```\n\n#### List API Keys\n\n```python\nresult = client.api_keys.list(\n    page=1,\n    limit=10,\n    status='active'\n)\n\napi_keys = result['api_keys']\npagination = result['pagination']\n```\n\n#### Update an API Key\n\n```python\napi_key = client.api_keys.update('key_id', {\n    'name': 'Updated Key Name',\n    'permissions': ['payments:read']\n})\n```\n\n#### Deactivate an API Key\n\n```python\napi_key = client.api_keys.deactivate('key_id')\n```\n\n#### Get API Key Usage\n\n```python\nusage = client.api_keys.get_usage('key_id')\n```\n\n### Merchant\n\n#### Get Current Merchant\n\n```python\nmerchant = client.merchant.get_current()\n```\n\n#### Update Merchant Information\n\n```python\nmerchant = client.merchant.update({\n    'name': 'Updated Business Name',\n    'business_type': 'e-commerce',\n    'website': 'https://mybusiness.com',\n    'stacks_address': 'SP2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKNRV9EJ7',\n    'bitcoin_address': '1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa'\n})\n```\n\n### Webhook Verification\n\n```python\nfrom sbtc_gateway import WebhookUtils\nfrom flask import Flask, request, jsonify\n\napp = Flask(__name__)\n\n@app.route('/webhook', methods=['POST'])\ndef webhook_handler():\n    signature = request.headers.get('X-Signature')\n    payload = request.get_data(as_text=True)\n    secret = 'your_webhook_secret'\n\n    try:\n        # Verify the webhook signature\n        is_valid = WebhookUtils.verify_signature(payload, signature, secret)\n\n        if not is_valid:\n            return jsonify({'error': 'Invalid signature'}), 400\n\n        # Parse the event\n        event = WebhookUtils.parse_event(payload)\n\n        # Handle the event\n        if event.type == 'payment.completed':\n            print(f'Payment completed: {event.data.payment.id}')\n        elif event.type == 'payment.failed':\n            print(f'Payment failed: {event.data.payment.id}')\n\n        return jsonify({'status': 'success'}), 200\n\n    except Exception as e:\n        print(f'Webhook error: {e}')\n        return jsonify({'error': 'Error processing webhook'}), 400\n```\n\n## Error Handling\n\n```python\nfrom sbtc_gateway import SBTCGateway, SBTCGatewayError, APIError, AuthenticationError\n\nclient = SBTCGateway('sk_test_key')\n\ntry:\n    payment = client.payments.create(payment_data)\nexcept AuthenticationError as e:\n    print(f'Authentication failed: {e.message}')\nexcept APIError as e:\n    print(f'API Error: {e.message}')\n    print(f'Error Code: {e.code}')\n    print(f'Details: {e.details}')\nexcept SBTCGatewayError as e:\n    print(f'SDK Error: {e.message}')\nexcept Exception as e:\n    print(f'Unexpected error: {e}')\n```\n\n## Configuration\n\n### Custom Base URL (for testing)\n\n```python\nclient = SBTCGateway(\n    'sk_test_key',\n    base_url='https://api.staging.sbtc-gateway.com',\n    timeout=60,  # 60 seconds\n    retries=5\n)\n```\n\n### Environment Variables\n\n```bash\nexport SBTC_GATEWAY_API_KEY=sk_live_your_api_key_here\nexport SBTC_GATEWAY_BASE_URL=https://api.sbtc-gateway.com\n```\n\n```python\nimport os\nfrom sbtc_gateway import SBTCGateway\n\nclient = SBTCGateway(\n    os.environ['SBTC_GATEWAY_API_KEY'],\n    base_url=os.environ.get('SBTC_GATEWAY_BASE_URL')\n)\n```\n\n## Django Integration\n\n```python\n# settings.py\nSBTC_GATEWAY_API_KEY = 'sk_live_your_api_key_here'\n\n# views.py\nfrom django.conf import settings\nfrom sbtc_gateway import SBTCGateway\n\nclient = SBTCGateway(settings.SBTC_GATEWAY_API_KEY)\n\ndef create_payment(request):\n    payment = client.payments.create({\n        'amount': 50000,\n        'currency': 'sbtc',\n        'description': 'Django payment'\n    })\n    return JsonResponse({'payment_url': payment.payment_url})\n```\n\n## FastAPI Integration\n\n```python\nfrom fastapi import FastAPI\nfrom sbtc_gateway import SBTCGateway, PaymentRequest\n\napp = FastAPI()\nclient = SBTCGateway('sk_test_key')\n\n@app.post(\"/create-payment\")\nasync def create_payment(payment_data: PaymentRequest):\n    payment = client.payments.create(payment_data)\n    return {\"payment_url\": payment.payment_url}\n```\n\n## Testing\n\n```bash\n# Install development dependencies\npip install -e \".[dev]\"\n\n# Run tests\npytest\n\n# Run tests with coverage\npytest --cov=sbtc_gateway\n```\n\n## Type Safety\n\nThis SDK includes comprehensive type hints for better IDE support:\n\n```python\nfrom sbtc_gateway import (\n    SBTCGateway,\n    Payment,\n    PaymentRequest,\n    Webhook,\n    APIKey\n)\n\nclient: SBTCGateway = SBTCGateway('sk_test_key')\n\n# Type-safe payment creation\npayment_data: PaymentRequest = PaymentRequest(\n    amount=50000,\n    currency='sbtc',\n    description='Test payment'\n)\n\npayment: Payment = client.payments.create(payment_data)\n```\n\n## Examples\n\nSee the [examples directory](./examples) for complete examples:\n\n- [Basic Payment Flow](./examples/basic_payment.py)\n- [Django Integration](./examples/django_example.py)\n- [FastAPI Integration](./examples/fastapi_example.py)\n- [Webhook Handler](./examples/webhook_handler.py)\n\n## API Compatibility\n\nThis SDK is compatible with sBTC Gateway API v1. All endpoints and features are supported:\n\n- **Base URL**: `https://api.sbtc-gateway.com`\n- **Authentication**: Bearer token (API key)\n- **Format**: JSON REST API\n- **Rate Limits**: Automatic handling with retries\n\n## Support\n\n- **Documentation**: [https://docs.sbtc-gateway.com](https://docs.sbtc-gateway.com)\n- **Issues**: [GitHub Issues](https://github.com/TheSoftNode/sbtc-payment-gateway/issues)\n- **Support**: support@sbtc-gateway.com\n\n## Contributing\n\n1. Fork the repository\n2. Create a feature branch: `git checkout -b feature-name`\n3. Make your changes and add tests\n4. Ensure tests pass: `pytest`\n5. Create a pull request\n\n## License\n\nMIT License - see [LICENSE](./LICENSE) file for details.\n\n---\n\nMade with \u2764\ufe0f by the sBTC Gateway team\n\nOfficial Python SDK for the sBTC Payment Gateway. Accept Bitcoin and STX payments with ease.\n\n## Installation\n\n```bash\npip install sbtc-gateway\n```\n\n## Quick Start\n\n```python\nimport sbtc_gateway\n\n# Initialize the client\nclient = sbtc_gateway.SBTCGateway('sk_live_your_api_key_here')\n\n# Create a payment\npayment = client.payments.create(sbtc_gateway.PaymentRequest(\n    amount=50000,  # 50,000 satoshis\n    currency='sbtc',\n    description='Premium subscription',\n    customer=sbtc_gateway.Customer(\n        email='customer@example.com',\n        name='John Doe'\n    )\n))\n\nprint(f\"Payment URL: {payment.payment_url}\")\n```\n\n## API Reference\n\n### Initialize Client\n\n```python\nimport sbtc_gateway\n\nclient = sbtc_gateway.SBTCGateway(\n    api_key='sk_live_your_api_key_here',\n    base_url='https://api.sbtc-gateway.com',  # optional\n    timeout=30,  # optional, seconds\n    retries=3   # optional, retry attempts\n)\n```\n\n### Payments API\n\n#### Create Payment\n\n```python\nfrom sbtc_gateway import PaymentRequest, Customer\n\npayment = client.payments.create(PaymentRequest(\n    amount=50000,  # Amount in satoshis\n    currency='sbtc',  # 'sbtc', 'btc', or 'stx'\n    description='Payment description',\n    customer=Customer(\n        email='customer@example.com',\n        name='John Doe'\n    ),\n    metadata={\n        'order_id': 'order_12345',\n        'user_id': 'user_67890'\n    },\n    webhook_url='https://yourapp.com/webhooks/payment',\n    redirect_url='https://yourapp.com/success'\n))\n```\n\n#### Retrieve Payment\n\n```python\npayment = client.payments.retrieve('pay_1234567890')\n```\n\n#### List Payments\n\n```python\nresult = client.payments.list(\n    page=1,\n    limit=20,\n    status='completed',\n    customer_email='customer@example.com'\n)\n\npayments = result.payments\npagination = result.pagination\n```\n\n#### Cancel Payment\n\n```python\npayment = client.payments.cancel('pay_1234567890')\n```\n\n### Merchant API\n\n#### Get Current Merchant\n\n```python\nmerchant = client.merchant.get_current()\n```\n\n#### Update Merchant\n\n```python\nmerchant = client.merchant.update(\n    name='New Business Name',\n    website='https://newwebsite.com'\n)\n```\n\n### Webhook Utilities\n\n#### Verify Webhook Signature\n\n```python\nfrom flask import Flask, request\nimport sbtc_gateway\n\napp = Flask(__name__)\n\n@app.route('/webhooks/sbtc', methods=['POST'])\ndef handle_webhook():\n    signature = request.headers.get('X-SBTC-Signature')\n    payload = request.get_data(as_text=True)\n    secret = 'your_webhook_secret'\n\n    try:\n        event = sbtc_gateway.WebhookUtils.verify_and_parse_event(\n            payload, signature, secret\n        )\n\n        if event.type == 'payment.completed':\n            print(f'Payment completed: {event.data.payment.id}')\n        elif event.type == 'payment.failed':\n            print(f'Payment failed: {event.data.payment.id}')\n\n        return 'OK', 200\n    except sbtc_gateway.ValidationError as e:\n        print(f'Webhook verification failed: {e}')\n        return 'Invalid signature', 400\n```\n\n## Error Handling\n\n```python\nimport sbtc_gateway\n\ntry:\n    payment = client.payments.create(sbtc_gateway.PaymentRequest(\n        amount=50000,\n        currency='sbtc',\n        description='Test payment'\n    ))\nexcept sbtc_gateway.AuthenticationError as e:\n    print(f'Authentication error: {e.message}')\nexcept sbtc_gateway.ValidationError as e:\n    print(f'Validation error: {e.message}')\nexcept sbtc_gateway.APIError as e:\n    print(f'API error: {e.message}')\n    print(f'Error code: {e.code}')\n    print(f'Details: {e.details}')\nexcept sbtc_gateway.NetworkError as e:\n    print(f'Network error: {e.message}')\n```\n\n## Webhooks\n\nHandle real-time payment updates:\n\n```python\nfrom flask import Flask, request\nimport sbtc_gateway\n\napp = Flask(__name__)\n\n@app.route('/webhooks/sbtc', methods=['POST'])\ndef handle_webhook():\n    signature = request.headers.get('X-SBTC-Signature')\n    payload = request.get_data(as_text=True)\n\n    try:\n        event = sbtc_gateway.WebhookUtils.verify_and_parse_event(\n            payload,\n            signature,\n            'your_webhook_secret'\n        )\n\n        if event.type == 'payment.created':\n            # Payment initiated\n            pass\n        elif event.type == 'payment.paid':\n            # Payment received (but not confirmed)\n            pass\n        elif event.type == 'payment.completed':\n            # Payment confirmed and completed\n            fulfill_order(event.data.payment)\n        elif event.type == 'payment.failed':\n            # Payment failed\n            notify_customer(event.data.payment)\n        elif event.type == 'payment.expired':\n            # Payment expired\n            cleanup_order(event.data.payment)\n\n        return {'status': 'success'}, 200\n\n    except sbtc_gateway.ValidationError:\n        return {'error': 'Invalid signature'}, 400\n\ndef fulfill_order(payment):\n    print(f'Fulfilling order for payment: {payment.id}')\n\ndef notify_customer(payment):\n    print(f'Notifying customer about failed payment: {payment.id}')\n\ndef cleanup_order(payment):\n    print(f'Cleaning up expired payment: {payment.id}')\n```\n\n## Testing\n\nUse test API keys for development:\n\n```python\n# Test API key (starts with sk_test_)\nclient = sbtc_gateway.SBTCGateway('sk_test_your_test_key_here')\n\n# All payments will use Bitcoin testnet and Stacks testnet\npayment = client.payments.create(sbtc_gateway.PaymentRequest(\n    amount=10000,  # 0.0001 BTC\n    currency='sbtc',\n    description='Test payment'\n))\n```\n\n## Environment Variables\n\nCreate a `.env` file:\n\n```bash\n# Production\nSBTC_API_KEY=sk_live_your_live_key_here\nSBTC_WEBHOOK_SECRET=whsec_your_webhook_secret\n\n# Development\nSBTC_API_KEY=sk_test_your_test_key_here\nSBTC_WEBHOOK_SECRET=whsec_your_test_webhook_secret\n```\n\nUse with python-dotenv:\n\n```python\nimport os\nfrom dotenv import load_dotenv\nimport sbtc_gateway\n\nload_dotenv()\n\nclient = sbtc_gateway.SBTCGateway(os.getenv('SBTC_API_KEY'))\n```\n\n## Django Integration\n\n```python\n# settings.py\nSBTC_API_KEY = os.getenv('SBTC_API_KEY')\nSBTC_WEBHOOK_SECRET = os.getenv('SBTC_WEBHOOK_SECRET')\n\n# views.py\nfrom django.conf import settings\nfrom django.http import JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.views.decorators.http import require_http_methods\nimport sbtc_gateway\n\nclient = sbtc_gateway.SBTCGateway(settings.SBTC_API_KEY)\n\n@csrf_exempt\n@require_http_methods([\"POST\"])\ndef webhook_handler(request):\n    signature = request.META.get('HTTP_X_SBTC_SIGNATURE')\n    payload = request.body.decode('utf-8')\n\n    try:\n        event = sbtc_gateway.WebhookUtils.verify_and_parse_event(\n            payload, signature, settings.SBTC_WEBHOOK_SECRET\n        )\n\n        # Handle the event\n        handle_payment_event(event)\n\n        return JsonResponse({'status': 'success'})\n    except sbtc_gateway.ValidationError:\n        return JsonResponse({'error': 'Invalid signature'}, status=400)\n```\n\n## FastAPI Integration\n\n```python\nfrom fastapi import FastAPI, HTTPException, Header, Request\nimport sbtc_gateway\n\napp = FastAPI()\nclient = sbtc_gateway.SBTCGateway('sk_live_your_api_key_here')\n\n@app.post(\"/webhooks/sbtc\")\nasync def webhook_handler(\n    request: Request,\n    x_sbtc_signature: str = Header(None)\n):\n    payload = await request.body()\n\n    try:\n        event = sbtc_gateway.WebhookUtils.verify_and_parse_event(\n            payload.decode('utf-8'),\n            x_sbtc_signature,\n            'your_webhook_secret'\n        )\n\n        # Handle the event\n        await handle_payment_event(event)\n\n        return {\"status\": \"success\"}\n    except sbtc_gateway.ValidationError:\n        raise HTTPException(status_code=400, detail=\"Invalid signature\")\n```\n\n## Support\n\n- **Documentation**: https://docs.sbtc-gateway.com\n- **API Reference**: https://docs.sbtc-gateway.com/api\n- **GitHub Issues**: https://github.com/TheSoftNode/sbtc-payment-gateway/issues\n- **Email Support**: developers@sbtc-gateway.com\n\n## License\n\nMIT License. See [LICENSE](LICENSE) for details.\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Official Python SDK for StacksPay - Accept Bitcoin and STX payments",
    "version": "1.0.0",
    "project_urls": {
        "Documentation": "https://docs.stackspay.com",
        "Homepage": "https://stackspay.com",
        "Issues": "https://github.com/TheSoftNode/sbtc-payment-gateway/issues",
        "Repository": "https://github.com/TheSoftNode/sbtc-payment-gateway"
    },
    "split_keywords": [
        "bitcoin",
        " stacks",
        " sbtc",
        " payments",
        " crypto",
        " gateway",
        " api",
        " sdk"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "aa6aa536f2af647b18205b740fc5ec31c68d0a3f582de8975adc36041b090171",
                "md5": "a94c5043e1d82049c403b8d0d995b687",
                "sha256": "1ec760eba478d25aec1f3a55407ad4046908054d0cb2f68b8aee5f44e8669c3e"
            },
            "downloads": -1,
            "filename": "stacks_pay_python-1.0.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "a94c5043e1d82049c403b8d0d995b687",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 16211,
            "upload_time": "2025-09-04T15:54:34",
            "upload_time_iso_8601": "2025-09-04T15:54:34.241929Z",
            "url": "https://files.pythonhosted.org/packages/aa/6a/a536f2af647b18205b740fc5ec31c68d0a3f582de8975adc36041b090171/stacks_pay_python-1.0.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "785ac651aa4ae9ecab3da1ddd0bbd28ace3626e26a782faac18f6850aaaa3504",
                "md5": "dea87e7313c8ec813ae1b41a158ada07",
                "sha256": "ded135f1a686cfb3ee3e47b960ea1805cb9fe459772d92d053a75f0a64661d83"
            },
            "downloads": -1,
            "filename": "stacks_pay_python-1.0.0.tar.gz",
            "has_sig": false,
            "md5_digest": "dea87e7313c8ec813ae1b41a158ada07",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 18085,
            "upload_time": "2025-09-04T15:54:35",
            "upload_time_iso_8601": "2025-09-04T15:54:35.627537Z",
            "url": "https://files.pythonhosted.org/packages/78/5a/c651aa4ae9ecab3da1ddd0bbd28ace3626e26a782faac18f6850aaaa3504/stacks_pay_python-1.0.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-09-04 15:54:35",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "TheSoftNode",
    "github_project": "sbtc-payment-gateway",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "lcname": "stacks-pay-python"
}
        
Elapsed time: 1.06921s