EPaySe
Coming Soon

Python SDK

The official EPaySe Python SDK is under development. Use the REST API directly with the requests library in the meantime.

Python Integration

Requests Library

The requests library makes HTTP calls clean and readable with minimal boilerplate.

hmac Module

Python's standard library hmac module with compare_digest for timing-safe verification.

Framework Ready

Works with Django, Flask, FastAPI, and any other Python web framework.

Create a Transaction

Create a payment transaction using Python's requests library with HMAC authentication:

Python
Create Transaction
import hashlib
import hmac
import json
import secrets
import time
import requests

API_KEY = "your_api_key"
SECRET_KEY = "your_secret_key"
BASE_URL = "https://api.epayse.com/api/v1"


def create_transaction(amount: float, currency: str, order_id: str) -> dict:
    """Create a new payment transaction."""
    timestamp = str(int(time.time()))
    nonce = secrets.token_hex(16)

    payload = json.dumps({
        "amount": amount,
        "currency": currency,
        "orderId": order_id,
        "description": f"Payment for {order_id}",
        "returnUrl": "https://yoursite.com/payment/callback",
        "cancelUrl": "https://yoursite.com/payment/cancel",
    })

    # Generate HMAC-SHA256 signature
    signature_string = timestamp + nonce + payload
    signature = hmac.new(
        SECRET_KEY.encode(),
        signature_string.encode(),
        hashlib.sha256
    ).hexdigest()

    response = requests.post(
        f"{BASE_URL}/transaction/create",
        data=payload,
        headers={
            "Content-Type": "application/json",
            "X-Api-Key-Id": API_KEY,
            "X-Signature": signature,
            "X-Timestamp": timestamp,
            "X-Nonce": nonce,
        },
    )

    data = response.json()

    if data["status"] == "SUCCESS":
        return data["data"]

    raise Exception(data.get("message", "Transaction creation failed"))


# Usage
result = create_transaction(100.00, "USD", "ORD-001")
print(f"Checkout URL: {result['checkout_url']}")

Create a Refund

Issue full or partial refunds for completed transactions:

Python
Create Refund
def create_refund(transaction_id: str, amount: float, reason: str = "") -> dict:
    """Create a full or partial refund."""
    timestamp = str(int(time.time()))
    nonce = secrets.token_hex(16)

    payload = json.dumps({
        "transactionId": transaction_id,
        "refundAmount": amount,
        "reason": reason,
    })

    signature = hmac.new(
        SECRET_KEY.encode(),
        (timestamp + nonce + payload).encode(),
        hashlib.sha256
    ).hexdigest()

    response = requests.post(
        f"{BASE_URL}/refund/create",
        data=payload,
        headers={
            "Content-Type": "application/json",
            "X-Api-Key-Id": API_KEY,
            "X-Signature": signature,
            "X-Timestamp": timestamp,
            "X-Nonce": nonce,
        },
    )

    return response.json()


# Full refund
result = create_refund("01kbkzs3pdcdkjvsq2xb2j0ej3", 100.00, "Customer request")

# Partial refund
result = create_refund("01kbkzs3pdcdkjvsq2xb2j0ej3", 25.00, "Partial refund")

Verify Webhook Signature (Flask)

Validate incoming webhooks using hmac.compare_digest for timing-safe comparison:

Python
Flask Webhook Handler
import hmac
import hashlib
import time
from flask import Flask, request, jsonify

app = Flask(__name__)


def verify_webhook_signature(payload: str, headers: dict, secret_key: str) -> bool:
    """Verify that a webhook request is genuinely from EPaySe."""
    signature = headers.get("X-Signature", "")
    timestamp = headers.get("X-Timestamp", "")
    nonce = headers.get("X-Nonce", "")

    # Reject if timestamp is older than 5 minutes
    if abs(time.time() - int(timestamp)) > 300:
        return False

    expected = hmac.new(
        secret_key.encode(),
        (timestamp + nonce + payload).encode(),
        hashlib.sha256
    ).hexdigest()

    return hmac.compare_digest(expected, signature)


@app.route("/webhooks/epayse", methods=["POST"])
def handle_webhook():
    payload = request.get_data(as_text=True)

    if not verify_webhook_signature(payload, request.headers, SECRET_KEY):
        return jsonify({"error": "Invalid signature"}), 401

    event = request.get_json()

    if event["event"] == "transaction.success":
        # Handle successful payment
        pass
    elif event["event"] == "refund.completed":
        # Handle completed refund
        pass

    return jsonify({"received": True})

Django Integration Example

Create payments in a Django view with proper redirect handling:

Python
Django Payment View
# views.py
import hashlib
import hmac
import json
import secrets
import time
import requests
from django.conf import settings
from django.http import JsonResponse
from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_exempt

BASE_URL = "https://api.epayse.com/api/v1"


def create_payment(request):
    """Create a payment and redirect to checkout."""
    api_key = settings.EPAYSE_API_KEY
    secret_key = settings.EPAYSE_SECRET_KEY

    timestamp = str(int(time.time()))
    nonce = secrets.token_hex(16)

    payload = json.dumps({
        "amount": float(request.POST["amount"]),
        "currency": "USD",
        "orderId": request.POST["order_id"],
        "description": request.POST.get("description", ""),
        "returnUrl": request.build_absolute_uri("/payment/callback/"),
        "cancelUrl": request.build_absolute_uri("/payment/cancel/"),
    })

    signature = hmac.new(
        secret_key.encode(),
        (timestamp + nonce + payload).encode(),
        hashlib.sha256
    ).hexdigest()

    response = requests.post(
        f"{BASE_URL}/transaction/create",
        data=payload,
        headers={
            "Content-Type": "application/json",
            "X-Api-Key-Id": api_key,
            "X-Signature": signature,
            "X-Timestamp": timestamp,
            "X-Nonce": nonce,
        },
    )

    data = response.json()

    if data["status"] == "SUCCESS":
        return redirect(data["data"]["checkout_url"])

    return JsonResponse({"error": "Payment failed"}, status=400)

Related Resources

Explore the full API documentation for detailed endpoint specifications.