Skip to main content

Official Python SDK for HayBTech Payment Gateway

Project description

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

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

haybtech_sdk-1.0.0.tar.gz (5.3 kB view details)

Uploaded Source

Built Distribution

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

haybtech_sdk-1.0.0-py3-none-any.whl (5.9 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: haybtech_sdk-1.0.0.tar.gz
  • Upload date:
  • Size: 5.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.3

File hashes

Hashes for haybtech_sdk-1.0.0.tar.gz
Algorithm Hash digest
SHA256 c920848fd135039a38e0b81a8fd4b278dd8a292836636206564b03bc6f6fc732
MD5 3c30d5e0338e0613887165dfad221484
BLAKE2b-256 4ec392541db7651d0ace0af45287fd16da5a36eaf2c823ffab5d596804209f74

See more details on using hashes here.

File details

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

File metadata

  • Download URL: haybtech_sdk-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 5.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.3

File hashes

Hashes for haybtech_sdk-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 af7ac355564de8eb51f133c9dc9f3b22ce6e75223401b8ce95071a072b82d806
MD5 305134d844b9c1ac0b2267de277db02a
BLAKE2b-256 9c071021b15fdaf86c1fbfe17bbebe377d1853cb7765d80ff144361405e4da73

See more details on using hashes here.

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