# CashPay Python SDK

Official Python SDK for integrating with CashPay Payment Gateway.

## Installation

```bash
pip install cashpay
```

## Quick Start

```python
from cashpay import CashPay

client = CashPay(
    api_key='cpk_live_xxx',
    api_secret='cps_live_xxx',
    environment='production'  # or 'sandbox'
)
```

## Usage Examples

### Check Balance

```python
# Get unified balance
balance = client.balance.get()
print(f"Total Balance: ₹{balance.total_balance / 100}")

# Get settlement balance
settlement = client.balance.get_settlement()
print(f"Available for withdrawal: ₹{settlement.available_withdrawal_amount / 100}")

# Get payout balance
payout = client.balance.get_payout()
print(f"Payout Balance: ₹{payout.payout_balance / 100}")
```

### Payins (Check Payment Status)

```python
# Get payin by order ID
payin = client.payins.get_by_order_id('ORDER_12345')
print(f"Status: {payin['status']}, UTR: {payin['utr']}")

# Get payin status by payment ID
status = client.payins.get_status('payment-uuid')
```

### Payouts

```python
# Create a payout
payout = client.payouts.create(
    beneficiary_id='ben_xxx',
    amount=10000,  # ₹100 in paise
    reference_id='PAY-001',
    narration='Salary payment',
    mode='IMPS',
    idempotency_key='unique-key'
)
print(f"Payout ID: {payout['id']}, Status: {payout['status']}")

# Create bulk payouts (max 100)
bulk_result = client.payouts.create_bulk([
    {'beneficiaryId': 'ben_1', 'amount': 10000, 'referenceId': 'PAY-001'},
    {'beneficiaryId': 'ben_2', 'amount': 20000, 'referenceId': 'PAY-002'},
], idempotency_key='bulk-key')
print(f"Success: {bulk_result['successCount']}, Failed: {bulk_result['failureCount']}")

# List payouts
payouts = client.payouts.list(page=1, limit=20, status='COMPLETED')

# Get payout by ID
payout_details = client.payouts.get('payout-uuid')

# Get payout by reference ID
payout_by_ref = client.payouts.get_by_reference_id('PAY-001')

# Cancel payout
cancelled = client.payouts.cancel('payout-uuid')
```

### Settlements

```python
# Create settlement with saved bank account
settlement = client.settlements.create(
    amount=100000,  # ₹1000 in paise
    bank_account_id='bank_xxx',
    reference_id='SET-001',
    idempotency_key='unique-key'
)

# Create settlement with direct bank details
direct_settlement = client.settlements.create(
    amount=100000,
    account_number='50100123456789',
    ifsc='HDFC0001234',
    account_holder_name='John Doe',
    reference_id='SET-002'
)

# Create bulk settlements
bulk_settlements = client.settlements.create_bulk([
    {'amount': 50000, 'bankAccountId': 'bank_1', 'referenceId': 'SET-001'},
    {'amount': 75000, 'bankAccountId': 'bank_2', 'referenceId': 'SET-002'},
])

# List settlements
settlements = client.settlements.list(status='COMPLETED')

# Get settlement by ID
settlement_details = client.settlements.get('settlement-uuid')

# Cancel settlement
cancelled_settlement = client.settlements.cancel('settlement-uuid')
```

### Webhook Verification

```python
from flask import Flask, request

app = Flask(__name__)

@app.route('/webhook', methods=['POST'])
def webhook():
    signature = request.headers.get('x-webhook-signature')
    payload = request.get_data(as_text=True)
    
    is_valid = client.verify_webhook(payload, signature, 'your-webhook-secret')
    
    if not is_valid:
        return 'Invalid signature', 401
    
    event = request.get_json()
    
    if event['type'] == 'payin.completed':
        print('Payment completed:', event['data'])
    elif event['type'] == 'payout.completed':
        print('Payout completed:', event['data'])
    elif event['type'] == 'settlement.completed':
        print('Settlement completed:', event['data'])
    
    return 'OK', 200
```

## Error Handling

```python
from cashpay import CashPay, CashPayError

try:
    payout = client.payouts.create(
        beneficiary_id='invalid-id',
        amount=10000
    )
except CashPayError as e:
    print(f"Error: {e.message}")
    print(f"Status: {e.status_code}")
    print(f"Code: {e.code}")
    print(f"Details: {e.details}")
```

## Configuration Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `api_key` | str | required | Your API key |
| `api_secret` | str | required | Your API secret |
| `environment` | str | 'production' | 'sandbox' or 'production' |
| `base_url` | str | auto | Custom API base URL |
| `timeout` | int | 30 | Request timeout in seconds |

## Support

- Documentation: https://docs.cashpay.com
- Email: support@cashpay.com
- GitHub Issues: https://github.com/cashpay/cashpay-python-sdk/issues
