Accept crypto payments in Python (Flask and Django)
To accept crypto payments in Python, create a CoinStack checkout with one call through the requests library, redirect the customer to its url, and confirm the payment with a signed webhook. In Flask the webhook reads request.get_data(); in Django it reads request.body in a view marked @csrf_exempt. Both compute an HMAC-SHA256 over the raw bytes, compare it with hmac.compare_digest, store the event_id so a retried event is ignored, and mark the order paid only when the checkout is completed or resolved.
What you need
The code was run in December 2026 on Python 3.14 with requests 2.34, Flask 3.1 and Django 6.1, against a stand-in for the API and with signed sample events. Install what your framework needs:
pip install requests flask # or: pip install requests djangoFrom the CoinStack dashboard's Developers page, create an API key with Read and write access and add a webhook for your server's URL. Copy the sk_ key and the whsec_ signing secret into environment variables; each is shown only once. BASE_URL is your site's public address; the checkout page links back to it.
export COINSTACK_API_KEY=sk_your_key
export COINSTACK_WEBHOOK_SECRET=whsec_your_secret
export BASE_URL=https://shop.example.comThe meaning of each checkout field is covered in the crypto payments API quickstart. This post is about the Python side.
Create the checkout with requests
This module is shared by the Flask and Django examples. Save it as coinstack_client.py.
import os
import requests
API = "https://coinstack.net/api/v1"
OPEN = ("pending", "confirming", "partial")
class CoinStackError(Exception):
pass
def call(method, path, **kwargs):
response = requests.request(
method,
f"{API}{path}",
headers={"Authorization": f"Bearer {os.environ['COINSTACK_API_KEY']}"},
timeout=30,
**kwargs,
)
body = response.json()
if not body["success"]:
raise CoinStackError(f"{response.status_code} {body['response']}")
return body["response"]
def create_checkout(order_id, amount, currency, base_url):
reference = f"order-{order_id}"
payload = {
"amount": amount,
"currency": currency,
"reference": reference,
"description": f"Order #{order_id}",
"success_url": f"{base_url}/orders/{order_id}",
"cancel_url": f"{base_url}/cart",
"metadata": {"order_id": str(order_id)},
}
try:
return call("POST", "/checkouts", json=payload)["checkout"]
except requests.Timeout:
# The first request may have gone through. Look before creating another.
found = call("GET", "/checkouts", params={"reference": reference})["checkouts"]
for checkout in found:
if checkout["status"] in OPEN:
return checkout
return call("POST", "/checkouts", json=payload)["checkout"]json=payload makes requests serialize the body and set Content-Type: application/json, which the API requires. Always pass timeout: without one, requests can wait on a stalled connection indefinitely, and your customer waits with it. call unwraps the API's envelope, {"success": true, "response": {...}} or {"success": false, "response": "message"}, and raises with the HTTP status and message on failure.
The except requests.Timeout branch exists because creating a checkout twice makes two checkouts. A timeout leaves you unsure whether the first request landed, so the code lists checkouts by reference and reuses an open one before trying again. This is the retry the errors page recommends, and it is why every checkout gets a reference. Note str(order_id) in metadata: metadata values must be strings, and an integer is rejected with Invalid metadata. Keep amount a string too, such as "25.00", never a float.
Flask: send the customer to the checkout
The Flask app keeps orders in SQLite so the example runs on its own. Save it as app.py; the next section adds the webhook to the same file.
import hashlib
import hmac
import json
import os
import sqlite3
import time
from contextlib import closing
from flask import Flask, redirect, request
from coinstack_client import create_checkout
app = Flask(__name__)
secret = os.environ["COINSTACK_WEBHOOK_SECRET"]
base_url = os.environ["BASE_URL"]
SCHEMA = """
CREATE TABLE IF NOT EXISTS orders (
id INTEGER PRIMARY KEY,
amount TEXT NOT NULL,
currency TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'unpaid',
paid_at TEXT
);
CREATE TABLE IF NOT EXISTS checkouts (
checkout_id TEXT PRIMARY KEY,
order_id INTEGER NOT NULL REFERENCES orders (id)
);
CREATE TABLE IF NOT EXISTS webhook_events (
event_id TEXT PRIMARY KEY,
kind TEXT NOT NULL,
received_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
"""
def connect():
conn = sqlite3.connect("shop.db", timeout=10)
conn.row_factory = sqlite3.Row
return conn
with closing(connect()) as conn:
conn.executescript(SCHEMA)
@app.post("/orders/<int:order_id>/pay")
def pay(order_id):
with closing(connect()) as conn:
order = conn.execute("SELECT * FROM orders WHERE id = ?", (order_id,)).fetchone()
if order is None:
return "Not found", 404
if order["status"] == "paid":
return redirect(f"/orders/{order_id}", 303)
checkout = create_checkout(order_id, order["amount"], order["currency"], base_url)
with closing(connect()) as conn, conn:
conn.execute(
"INSERT OR IGNORE INTO checkouts (checkout_id, order_id) VALUES (?, ?)",
(checkout["checkout_id"], order_id),
)
return redirect(checkout["url"], 303)
@app.get("/orders/<int:order_id>")
def order_status(order_id):
with closing(connect()) as conn:
order = conn.execute("SELECT status FROM orders WHERE id = ?", (order_id,)).fetchone()
if order is None:
return "Not found", 404
if order["status"] == "paid":
return f"Order #{order_id} is paid."
return f"Order #{order_id}: payment not confirmed yet. Reload this page in a minute."A separate checkouts table, instead of a column on orders, lets one order have several checkouts: one that expired, then a fresh one. A late payment to the first still finds its order. The amount always comes from the database, not the request. order_status is the page success_url points to; it can load a moment before the webhook arrives, so it says "not confirmed yet" rather than "failed". with closing(connect()) as conn, conn: reads as "open a connection, run one transaction, commit or roll back, then close": sqlite3's own context manager handles the transaction but does not close the connection, which is what closing adds.
Flask: verify the signature and handle the event
Append this to app.py.
def verify(header, body):
parts = dict(part.split("=", 1) for part in header.split(",") if "=" in part)
timestamp = parts.get("t", "")
signed = timestamp.encode() + b"." + body
expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
return (
hmac.compare_digest(parts.get("v1", "").encode(), expected.encode())
and timestamp.isdigit()
and abs(time.time() - int(timestamp)) <= 300
)
def apply_checkout(conn, checkout):
if checkout["status"] not in ("completed", "resolved"):
return
conn.execute(
"""
UPDATE orders SET status = 'paid', paid_at = CURRENT_TIMESTAMP
WHERE status <> 'paid'
AND id = (SELECT order_id FROM checkouts WHERE checkout_id = ?)
""",
(checkout["checkout_id"],),
)
@app.post("/webhooks/coinstack")
def coinstack_webhook():
body = request.get_data()
if not verify(request.headers.get("CoinStack-Signature", ""), body):
return "Invalid signature", 400
event = json.loads(body)
# One transaction: committed if everything succeeds, rolled back if anything raises.
with closing(connect()) as conn, conn:
inserted = conn.execute(
"INSERT INTO webhook_events (event_id, kind) VALUES (?, ?) ON CONFLICT DO NOTHING",
(event["event_id"], event["kind"]),
).rowcount
if inserted == 1 and event["kind"].startswith("checkout."):
apply_checkout(conn, event["data"]["checkout"])
return "", 200verify is the function from the CoinStack webhooks guide. It splits the t=...,v1=... header, signs t plus a full stop plus the raw body with your secret, and checks three things: the signature matches in constant time, t is a number, and it is no more than 300 seconds old. request.get_data() returns the body as bytes, exactly as sent. Calling request.get_json() for the check and re-encoding the result would change the bytes and fail every time; parse with json.loads only after verifying.
The event insert and the order update run in one transaction. The first delivery of an event_id inserts a row (rowcount is 1) and does the work. A retry, which keeps the same event_id, inserts nothing and changes nothing but still gets its 200. If apply_checkout raises, the transaction rolls back, Flask returns a 500, and CoinStack retries after 1 minute, then 5 minutes, then later, up to 8 attempts over about a day. The UPDATE only matches checkouts this app created, so the dashboard's Send test event, whose checkout you never made, changes nothing.
Checking the status, rather than the event name, also keeps the handler correct when events arrive out of order. A retried checkout.confirming that lands after checkout.completed has status confirming and is ignored. Reliable payment webhooks covers ordering in more depth.
Test the Flask webhook with a signed request
Signing a sample body in a test proves the whole path, including the raw-body handling, without waiting for a real payment. Save as test_webhook.py and run pytest:
import hashlib
import hmac
import json
import os
import time
os.environ.setdefault("COINSTACK_WEBHOOK_SECRET", "whsec_test")
os.environ.setdefault("BASE_URL", "https://shop.example.com")
from app import app, connect # noqa: E402
def signed(body):
t = str(int(time.time()))
secret = os.environ["COINSTACK_WEBHOOK_SECRET"].encode()
v1 = hmac.new(secret, t.encode() + b"." + body, hashlib.sha256).hexdigest()
return {"CoinStack-Signature": f"t={t},v1={v1}"}
def test_completed_event_marks_order_paid_once():
with connect() as conn:
order_id = conn.execute(
"INSERT INTO orders (amount, currency) VALUES ('1.00', 'USD')"
).lastrowid
conn.execute(
"INSERT INTO checkouts (checkout_id, order_id) VALUES (?, ?)",
(f"test-checkout-{order_id}", order_id),
)
body = json.dumps({
"event_id": f"test-event-{order_id}",
"kind": "checkout.completed",
"data": {"checkout": {"checkout_id": f"test-checkout-{order_id}", "status": "completed"}},
"created_at": "2026-12-30T12:00:00Z",
}).encode()
client = app.test_client()
for _ in range(2): # the second delivery is a duplicate
response = client.post("/webhooks/coinstack", data=body,
headers=signed(body), content_type="application/json")
assert response.status_code == 200
assert client.post("/webhooks/coinstack", data=body, content_type="application/json",
headers={"CoinStack-Signature": "t=1,v1=bad"}).status_code == 400
with connect() as conn:
status = conn.execute("SELECT status FROM orders WHERE id = ?", (order_id,)).fetchone()[0]
assert status == "paid"The test writes to the same shop.db as the app, which is fine for a demo; point connect() at a temporary file in a real test suite.
Django: models for orders, checkouts and events
In a Django app called payments, put coinstack_client.py next to views.py and define three models in models.py:
from django.db import models
class Order(models.Model):
amount = models.DecimalField(max_digits=12, decimal_places=2)
currency = models.CharField(max_length=3, default="USD")
status = models.CharField(max_length=10, default="unpaid")
paid_at = models.DateTimeField(null=True, blank=True)
class Checkout(models.Model):
checkout_id = models.CharField(max_length=36, primary_key=True)
order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name="checkouts")
class WebhookEvent(models.Model):
event_id = models.CharField(max_length=36, primary_key=True)
kind = models.CharField(max_length=40)
received_at = models.DateTimeField(auto_now_add=True)Making event_id the primary key is what hands duplicate detection to the database: two workers handling the same event at the same moment cannot both insert it. str(order.amount) on a DecimalField with 2 decimal places gives "25.00", the string format the API wants. Run makemigrations and migrate as usual.
Django: the webhook view with csrf_exempt and request.body
import hashlib
import hmac
import json
import os
import time
from django.db import transaction
from django.http import HttpResponse, HttpResponseBadRequest
from django.shortcuts import get_object_or_404, redirect
from django.utils import timezone
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from .coinstack_client import create_checkout
from .models import Checkout, Order, WebhookEvent
secret = os.environ["COINSTACK_WEBHOOK_SECRET"]
base_url = os.environ["BASE_URL"]
@require_POST
def pay(request, order_id):
order = get_object_or_404(Order, pk=order_id)
if order.status == "paid":
return redirect(f"/orders/{order.id}/")
checkout = create_checkout(order.id, str(order.amount), order.currency, base_url)
Checkout.objects.get_or_create(checkout_id=checkout["checkout_id"], order=order)
return redirect(checkout["url"])
def order_status(request, order_id):
order = get_object_or_404(Order, pk=order_id)
note = "is paid." if order.status == "paid" else "is waiting for the payment to confirm."
return HttpResponse(f"Order #{order.id} {note}")
def verify(header, body):
parts = dict(part.split("=", 1) for part in header.split(",") if "=" in part)
timestamp = parts.get("t", "")
signed = timestamp.encode() + b"." + body
expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
return (
hmac.compare_digest(parts.get("v1", "").encode(), expected.encode())
and timestamp.isdigit()
and abs(time.time() - int(timestamp)) <= 300
)
def apply_checkout(checkout):
if checkout["status"] not in ("completed", "resolved"):
return
Order.objects.filter(
checkouts__checkout_id=checkout["checkout_id"],
).exclude(status="paid").update(status="paid", paid_at=timezone.now())
@csrf_exempt
@require_POST
def coinstack_webhook(request):
body = request.body
if not verify(request.headers.get("CoinStack-Signature", ""), body):
return HttpResponseBadRequest("Invalid signature")
event = json.loads(body)
with transaction.atomic():
_, created = WebhookEvent.objects.get_or_create(
event_id=event["event_id"],
defaults={"kind": event["kind"]},
)
if created and event["kind"].startswith("checkout."):
apply_checkout(event["data"]["checkout"])
return HttpResponse(status=200)Django's CSRF middleware rejects any POST without a CSRF cookie and token; the CSRF reference says such a request gets "a 403 error". CoinStack's servers have no browser session and cannot send a token, so the webhook view carries @csrf_exempt (listed first, as the outermost decorator). The signature check takes the token's place as the proof that the request is genuine. The pay view keeps CSRF protection, because your own checkout form posts to it with {% csrf_token %}.
request.body is the raw request as a bytestring. The request reference warns that reading the request through its stream methods first makes body raise RawPostDataException, so read body before anything else touches the request. request.headers is case-insensitive, so CoinStack-Signature matches however the header arrives.
Inside transaction.atomic(), get_or_create reports created=True only for the first delivery. If the order update raises, the event row is rolled back with it, Django returns a 500, and the retry runs the work again. The .exclude(status="paid").update(...) is a single conditional SQL UPDATE, so it cannot mark an order paid twice.
Django: URLs and the trailing slash trap
from django.urls import path
from payments import views
urlpatterns = [
path("orders/<int:order_id>/", views.order_status),
path("orders/<int:order_id>/pay/", views.pay),
path("webhooks/coinstack/", views.coinstack_webhook),
]Register the webhook in the CoinStack dashboard with the trailing slash: https://shop.example.com/webhooks/coinstack/. On Django 6.1 with the default APPEND_SLASH, a POST to the slashless URL behaves in one of 2 ways. With DEBUG = False it gets a 301 redirect, and the CoinStack docs count any redirect as a failed delivery. With DEBUG = True Django raises a RuntimeError that explains the slash. Either way the event never reaches your view.
Running under gunicorn or several workers
Production Flask and Django apps run several worker processes, and duplicates of one event can land on two of them at once. That is why both examples keep handled event IDs in the database with a unique key rather than in a Python set, which each worker would have its own copy of. The handlers do two small writes and answer well inside the 10 seconds CoinStack allows. If yours also sends emails or provisions an account, commit the event and the paid status, return 200, and hand the slow work to a task queue such as Celery or RQ.
Before launch, pay a real $1 checkout end to end with a stablecoin, and use Send test on the webhook, which should answer 200 without changing any order. How to test a crypto checkout lists the other cases to try.
Frequently asked questions
Why does my Django webhook return 403?
The CSRF middleware rejected it before your code ran. Add @csrf_exempt to the webhook view, as the outermost decorator, and keep the signature check inside it. If the 403 persists, look for other middleware or a reverse proxy rule that protects the path. A 301 instead of a 403 means the URL is missing its trailing slash.
Can I use FastAPI instead?
Yes. Read the raw bytes with body = await request.body() in a route that takes the Request object, run the same verify function, then parse with json.loads. Avoid declaring a Pydantic model as the route's body parameter for the webhook, since FastAPI would parse the JSON for you and you would be checking re-encoded bytes. Checkout creation can stay on requests or move to httpx.
Why use hmac.compare_digest instead of ==?
A plain == on strings can return as soon as it finds the first differing character, so response timings can leak how much of a forged signature was right. hmac.compare_digest avoids that short cut: the Python standard library documents it as designed to prevent timing analysis, so the time it takes says nothing about how close a guess was.
Does Django REST Framework change anything?
It can. DRF parses the body when you access request.data, and the Django request reference warns that request.body raises an error once the request has been read as a stream. For the webhook, a plain Django function view like the one above avoids the question. If you must use an APIView, read request.body before touching request.data. For more on verification across frameworks, see how to verify payment webhooks, and for PHP the PHP and Laravel tutorial.