# cptpayment

Official CPTPayment SDK for Python

## Installation

```bash
pip install cptpayment
```

Or install from source:

```bash
pip install -e .
```

## Quick Start

```python
from cpt import CPTPayment

cpt = CPTPayment('your-api-key')

# Test connection
auth = cpt.auth_test()
print(f"Store ID: {auth['store_id']}")

# Create an order
order = cpt.create_order(
    order_id='ORDER_123',
    price_amount=29.99,
    price_currency='USD',
    title='Product Name',
    description='Product description',
    success_url='https://yourstore.com/success',
    cancel_url='https://yourstore.com/cancel',
)

# Get checkout URL for redirect
checkout_url = cpt.get_checkout_url(order['order_id'], order['store_id'])
# Redirect user to: checkout_url
```

## API Reference

### Constructor

```python
cpt = CPTPayment(
    api_key='your-api-key',
    base_url='https://api.cptpayment.com'  # optional
)
```

### Methods

#### `auth_test()`
Test API connection and get store info.

```python
auth = cpt.auth_test()
# Returns: {'status', 'store_id', 'mode', 'credits'}
```

#### `create_order(...)`
Create an order on CPTPayment.

```python
order = cpt.create_order(
    order_id='ORDER_123',
    price_amount=29.99,
    price_currency='USD',
    success_url='https://yourstore.com/success',
    cancel_url='https://yourstore.com/cancel',
    purchaser_email='customer@example.com',  # optional
    description='Order description',          # optional
    title='Order title',                      # optional
)
# Returns: {'order_id', 'store_id', 'status', 'invoice', 'payment_url'}
```

#### `get_order_status(order_id)`
Get order status.

```python
status = cpt.get_order_status('ORDER_123')
# Returns: {'order_id', 'status', 'invoice'}
```

#### `get_checkout_url(order_id, store_id)`
Generate checkout URL for redirect flow.

```python
url = cpt.get_checkout_url('ORDER_123', 42)
# Returns: 'https://cptpayment.com/checkout/?plugins=1&order_id=ORDER_123&store_id=42'
```

#### `verify_webhook(payload, signature)`
Verify webhook signature.

```python
is_valid = cpt.verify_webhook(request.json, request.headers.get('X-Signature'))
```

### Advanced Methods (Custom UI)

#### `get_wallets(order_id, store_id, reservation_id=None)`
Get available wallets for an order.

#### `create_invoice(...)`
Create an invoice after wallet selection.

#### `get_invoice_status(invoice_id)`
Get invoice status for polling.

## Error Handling

```python
from cpt import CPTPayment, CPTError, CPTAuthError

try:
    order = cpt.create_order(...)
except CPTAuthError:
    print('Invalid API key')
except CPTError as e:
    print(f'API Error: {e.message} (status: {e.status_code})')
```

## Flask Example

```python
from flask import Flask, request, jsonify
from cpt import CPTPayment
import os

app = Flask(__name__)
cpt = CPTPayment(os.environ['CPT_API_KEY'])

@app.route('/checkout', methods=['POST'])
def checkout():
    data = request.json

    order = cpt.create_order(
        order_id=f"ORDER_{data['product_id']}",
        price_amount=data['price'],
        price_currency='USD',
        title=data['product_name'],
        success_url='http://localhost:5000/success',
        cancel_url='http://localhost:5000/cancel',
    )

    checkout_url = cpt.get_checkout_url(order['order_id'], order['store_id'])
    return jsonify({'checkout_url': checkout_url})

@app.route('/webhook', methods=['POST'])
def webhook():
    payload = request.json

    if payload.get('status') == 'paid':
        print(f"Payment confirmed for order: {payload.get('order_id')}")
        # Fulfill order here

    return jsonify({'status': 'received'})
```

## License

MIT
