# Python SDK

Create payments, check their status and verify webhooks from Python: Django, Flask, FastAPI or any script.

- **Package:** [`razcrypto`](https://pypi.org/project/razcrypto/) on PyPI
- **Version:** 2.0.0 · typed (`py.typed`)
- **Requires:** Python 3.9+. Standard library only.
- **Key:** Secret key `sk_…` (server only) + webhook signing secret `whsec_…`
- **Download:** [razcrypto-python-sdk.zip](https://razcryptogateway.com/downloads/razcrypto-python-sdk.zip) · [Source on GitHub](https://github.com/WorldxGrowth/razcrypto-python-sdk) · MIT

## 1. Install

### From PyPI (recommended)

```bash
pip install razcrypto
```

### From the download (local / offline)

```bash
curl -L -o razcrypto-python-sdk.zip https://razcryptogateway.com/downloads/razcrypto-python-sdk.zip
unzip razcrypto-python-sdk.zip               # creates razcrypto-python-sdk/
pip install ./razcrypto-python-sdk
```

### From GitHub (development)

```bash
pip install "git+https://github.com/WorldxGrowth/razcrypto-python-sdk.git"
# or editable, to change the code:
git clone https://github.com/WorldxGrowth/razcrypto-python-sdk.git && pip install -e ./razcrypto-python-sdk
```

## 2. Keys

```bash
# .env (server only)
RAZCRYPTO_SECRET_KEY=sk_test_xxxxxxxxxxxxxxxx
RAZCRYPTO_WEBHOOK_SECRET=whsec_xxxxxxxxxxxxxxxx
```

Get them in **Dashboard → API apps**.

## 3. Quick example

```python
import os
from razcrypto import RazCrypto

rc = RazCrypto(os.environ["RAZCRYPTO_SECRET_KEY"])

payment = rc.payments.create(
    amount="49.00",                 # decimal string
    currency="USD",                 # or INR, EUR …; converted to crypto at checkout
    reference_id=str(order.id),     # your order id
    redirect_url="https://shop.example/thanks",  # website flow only
    idempotency_key=f"order_{order.id}",          # a retry never creates a duplicate
)
# Website: redirect to payment["checkout_url"]
# App: return {"payment_id": payment["id"], "checkout_url": payment["checkout_url"]}

p = rc.payments.retrieve("pay_…")   # server truth
if p["status"] == "paid":
    ...  # fulfil
```

## 4. Verify webhooks

```python
from flask import Flask, request
from razcrypto import webhooks, SignatureVerificationError

@app.post("/webhooks/razcrypto")
def razcrypto_webhook():
    try:
        event = webhooks.verify(request.get_data(), request.headers, os.environ["RAZCRYPTO_WEBHOOK_SECRET"])
    except SignatureVerificationError:
        return "", 400
    payment = event["data"]["object"]          # the full payment object
    if event["type"] == "payment.paid":
        mark_order_paid(payment["reference_id"], payment["id"])
    return "", 200
```

- **Django:** `webhooks.verify(request.body, request.headers, secret)` in a `@csrf_exempt` view.
- **FastAPI:** `webhooks.verify(await request.body(), request.headers, secret)`.

Store the `webhook-id` header and skip repeats. Details: [Webhooks](/docs/webhooks).

## 5. Verify the checkout signature

```python
from razcrypto import is_valid_checkout_signature

# body from the app SDK / checkout.js onSuccess, or the redirect query string
if not is_valid_checkout_signature(body, os.environ["RAZCRYPTO_WEBHOOK_SECRET"]):
    ...  # not from RazCrypto: do not trust it, wait for the webhook
```

## Mobile app backend

The same four endpoints as in the [Laravel example](/docs/php-sdk#laravel-full-integration-for-a-mobile-app):
`create` (returns `checkout_url`), `verify` (signature + `retrieve`), `status` (for polling) and the webhook. Fulfil
only when the status is `paid`, once per order.

## API

| Area | Methods |
|---|---|
| Payments | `payments.create(**params, idempotency_key=…)`, `retrieve(id)`, `list(**params)`, `auto_paging_iter(**params)`, `methods(id)`, `quote(id, chain, coin)`, `cancel(id)`, `simulate(id, outcome)` (test mode) |
| Payment links | `payment_links.create(…)`, `retrieve`, `list`, `update`, `deactivate` |
| Others | `chains()`, `rates(["USDT", "BNB"], "USD")`, `merchant()`, `event(id)` |

**Errors.** API errors raise `razcrypto.ApiError` (`status`, `code`, `param`, `request_id`). Network problems raise
`razcrypto.ConnectionError_`. Network errors, `429` and `5xx` are retried. Options:
`RazCrypto(key, timeout=30.0, max_retries=2)`. See [Errors](/docs/errors).

## Test

```python
rc.payments.simulate("pay_…", "paid")   # with a sk_test_ key; also underpaid, expired, cancelled
```

Run the SDK's own tests with `python -m unittest discover -s tests`.
