cashpayyy 1.1.1
Official CashPay Payment Gateway SDK for Python
Requires Python: >=3.8
Keywords: cashpay payment gateway upi payin payout settlement india

# 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

```python
# 1. Create a Hosted Payment Page (Direct Redirect Flow)
page = client.payins.create_payment_page({
    'amount': 10000, # ₹100
    'orderId': 'ORDER_123',
    'customerName': 'John Doe',
    'customerEmail': 'john@example.com',
    'customerPhone': '9876543210',
    'returnUrl': 'https://yoursite.com/payment/result'
})
print(f"Payment URL: {page['paymentUrl']}")

# 2. Create UPI Intent (for Mobile App redirects)
intent = client.payins.create_intent({
    'amount': 5000,
    'orderId': 'ORDER_124',
    'customer_phone': '9876543210'
})
print(f"UPI DeepLink: {intent['intentUrl']}")

# 3. Create Card Payment
card = client.payins.create_card({
    'amount': 10000,
    'orderId': 'ORDER_125',
    'cardNumber': '4111111111111111',
    'expiryMonth': '12',
    'expiryYear': '2025',
    'cvv': '123'
})

# Get payin status by payment ID
status = client.payins.get_status('payment-uuid')

# Get payin by order ID
payin = client.payins.get_by_order_id('ORDER_124')
print(f"Status: {payin['status']}, UTR: {payin['utr']}")
```

### Payment Links

```python
# Create a shareable payment link or QR
link = client.payment_links.create({
    'amount': 50000,
    'description': 'Invoice #001',
    'type': 'one-time', # or 'reusable'
    'outputType': 'link' # or 'qr'
})
print(f"Short URL: {link['shortUrl']}")

# List payment links
links = client.payment_links.list(page=1, limit=10, status='active')

# Deactivate a link
client.payment_links.deactivate('link-uuid')
```

### Beneficiaries & Bank Accounts

```python
# Add a beneficiary for payouts
beneficiary = client.beneficiaries.create({
    'name': 'John Doe',
    'accountNumber': '50100123456789',
    'ifsc': 'HDFC0001234'
})

# Add a merchant bank account for settlements
bank = client.bank_accounts.create({
    'accountNumber': '50100123456789',
    'ifsc': 'HDFC0001234',
    'accountHolderName': 'My Business'
})
```

### 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