PayzCore Docs

Python SDK

Official Python SDK for PayzCore. Create payments, check status, verify webhooks with HMAC-SHA256. Flask and Django examples included. Python 3.9+.

Python SDK

The official Python SDK for PayzCore.

Installation

pip install payzcore

Initialization

from payzcore import PayzCore

# Project API (payment monitoring)
client = PayzCore("pk_live_YOUR_KEY")

# With options
client = PayzCore(
    "pk_live_YOUR_KEY",
    base_url="https://api.payzcore.com",  # optional, default
    timeout=30.0,                          # optional, seconds
    max_retries=2,                         # optional, retries on 5xx
)

# Admin API (project management)
admin = PayzCore("mk_YOUR_MASTER_KEY", master_key=True)

The client supports context managers for automatic cleanup:

with PayzCore("pk_live_YOUR_KEY") as client:
    payment = client.payments.create(
        amount=50,
        chain="TRC20",
        external_ref="user-123",
    )

Create a Payment

result = client.payments.create(
    amount=50,
    chain="TRC20",
    token="USDT",                # optional, defaults to "USDT"
    external_ref="customer-123",
    external_order_id="ORD-456", # optional, idempotency
    expires_in=3600,             # optional, seconds
    metadata={"type": "topup"},  # optional, max 4KB
)

payment = result["payment"]
print(payment["address"])   # blockchain address
print(payment["amount"])    # "50.00"
print(payment["qr_code"])  # base64 PNG

Get Payment Status

result = client.payments.get("payment-uuid")

payment = result["payment"]
print(payment["status"])        # 'pending', 'confirming', 'paid', etc.
print(payment["paid_amount"])
print(payment["transactions"])  # list of blockchain txs

List Payments

result = client.payments.list(status="paid", limit=25, offset=0)

for payment in result["payments"]:
    print(payment["id"], payment["status"])

Cancel a Payment

result = client.payments.cancel("payment-uuid")

Confirm Transaction Hash

result = client.payments.confirm("payment-uuid", "abc123def...")
print(result["verified"])  # True if found on blockchain

Webhook Verification

The SDK exports standalone functions for webhook verification. Import them directly from the package:

from payzcore import verify_signature, construct_event

Verify Signature Only

from payzcore import verify_signature

is_valid = verify_signature(
    body=raw_body,
    signature=request.headers["x-payzcore-signature"],
    secret="whsec_YOUR_SECRET",
)
from payzcore import construct_event, WebhookSignatureError

# Verifies signature and returns a typed WebhookPayload dict
# Raises WebhookSignatureError if signature is invalid
try:
    event = construct_event(
        body=raw_body,
        signature=request.headers["x-payzcore-signature"],
        secret="whsec_YOUR_SECRET",
    )
except WebhookSignatureError:
    return {"error": "Invalid signature"}, 401

print(event["event"])        # "payment.completed"
print(event["payment_id"])   # UUID
print(event["paid_amount"])  # "50.00"

Both functions accept optional timestamp replay protection:

event = construct_event(
    body=raw_body,
    signature=signature,
    secret="whsec_YOUR_SECRET",
    timestamp=request.headers.get("x-payzcore-timestamp"),
    tolerance_seconds=300,  # 5 minutes (default)
)

Flask Webhook Handler

from flask import Flask, request, jsonify
from payzcore import construct_event, WebhookSignatureError

app = Flask(__name__)

@app.route("/webhooks/payzcore", methods=["POST"])
def handle_webhook():
    body = request.get_data(as_text=True)
    signature = request.headers.get("x-payzcore-signature", "")

    try:
        event = construct_event(body, signature, "whsec_YOUR_SECRET")
    except WebhookSignatureError:
        return jsonify({"error": "Invalid signature"}), 401

    if event["event"] == "payment.completed":
        credit_user(event["external_ref"], float(event["paid_amount"]))
    elif event["event"] == "payment.expired":
        handle_expired(event["external_ref"], event["payment_id"])

    return jsonify({"ok": True})

Django Webhook Handler

import json
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from payzcore import construct_event, WebhookSignatureError

@csrf_exempt
def payzcore_webhook(request):
    if request.method != "POST":
        return JsonResponse({"error": "Method not allowed"}, status=405)

    body = request.body.decode("utf-8")
    signature = request.headers.get("x-payzcore-signature", "")

    try:
        event = construct_event(body, signature, "whsec_YOUR_SECRET")
    except WebhookSignatureError:
        return JsonResponse({"error": "Invalid signature"}, status=401)

    if event["event"] == "payment.completed":
        credit_user(event["external_ref"], float(event["paid_amount"]))

    return JsonResponse({"ok": True})

Error Handling

The SDK throws typed error classes for different HTTP status codes:

from payzcore import (
    PayzCoreError,
    AuthenticationError,
    ValidationError,
    RateLimitError,
    NotFoundError,
)

try:
    result = client.payments.create(amount=50, chain="TRC20", external_ref="user-1")
except ValidationError as e:
    print(f"Invalid request: {e.message} (details: {e.details})")
except AuthenticationError as e:
    print(f"Auth error: {e.message}")
except RateLimitError as e:
    print(f"Rate limited, daily: {e.is_daily}, retry after: {e.retry_after}")
except NotFoundError as e:
    print(f"Not found: {e.message}")
except PayzCoreError as e:
    print(f"API error {e.status}: {e.message}")
Error ClassStatusMeaning
ValidationError400Invalid request parameters
AuthenticationError401Invalid or missing API key
ForbiddenError403Project inactive or limit exceeded
NotFoundError404Payment not found
RateLimitError429Daily API call limit reached
PayzCoreError5xxServer error (auto-retried)

On this page