Skip to main content

HayBTech Python SDK

Official Python SDK for the HayBTech Payment Gateway API -- mobile payments across West Africa .

PyPI Python License


Installation

pip install haybtech-sdk

Quick Start (Zero-Config)

If you have HAYBTECH_SECRET_KEY set in your environment (e.g. via .env), you can initialize the SDK with zero configuration:

from haybtech import HayBTechClient

client = HayBTechClient()

(Optional) You can also pass the key explicitly:

client = HayBTechClient('sk_test_your_key')

Initiate a payment

try: response = client.payments.create({ 'merchant_ref': 'ORDER-12345', 'amount': 5000, 'currency': 'XOF', 'return_url': 'https://mysite.com/success', 'cancel_url': 'https://mysite.com/cancel', 'callback_url': 'https://mysite.com/webhook' })

print(f"Payment URL: {response.redirect_url()}")

# Django Helper
# return response.to_django_redirect()

except Exception as e: print(f"Error: {e}")


---

## Webhooks

### Django

```python
from haybtech import Webhook, SignatureException

def my_webhook_view(request):
    payload = request.body.decode('utf-8')
    signature = request.headers.get('X-HayBTech-Signature')
    secret = 'whsec_...'

    try:
        event = Webhook.construct_event(payload, signature, secret)
        
        if event['event'] == 'payment.success':
            merchant_ref = event['data']['merchant_ref']
            # Mark order as paid
            
        return HttpResponse("OK", status=200)
    except SignatureException:
        return HttpResponse("Invalid Signature", status=403)

Flask

from flask import Flask, request, jsonify
from haybtech import Webhook, SignatureException

app = Flask(__name__)

@app.route('/webhook', methods=['POST'])
def webhook():
    payload = request.get_data(as_text=True)
    signature = request.headers.get('X-HayBTech-Signature')

    try:
        event = Webhook.construct_event(payload, signature, 'whsec_...')
        
        if event['event'] == 'payment.success':
            # Mark order as paid
            pass
        
        return jsonify(status='ok'), 200
    except SignatureException:
        return jsonify(error='Invalid Signature'), 403

FastAPI

from fastapi import FastAPI, Request, HTTPException
from haybtech import Webhook, SignatureException

app = FastAPI()

@app.post("/webhook")
async def webhook(request: Request):
    payload = (await request.body()).decode('utf-8')
    signature = request.headers.get('X-HayBTech-Signature')

    try:
        event = Webhook.construct_event(payload, signature, 'whsec_...')
        
        if event['event'] == 'payment.success':
            # Mark order as paid
            pass
        
        return {"status": "ok"}
    except SignatureException:
        raise HTTPException(status_code=403, detail="Invalid Signature")

Available Events

Event Description
payment.success Payment confirmed
payment.failed Payment failed
payment.cancelled Cancelled by customer
payment.expired Payment timed out
payment.expired Payment timed out

Error Handling

from haybtech import HayBTechClient
from haybtech.exceptions import ApiException, HayBTechException

client = HayBTechClient('sk_test_...')

try:
    response = client.payments.create(params)
except ApiException as e:
    print(e.message)       # Human-readable message
    print(e.http_status)   # 400, 422, 500...
    print(e.error_code)    # e.g., "insufficient_funds"
except HayBTechException as e:
    # SDK not configured, key invalid, etc.
    print(e)

Test Mode

client = HayBTechClient('sk_test_...') # No real charges


Security Features

This SDK is built for Maximum Security:

  • Zero Dependencies: Uses only standard Python libraries (urllib, hmac, hashlib). No vulnerabilities from external packages.
  • Secret Masking: Keys are automatically masked in repr() and protected against pickle serialization.
  • Memory Protection: Webhook payloads are capped at 1 MB to prevent memory exhaustion attacks.
  • Timing Attack Resistance: Uses hmac.compare_digest for signature verification.
  • Replay Protection: 5-minute timestamp tolerance on webhook signatures.
  • CRLF Guard: Prevents HTTP header injection via malformed keys.

API Resources

Resource Description
client.payments Create, retrieve, list, and verify transactions
client.webhooks Manage notification endpoints programmatically

MIT License

Metadata

Release files for haybtech-sdk 1.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for haybtech-sdk 1.0.0
File Size Uploaded Provenance Actions
haybtech_sdk-1.0.0.tar.gz 5.3 kB Without provenance Details for haybtech_sdk-1.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for haybtech-sdk 1.0.0
File Interpreter ABI Platform Actions
haybtech_sdk-1.0.0-py3-none-any.whl Python 3 none any Details for haybtech_sdk-1.0.0-py3-none-any.whl

Total release size: 11.2 kB

Release files / haybtech_sdk-1.0.0.tar.gz

Download URL haybtech_sdk-1.0.0.tar.gz
Size 5.3 kB
Tags Source
SHA-256 checksum
How to use checksums
c920848fd135039a38e0b81a8fd4b278dd8a292836636206564b03bc6f6fc732
BLAKE2b-256 checksum
How to use checksums
4ec392541db7651d0ace0af45287fd16da5a36eaf2c823ffab5d596804209f74
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.14.3

Release files / haybtech_sdk-1.0.0-py3-none-any.whl

Download URL haybtech_sdk-1.0.0-py3-none-any.whl
Size 5.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
af7ac355564de8eb51f133c9dc9f3b22ce6e75223401b8ce95071a072b82d806
BLAKE2b-256 checksum
How to use checksums
9c071021b15fdaf86c1fbfe17bbebe377d1853cb7765d80ff144361405e4da73
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.14.3

Security for haybtech-sdk 1.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

1.0.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page