Skip to main content

Clean, fully-typed Python SDK for the Paystack API — full surface coverage, Pydantic models, and automatic retry logic.

Project description

paystack-python

A clean, fully-typed Python SDK for the Paystack API — complete surface coverage, Pydantic v2 models, and automatic retry logic.

PyPI version Python versions Tests Coverage License: MIT


Why this exists

The official Paystack Python library covers less than 30% of the API surface and hasn't been updated in years. Nigerian developers waste hours reading raw API docs for every integration. This SDK provides complete, typed coverage so you can integrate Paystack in minutes, not days.


Installation

pip install paystack-python

Quick start

from paystack import PaystackClient

paystack = PaystackClient(secret_key="sk_test_...")

# Or use an environment variable: PAYSTACK_SECRET_KEY
paystack = PaystackClient()

# Initialise a payment — returns a typed Pydantic model
response = paystack.transactions.initialize(
    email="customer@example.com",
    amount=50_000,   # ₦500.00 — always in lowest denomination (kobo)
)
print(response.data.authorization_url)   # redirect the user here

# Verify after payment
result = paystack.transactions.verify("txn_reference_xyz")
if result.data.status == "success":
    fulfil_order()

API coverage

Resource Operations
Transactions initialize, verify, list, fetch, charge_authorization, check_authorization, timeline, totals, export, partial_debit
Customers create, list, fetch, update, validate, whitelist/blacklist, deactivate_authorization
Transfers create_recipient, list/fetch/update/delete recipient, initiate, bulk, finalize, verify, fetch, list
Plans create, list, fetch, update
Subscriptions create, list, fetch, enable, disable, generate_update_link, send_update_link
Refunds create, list, fetch
Identity resolve_account, validate_account, resolve_card_bin, list_banks, list_countries, list_states
Webhooks verify_signature, parse_event, WebhookEvent

Key features

Typed responses — everywhere

Every method returns a PaystackResponse[T] or PaginatedResponse[T]. Your editor knows the exact shape of response.data before you run a single line.

resp = paystack.transactions.verify("ref_123")
# resp.data is Transaction — fully typed
print(resp.data.amount)          # int (kobo)
print(resp.data.authorization)   # Authorization | None

Automatic retry with exponential backoff

Transient failures (429, 5xx) are retried automatically. Configure per-client:

paystack = PaystackClient(
    secret_key="sk_...",
    max_retries=3,       # default
    backoff_factor=0.5,  # waits: 0s, 1s, 2s between attempts
)

Normalisation layer

Paystack returns different response shapes across endpoints. Every response is normalised into a consistent PaystackResponse[T] envelope — no more response["data"]["authorization_url"] guesswork.

Webhook verification

from paystack.webhooks import WebhookEvent
from paystack.exceptions import WebhookSignatureError

# Django/Flask/FastAPI view
def webhook(request):
    try:
        event = WebhookEvent(
            payload=request.body,
            signature=request.headers["X-Paystack-Signature"],
            secret_key=settings.PAYSTACK_SECRET_KEY,
        )
    except WebhookSignatureError:
        return HttpResponse(status=400)

    if event.type == "charge.success":
        process_payment(event.data)
    elif event.type == "transfer.success":
        confirm_transfer(event.data)

    return HttpResponse(status=200)

Advanced usage

Transfers

# 1. Create a recipient
recipient = paystack.transfers.create_recipient(
    type="nuban",
    name="Ada Okafor",
    account_number="0123456789",
    bank_code="058",   # GTBank
)

# 2. Initiate the transfer
transfer = paystack.transfers.initiate(
    amount=250_000,   # ₦2,500
    recipient=recipient.data.recipient_code,
    reason="Freelance payment - Invoice #42",
)

# 3. Verify later
result = paystack.transfers.verify(transfer.data.transfer_code)

Subscriptions

# Create a monthly plan
plan = paystack.plans.create(
    name="Pro Monthly",
    amount=2_000_000,   # ₦20,000/month
    interval="monthly",
)

# Subscribe a customer
sub = paystack.subscriptions.create(
    customer="CUS_xxxxx",
    plan=plan.data.plan_code,
)

# Disable when they cancel
paystack.subscriptions.disable(
    code=sub.data.subscription_code,
    token=sub.data.email_token,
)

Identity verification

# Resolve a bank account before sending money
account = paystack.identity.resolve_account(
    account_number="0123456789",
    bank_code="058",
)
print(f"Sending to: {account.data.account_name}")

# List all banks
banks = paystack.identity.list_banks(country="nigeria")

Error handling

from paystack.exceptions import (
    AuthenticationError,
    InvalidRequestError,
    NotFoundError,
    RateLimitError,
    RetryExhaustedError,
    ServerError,
)

try:
    result = paystack.transactions.verify("ref_xyz")
except NotFoundError:
    print("Transaction not found")
except AuthenticationError:
    print("Check your secret key")
except RetryExhaustedError as e:
    print(f"Failed after retries: {e.status_code}")
except PaystackError as e:
    print(f"Unexpected error: {e.message} (HTTP {e.status_code})")

Development

git clone https://github.com/yourusername/paystack-python
cd paystack-python
pip install -e ".[dev]"

# Run tests
pytest

# Run tests with coverage
pytest --cov=paystack --cov-report=term-missing

# Lint
ruff check paystack/

# Type check
mypy paystack/

Contributing

PRs are welcome! Please open an issue first to discuss what you'd like to change.

Areas where contributions are especially valued:

  • Additional Paystack resources (Disputes, Settlements, Charges, Bulk Charges, Payment Pages)
  • Async client (httpx-based AsyncPaystackClient)
  • Django integration helpers

License

MIT © 2024

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

paystack_sdk_python-1.0.0.tar.gz (20.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

paystack_sdk_python-1.0.0-py3-none-any.whl (23.5 kB view details)

Uploaded Python 3

File details

Details for the file paystack_sdk_python-1.0.0.tar.gz.

File metadata

  • Download URL: paystack_sdk_python-1.0.0.tar.gz
  • Upload date:
  • Size: 20.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for paystack_sdk_python-1.0.0.tar.gz
Algorithm Hash digest
SHA256 eeb2d1e95577d20dd86e8856163309b7a204c646dcfc8083ca3805d6dee2ccc7
MD5 35255ad7d03cb466f62649237f50a4ee
BLAKE2b-256 f117cdf0a95ddc379432d06b994e3012ce4a72127945bc0c6d712439547c217e

See more details on using hashes here.

Provenance

The following attestation bundles were made for paystack_sdk_python-1.0.0.tar.gz:

Publisher: publish.yml on Barrkolawole22/paystack-python

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file paystack_sdk_python-1.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for paystack_sdk_python-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 f4001e66c1fa3eb7928c4c81d0f649905ac3c7d15f9082fbca38853cf530332f
MD5 e76299b1c223f5481b5cdea871454e56
BLAKE2b-256 82d02b2ab85941d4107c250405ab3c4b1e5affd304bba9551c1690831b43ed53

See more details on using hashes here.

Provenance

The following attestation bundles were made for paystack_sdk_python-1.0.0-py3-none-any.whl:

Publisher: publish.yml on Barrkolawole22/paystack-python

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page