Metadata-Version: 2.1
Name: gtrade-payments
Version: 1.0.0
Summary: Official GTRADE payments SDK for Python: create crypto payments, list them and verify signed webhooks.
Author: GTRADE
License: MIT
Keywords: gtrade,payments,crypto,checkout,webhooks
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Typing :: Typed
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE

# gtrade_payments (Python)

Official GTRADE payments SDK for Python 3.8+. Create crypto payments, send customers to the hosted
checkout, list payments and verify signed webhooks. Standard library only (no dependencies), typed.

## Install

```bash
pip install https://docs.gtradegateway.io/sdk/gtrade_payments-1.0.0-py3-none-any.whl
```

Checksums: https://docs.gtradegateway.io/sdk/SHA256SUMS

## Quick start

```python
import os
from gtrade_payments import Gtrade

gtrade = Gtrade(api_key=os.environ["GTRADE_API_KEY"])

payment = gtrade.payments.create(
    amount_usd=25,
    customer_email="buyer@example.com",
    customer_id="cust_42",                # optional, defaults to the email
    metadata={"order_id": "A-1001"},      # optional, returned on the payment and every webhook
    idempotency_key="order-A-1001",       # optional, recommended: one key per order
)

# Redirect the customer to the hosted checkout:
return redirect(payment.checkout_url, code=303)
```

Keep the API key on your server. Responses are `dict`s that also allow attribute access
(`payment.id` and `payment["id"]` both work).

## Client options

```python
Gtrade(api_key, base_url="https://api.gtradegateway.io", timeout=30.0, max_retries=2)
```

`base_url` defaults to `gtrade_payments.DEFAULT_BASE_URL`. `timeout` is in seconds.
`max_retries=0` disables automatic retries.

## API

### Payments

```python
gtrade.payments.create(amount_usd=..., customer_email=..., customer_id=None, metadata=None, idempotency_key=None)
gtrade.payments.retrieve(payment_id)
gtrade.payments.list(limit=None, status=None, starting_after=None)   # {"object": "list", "data": [...], "has_more": bool}

for p in gtrade.payments.list_auto_paging(status="paid", limit=100):  # fetches further pages lazily
    print(p.id, p.amount_paid_usd)
```

A payment has `id`, `status` (`open`, `pending`, `partially_paid`, `paid`, `cancelled`, `expired`),
`amount_usd`, `amount_paid_usd`, `currency`, `network`, `customer_email`, `customer_id`,
`checkout_url`, `metadata`, `created_at`, `updated_at`.

Idempotency: the same `idempotency_key` with the same parameters returns the original payment.
The same key with different parameters raises `ConflictError` (`idempotency_key_reused`).

### Webhook endpoints

```python
wh = gtrade.webhooks.create("https://shop.example.com/gtrade/webhook")  # public https only
gtrade.webhooks.list()
gtrade.webhooks.test(wh.id)      # sends a signed payment.test event: status "succeeded" | "pending", response_status
gtrade.webhooks.delete(wh.id)    # {"id": ..., "deleted": True}
```

### Health

```python
gtrade.health()                  # {"status": "ok"}
```

## Receiving webhooks

Each delivery is a `POST` with a JSON body and the headers `X-Gtrade-Signature`
(`sha256=<hex HMAC-SHA256(raw body, your API key)>`), `X-Gtrade-Event` and `X-Gtrade-Delivery`.
Verify over the **raw** body bytes:

```python
from gtrade_payments import Webhook, SignatureVerificationError

@app.post("/gtrade/webhook")
def gtrade_webhook():
    raw = request.get_data()          # exact bytes; never re-serialise request.json
    try:
        event = Webhook.construct_event(raw, request.headers.get("X-Gtrade-Signature"), API_KEY)
    except SignatureVerificationError:
        return "invalid signature", 400
    if event.type == "payment.paid":
        ...  # fulfil event.data.metadata["order_id"]
    return {"received": True}
```

- `Webhook.verify(raw_body, signature_header, api_key) -> bool` (constant-time compare).
- `Webhook.construct_event(raw_body, signature_header, api_key)` returns the parsed event or raises `SignatureVerificationError`.

Event types: `payment.updated`, `payment.partially_paid`, `payment.paid`, `payment.cancelled`,
`payment.expired`, `payment.test`. Answer with any 2xx within 10 s. The same status can arrive more
than once, so make your handler idempotent on `data.id` + `data.status`.

## Errors

All exceptions extend `GtradeError` and carry `status_code`, `type`, `code`, `message`, `request_id`, `headers`, `body`.

| Class | When |
|---|---|
| `AuthenticationError` | 401, missing or invalid API key |
| `NotFoundError` | 404, unknown payment or webhook |
| `ConflictError` | 409, idempotency key conflict |
| `ValidationError` | 400 / 422, invalid parameters |
| `RateLimitError` | 429, has `retry_after` (seconds) |
| `ApiError` | any other HTTP error |
| `ConnectionError` | network failure or timeout (this is `gtrade_payments.ConnectionError`, not the builtin) |
| `SignatureVerificationError` | webhook signature check failed |

## Retries

GET and DELETE requests are retried up to `max_retries` times on 429 (honouring `Retry-After`), 5xx
and network errors, with exponential backoff and jitter. `payments.create` is retried only with an
idempotency key; when retries are enabled and you pass none, the SDK generates one per call, so a
retry can never create a duplicate. `webhooks.create` and `webhooks.test` are never retried.

## Examples

- `examples/create_payment_flask.py`: Flask route that creates a payment and redirects to checkout.
- `examples/webhook_flask.py`: Flask webhook receiver verifying the raw body.

## License

MIT, see `LICENSE`.
