Metadata-Version: 2.4
Name: django-credo-sdk
Version: 0.1.2
Summary: Unofficial Django SDK for Credo payment integration
Author-email: Samox <hello@credocentral.com>
License: MIT License
        
        Copyright (c) 2025 Samox
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
Project-URL: Homepage, https://github.com/yourusername/django-credo-sdk
Project-URL: Bug Tracker, https://github.com/yourusername/django-credo-sdk/issues
Project-URL: Documentation, https://github.com/yourusername/django-credo-sdk#readme
Project-URL: Source Code, https://github.com/yourusername/django-credo-sdk
Keywords: django,credo,payments,sdk,payment-gateway,nigeria,fintech
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Framework :: Django
Classifier: Framework :: Django :: 5.0
Classifier: Framework :: Django :: 5.1
Classifier: Framework :: Django :: 5.2
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Office/Business :: Financial
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: django>=5.0
Requires-Dist: djangorestframework>=3.14.0
Requires-Dist: requests>=2.31.0
Dynamic: license-file

# Django Credo SDK

Unofficial Django SDK for integrating Credo Payment Gateway into Django applications.

The SDK gives you a small, server-side integration surface for:

- initializing Credo payment sessions
- generating readable unique payment references
- verifying transactions before fulfillment
- handling Credo browser callbacks and server webhooks on one endpoint
- verifying webhook signatures
- processing payment events idempotently
- using optional Django model mixins for common payment workflows
- testing your configuration from a built-in debug page

## Installation

```bash
pip install django-credo-sdk
```

## Requirements

- Python 3.10+
- Django 5.0+
- Django REST Framework 3.14+
- requests 2.31+

The package does not cap Django below future major versions, so supported environments can resolve newer Django releases such as Django 6 when your Python version supports them.

## Django Setup

Add the app and SDK URLs:

```python
# settings.py
INSTALLED_APPS = [
    # ...
    "rest_framework",
    "credo_pay",
]
```

```python
# urls.py
from django.urls import include, path

urlpatterns = [
    path("api/credo/", include("credo_pay.urls")),
]
```

Configure Credo from Django settings or environment variables:

```python
# settings.py
CREDO_PUBLIC_KEY = "your_public_key"
CREDO_SECRET_KEY = "your_secret_key"
CREDO_ENVIRONMENT = "sandbox"  # "sandbox" or "production"
CREDO_DEFAULT_CALLBACK_URL = "https://yoursite.com/api/credo/callback-webhook/"

# Optional, but recommended for webhooks
CREDO_WEBHOOK_SECRET_TOKEN = "token-you-set-in-credo-dashboard"

# Optional defaults
CREDO_DEFAULT_CURRENCY = "NGN"
CREDO_DEFAULT_CHANNELS = ["card", "bank"]
CREDO_DEFAULT_BEARER = 0  # 0 = customer pays fee, 1 = merchant pays fee
CREDO_LOGO_URL = ""       # Credo expects a 60x60 logo
CREDO_REQUEST_TIMEOUT = 15
```

If you use `python-decouple`, the same settings can be loaded from `.env`.

```env
CREDO_PUBLIC_KEY=your_public_key
CREDO_SECRET_KEY=your_secret_key
CREDO_ENVIRONMENT=sandbox
CREDO_DEFAULT_CALLBACK_URL=https://yoursite.com/api/credo/callback-webhook/
CREDO_WEBHOOK_SECRET_TOKEN=your_webhook_token
CREDO_REQUEST_TIMEOUT=15
```

`CREDO_DEFAULT_CALLBACK_URL` should point to the SDK's unified callback/webhook endpoint. The same URL handles:

- `GET` browser redirects from Credo after payment attempts
- `POST` server-to-server webhook notifications from Credo

In production, callback and logo URLs must use HTTPS. Local `http://localhost` callback URLs are only for sandbox browser-redirect testing.

## Terminal ID

Credo Terminal IDs identify merchant accounts on Credo's platform. The current Credo initialize, verify, callback, and webhook endpoints used by this SDK do not accept a `terminalId` field, so `CREDO_TERMINAL_ID` is not required by this package.

Keep your Terminal ID with your Credo credentials, but do not configure it for this SDK unless Credo adds an endpoint requirement later.

## Environment URLs

The SDK chooses Credo's API URL from `CREDO_ENVIRONMENT`.

| Environment | API URL |
| --- | --- |
| `sandbox` | `https://api.credodemo.com` |
| `production` | `https://api.credocentral.com` |

## Amounts

Credo expects payment initialization amounts in the lowest currency value. For NGN, that is kobo.

The SDK public APIs accept the currency's main unit instead:

```python
client.initialize_payment(
    amount=15000,  # NGN 15,000
    email="customer@example.com",
)
```

The SDK sends `1500000` to Credo for NGN. Verification and webhook payloads retain Credo's raw amount fields and also expose main-unit helpers such as `trans_amount_major`, `debited_amount_major`, `trans_fee_amount_major`, and `settlement_amount_major`.

## Initialize a Payment

```python
from credo_pay import CredoClient

client = CredoClient()

response = client.initialize_payment(
    amount=15000,  # NGN 15,000; SDK sends kobo to Credo
    email="customer@example.com",
    callback_url="https://yoursite.com/api/credo/callback-webhook/",
    first_name="John",
    last_name="Doe",
    phone_number="2348032132100",
    reference_prefix="ORDER",
)

redirect_url = response.authorization_url
trans_ref = response.trans_ref
business_reference = response.reference
```

Redirect the customer to `response.authorization_url`.

## Payment References

Credo references must be unique and alphanumeric. If you want references that carry product or order context, pass `reference_prefix`:

```python
response = client.initialize_payment(
    amount=15000,
    email="customer@example.com",
    reference_prefix="codex",
)
```

You can also generate a reference yourself:

```python
from credo_pay import generate_payment_reference

reference = generate_payment_reference(prefix="codex")

response = client.initialize_payment(
    amount=15000,
    email="customer@example.com",
    reference=reference,
)
```

The prefix is sanitized to alphanumeric characters because Credo references do not support spaces, hyphens, or symbols. Store both your business reference and Credo's `trans_ref` for reconciliation.

## Verify Before Fulfillment

Credo's browser callback is a redirect with query parameters. Treat it as a signal to verify, not as proof of payment.

```python
verification = client.verify_payment("jIMj005d3Y100M0A00MB")

if verification.is_successful:
    verification.assert_amount(15000, currency="NGN")
    fulfill_order()
elif verification.is_failed:
    mark_order_failed()
else:
    keep_order_pending()
```

`assert_amount()` receives the expected amount in the currency's main unit, not kobo.

## Unified Callback/Webhook View

The SDK's built-in URL is:

```text
/api/credo/callback-webhook/
```

It is intentionally named `callback-webhook` because it serves two Credo flows:

| Method | Source | Purpose |
| --- | --- | --- |
| `GET` | Customer browser redirect | Parse callback query params and verify transaction |
| `POST` | Credo server webhook | Verify signature, parse event, run handlers |

Subclass `CredoWebhookView` when you use Django REST Framework:

```python
from django.shortcuts import redirect
from credo_pay import CredoWebhookView


class MyCredoView(CredoWebhookView):
    def handle_callback(self, callback_data, verify_response):
        if verify_response and verify_response.is_successful:
            Order.objects.filter(reference=callback_data.reference).update(status="paid")
            return redirect("/payment/success/")
        return redirect("/payment/failed/")

    def handle_webhook(self, event):
        if event.is_successful:
            Order.objects.filter(credo_trans_ref=event.trans_ref).update(status="paid")
        elif event.is_failed:
            Order.objects.filter(credo_trans_ref=event.trans_ref).update(status="failed")
        elif event.is_settlement:
            Transaction.objects.filter(credo_trans_ref=event.trans_ref).update(settled=True)
```

```python
from django.urls import path
from .views import MyCredoView

urlpatterns = [
    path("api/credo/callback-webhook/", MyCredoView.as_view(), name="credo-callback-webhook"),
]
```

If your project does not use DRF, subclass `DjangoCredoWebhookView`:

```python
from credo_pay import DjangoCredoWebhookView


class MyCredoView(DjangoCredoWebhookView):
    def handle_webhook(self, event):
        ...
```

## Webhook Signatures

Credo signs webhook requests with a SHA512 hash:

```text
SHA512(webhook_token + business_code)
```

Set `CREDO_WEBHOOK_SECRET_TOKEN` to the token configured in Credo's dashboard. Credo sends `data.businessCode` in each webhook payload, and the SDK uses that payload value for signature verification.

## Idempotent Payment Processing

Callbacks and webhooks may arrive close together. Use `process_payment_event()` with a row lock so fulfillment happens once.

```python
from credo_pay import model_payment_lock, process_payment_event

process_payment_event(
    reference=event.trans_ref,
    event=event,
    lock=model_payment_lock(Order, lookup_field="credo_trans_ref"),
    on_success=lambda event, order: order.mark_paid_once(),
    on_failure=lambda event, order: order.mark_failed_once(),
)
```

Your `mark_paid_once()` and `mark_failed_once()` methods should also be safe to call repeatedly.

## Model Mixin

`CredoPaymentMixin` is optional. It reduces boilerplate for the common pattern of keeping payment state on a Django model.

The mixin handles only Credo API calls. You own your model's fields and decide what to persist in each lifecycle hook.

```python
from django.db import models
from credo_pay.mixins import CredoPaymentMixin


class Order(CredoPaymentMixin, models.Model):
    amount    = models.DecimalField(max_digits=12, decimal_places=2)
    email     = models.EmailField()
    credo_ref = models.CharField(max_length=64, blank=True)
    status    = models.CharField(max_length=20, default="pending")

    # --- required ---

    def get_payment_amount(self):
        return self.amount

    def get_payment_email(self):
        return self.email

    # --- required for sync_payment_status() ---

    def get_credo_trans_ref(self):
        return self.credo_ref or None

    # --- hooks: override only what you need ---

    def on_payment_initiated(self, response):
        self.credo_ref = response.trans_ref or ""
        self.status = "awaiting_payment"
        self.save(update_fields=["credo_ref", "status"])

    def on_payment_confirmed(self, verification):
        self.status = "paid"
        self.save(update_fields=["status"])

    def on_payment_failed(self, verification):
        self.status = "failed"
        self.save(update_fields=["status"])
```

Starting a payment in a view:

```python
order = get_object_or_404(Order, pk=pk)
response = order.create_payment()
return redirect(response.authorization_url)
```

Handling a callback or webhook:

```python
order = Order.objects.get(credo_ref=event.trans_ref)
order.sync_payment_status()
```

Two methods are required: `get_payment_amount()` and `get_payment_email()`. Override `get_credo_trans_ref()` so that `sync_payment_status()` can locate the right Credo transaction. Everything else returns `None` by default and can be overridden when needed:

- `get_payment_callback_url()` — per-object callback URL
- `get_payment_currency()` — currency code
- `get_payment_channels()` — payment channels
- `get_payment_first_name()`, `get_payment_last_name()`, `get_payment_phone_number()`
- `get_payment_service_code()`, `get_payment_bank_account()` — routed payments
- `get_payment_metadata()`, `get_payment_custom_fields()`
- `get_payment_bearer()` — who pays the transaction fee (0 = customer, 1 = merchant)

All keyword arguments accepted by `CredoClient.initialize_payment()` can also be passed directly to `create_payment()` as one-off overrides without subclassing:

```python
response = order.create_payment(callback_url="https://yoursite.com/api/credo/callback-webhook/")
```

### Routed payments with the mixin

Override `get_payment_service_code()` and `get_payment_bank_account()`:

```python
class VendorOrder(CredoPaymentMixin, models.Model):
    amount       = models.DecimalField(max_digits=12, decimal_places=2)
    email        = models.EmailField()
    service_code = models.CharField(max_length=80)
    bank_account = models.CharField(max_length=20)
    credo_ref    = models.CharField(max_length=64, blank=True)
    status       = models.CharField(max_length=20, default="pending")

    def get_payment_amount(self):        return self.amount
    def get_payment_email(self):         return self.email
    def get_credo_trans_ref(self):       return self.credo_ref or None
    def get_payment_service_code(self):  return self.service_code
    def get_payment_bank_account(self):  return self.bank_account

    def on_payment_initiated(self, response):
        self.credo_ref = response.trans_ref or ""
        self.status = "pending"
        self.save(update_fields=["credo_ref", "status"])

    def on_payment_confirmed(self, verification):
        self.status = "paid"
        self.save(update_fields=["status"])
```

### Preventing duplicate processing

When a callback and a webhook arrive at the same time, use `payment_lock()` inside your hook:

```python
def on_payment_confirmed(self, verification):
    with self.payment_lock() as locked:
        if locked.status == "paid":
            return                      # already processed, do nothing
        locked.status = "paid"
        locked.save(update_fields=["status"])
```

### Amount verification

Call `assert_amount()` on the `VerifyResponse` inside `on_payment_confirmed()` before fulfilling the order:

```python
def on_payment_confirmed(self, verification):
    verification.assert_amount(self.amount, currency="NGN")
    self.status = "paid"
    self.save(update_fields=["status"])

## Routed Payments

Use routed payments when Credo has configured dynamic settlement service codes for your account.

```python
response = client.initialize_routed_payment(
    amount=15000,
    email="customer@example.com",
    service_code="YOUR_SERVICE_CODE",
    bank_account="0114877128",
    callback_url="https://yoursite.com/api/credo/callback-webhook/",
)
```

For model-based routed payments, use `CredoPaymentMixin` and override `get_payment_service_code()` and `get_payment_bank_account()`. See the Routed payments with the mixin example in the Model Mixin section above.

## REST Endpoints

When `credo_pay.urls` is included under `/api/credo/`, the SDK provides:

| Endpoint | Method | Auth | Description |
| --- | --- | --- | --- |
| `/api/credo/initialize/` | `POST` | Open | Initialize a payment |
| `/api/credo/routed/initialize/` | `POST` | Open | Initialize a routed payment |
| `/api/credo/verify/<trans_ref>/` | `GET` | Open | Verify a transaction |
| `/api/credo/callback-webhook/` | `GET` | Open | Customer redirect callback |
| `/api/credo/callback-webhook/` | `POST` | Open | Credo server webhook |
| `/api/credo/debug/` | `GET` | Debug-gated | Development debug interface |

All production endpoints use `AllowAny` so the SDK does not impose an authentication policy. If your application requires users to be logged in before initiating a payment, subclass the view and set your own `permission_classes`:

```python
from rest_framework.permissions import IsAuthenticated
from credo_pay.views import PaymentInitializeView

class AuthenticatedPaymentView(PaymentInitializeView):
    permission_classes = [IsAuthenticated]
```

Webhook and callback endpoints must remain open because Credo's servers cannot supply Django authentication credentials. Authenticity of POST webhooks is enforced through `X-Credo-Signature` verification instead.

## Debug Interface

Visit:

```text
http://localhost:8000/api/credo/debug/
```

The debug interface is available only when Django `DEBUG=True` or `CREDO_ENABLE_DEBUG_INTERFACE=True`. Do not enable it in production.

The debug interface uses the same configured SDK settings as normal payment calls. It does not invent callback URLs. If `CREDO_DEFAULT_CALLBACK_URL` is missing, the configuration check fails.

Debug payment initialization uses `CREDO_DEBUG_REQUEST_TIMEOUT` when set, defaulting to `8` seconds. Normal SDK calls use `CREDO_REQUEST_TIMEOUT`, defaulting to `15` seconds.

Use it to:

- confirm keys, environment, API URL, callback URL, and webhook token state
- initialize a sandbox payment
- verify a transaction by Credo `trans_ref`
- watch real callbacks and webhooks that reach the SDK endpoint
- copy integration examples

Local browser callbacks can work with `localhost` because the customer browser is redirected. Server-to-server webhooks from Credo need a public HTTPS URL, for example through a tunnel, and that public URL must be registered in Credo's dashboard.

The debug webhook inbox starts polling only after you initialize a debug payment and stops when a callback or webhook arrives.

## Status Codes

| Code | Meaning |
| --- | --- |
| `0` | Successful |
| `1` | Refunded |
| `2` | Refund queued |
| `3` | Failed |
| `4` | Successful, queued for settlement |
| `5` | Settled |
| `6` | Review |
| `7` | Declined |
| `8` | Failed aged |
| `9` | Abandoned |
| `13` | Attempted |
| `14` | Initialised |
| `15` | Initialising |

## Production Checklist

- Set `CREDO_ENVIRONMENT=production`.
- Use live Credo public and secret keys.
- Set `CREDO_DEFAULT_CALLBACK_URL` to your HTTPS callback/webhook endpoint.
- Register the same HTTPS endpoint in Credo's webhook settings.
- Set a strong `CREDO_WEBHOOK_SECRET_TOKEN` in both Credo and Django.
- Always verify payment status before fulfillment.
- Make order fulfillment idempotent.
- Do not expose secret keys in frontend code.

## Support

- Credo support: `hello@credocentral.com`
- Sandbox dashboard: `https://www.credodemo.com`
- Production dashboard: `https://www.credocentral.com`

## Disclaimer

This is an unofficial SDK and is not affiliated with or endorsed by Credo.
