Skip to content
HisarPay

Crypto payments in Python

Two clients with the same names, sync and async. In Django, Flask or a FastAPI service, type definitions help your editor and errors help your logs.

  • Python 3.9+
  • sync · async
  • Flask · FastAPI · Django

What it does

  • HisarPay and AsyncHisarPay offer the same methods.
  • Decimal and timezone-aware datetime values can be passed as they are.
  • The shape of every response is a TypedDict in hisarpay.types.
  • Lists come with an iterator over all pages.
Creating an invoice from a terminal

Requirements

Python
3.9 or later
Dependency
httpx
HisarPay
A test key (hp_test_…)

Setup

  1. Step 1

    Install

    Install it into your virtual environment and read the key from an environment variable.

    Terminal
    pip install https://hisarpay.com/downloads/hisarpay-1.0.0-py3-none-any.whl
  2. Step 2

    Open the invoice

    Give the amount as a Decimal or a string. Send the customer to payment_url.

    Python
    import os
    from hisarpay import HisarPay
    
    client = HisarPay(os.environ["HISARPAY_API_KEY"])
    
    def start_payment(order) -> str:
        invoice = client.invoices.create({
            "price_usd": order.total,             # Decimal("49.90") or "49.90", never a float
            "order_id": order.number,             # the same order never gets a second invoice
            "description": order.title,
            "success_url": f"https://shop.example/orders/{order.number}",
        })
        return invoice["payment_url"]             # redirect the customer here
  3. Step 3

    Verify the webhook

    Hand over the raw bytes; with request.json the signature will not match.

    import os
    from flask import Flask, abort, request
    from hisarpay import SignatureVerificationError, webhooks
    
    app = Flask(__name__)
    
    @app.post("/webhooks/hisarpay")
    def hisarpay_webhook():
        try:
            event = webhooks.construct_event(
                request.get_data(),                        # raw bytes, not request.json
                request.headers.get(webhooks.SIGNATURE_HEADER),
                os.environ["HISARPAY_WEBHOOK_SECRET"],
            )
        except SignatureVerificationError:
            abort(400)
        if event["livemode"] and event["type"] in ("invoice.paid", "invoice.overpaid"):
            mark_paid(event["id"], event["data"]["invoice"]["order_id"])   # once per event id
        return "", 204
  4. Step 4

    Run the sample shop

    Download the example project from the top of this page: a small shop with three products that verifies the webhook and shows the state of an order. The library is inside; put your test key in .env and start it.

Client options

All optional; the defaults suit most shops.

base_url
Defaults to https://hisarpay.com. Point it at a local API during development.
timeout
Timeout of each network step in seconds. Defaults to 30.
max_retries
Retries after the first attempt (network errors, timeouts, 429, 5xx). Defaults to 2.
http_client
Your own httpx client (a proxy, a custom transport).
idempotency_key
Your own key for one POST request. Left out, the library makes one and keeps it across retries.

Errors

All of them extend hisarpay.HisarPayError.

ErrorWhen
ValidationErrorOne of the fields is wrong (400, 422)
AuthenticationErrorKey missing, unknown or revoked (401)
PermissionDeniedErrorScope missing, IP not allowed, a live-only call with a test key (403)
RateLimitErrorToo many requests (429)
APIConnectionError · APITimeoutErrorThe network was not reached, or the answer took too long
SignatureVerificationErrorThe webhook signature does not match

Frequently asked questions

How do I close the async client?
Use an async with block or call await client.aclose(). An httpx client of your own is never closed by the library.
Django answers with a CSRF error. Why?
A webhook does not come from a browser and has no CSRF token. Mark the view csrf_exempt; the signature is what protects it.
How do I test a handler?
webhooks.generate_test_header makes a valid header for your payload and secret.
Which licence does the library have?
MIT. Read the source and ship it with your project.

Node.js

A dependency-free library written in TypeScript, with samples for Express, Next.js and plain http.

  • Node.js 18+
  • TypeScript
  • ESM · CommonJS

PHP

A Composer package that works with plain PHP, Laravel and Symfony. No framework needed.

  • PHP 8.1+
  • Composer
  • Laravel · Symfony

REST API

A predictable REST API for everything from invoices to withdrawals, with signed webhooks and a test mode.

  • REST
  • OpenAPI 3.1
  • Webhooks

Your first collection is an e-mail away

Sign-up is free; your test keys are ready the moment you confirm your e-mail.