Skip to content

Python SDK

View as Markdown

The official Python SDK tappay-mn calls the TapPay API for you. It signs requests with HMAC, sends an Idempotency-Key, retries safely, pages through lists and verifies webhooks, so you do not write HTTP by hand. Use it on your server with your secret key.

Install

Add the package to your project.

pip install tappay-mn

Supported versions

The SDK supports these runtime versions. A runtime leaves the list one minor version after its end of life.

SDKPackageVersionInstallSupported runtimesRegistrySource
Pythontappay-mn3.1.0pip install tappay-mnPython 3.10, 3.11, 3.12, 3.13, 3.14PyPIgitlab.com/node-platform/nodepay-python

Quickstart

Take a first test payment in five minutes with a sandbox key. Each step is a full script that you can run on its own.

  1. Create an invoice for the order. The response has the invoiceId and the intentId.
import json
import uuid
import tappay

client = tappay.TapPay("sk_test_YOUR_SECRET_KEY")
invoice = client.invoices.create({
    "body": {
        "terminalId": "YOUR_TERMINAL_ID",
        "amount": 1000,
        "description": "Order #1001",
        "orderId": "order-" + str(uuid.uuid4()) + "",
    },
})
print(json.dumps(invoice))
  1. Create a checkout session for the invoice and send the customer to its url.
import json
import tappay

client = tappay.TapPay("sk_test_YOUR_SECRET_KEY")
checkout_session = client.checkout_sessions.create({
    "body": {
        "invoiceId": "INVOICE_ID",
        "terminalId": "YOUR_TERMINAL_ID",
        "returnUrl": "https://example.com/return",
        "cancelUrl": "https://example.com/cancel",
    },
})
print(json.dumps(checkout_session))
  1. In the sandbox, let the simulator pay the intent. In production the customer pays.
import json
import tappay

client = tappay.TapPay("sk_test_YOUR_SECRET_KEY")
result = client.sandbox.simulate_intent({"id": "INTENT_ID", "body": {"channel": "QR", "outcome": "SUCCEEDED"}})
print(json.dumps(result))
  1. Verify the webhook over the raw body with constructEvent.
import json
import os
import sys
import tappay

client = tappay.TapPay("sk_test_YOUR_SECRET_KEY")
# Your web framework gives you these: the raw body, the headers and the path of your endpoint.
data = json.load(sys.stdin)
try:
    event = client.webhooks.construct_event(data["rawBody"], data["headers"], secrets=[os.environ["TAPPAY_WEBHOOK_SECRET"]], path=data["path"])
    print("valid" if event.id else "invalid")
except tappay.SignatureVerificationError:
    print("invalid")
  1. The event carries only ids. Read the object itself with events.retrieveObject before you hand over goods.
import json
import tappay

client = tappay.TapPay("sk_test_YOUR_SECRET_KEY")
# In your webhook handler pass the event from construct_event. Here it is built from the payment of step 3.
event = {"id": "evt_example", "type": "payment.succeeded", "objectId": "PAYMENT_ID"}
payment = client.events.retrieve_object(event)
print(json.dumps(payment))
  1. Refund the payment if the customer returns the order.
import json
import tappay

client = tappay.TapPay("sk_test_YOUR_SECRET_KEY")
refund = client.refunds.create({"paymentId": "PAYMENT_ID", "body": {"amount": "1000", "reason": "Customer returned the item"}})
print(json.dumps(refund))

Configuration

Pass options to the constructor. An option you leave out is read from the environment. The environment, sandbox or production, follows the key prefix: sk_test_ is the sandbox and sk_live_ is production, so you never set the base URL in code.

OptionEnvironment variableDefaultMeaning
api_keyTAPPAY_SECRET_KEYrequiredSecret key. A publishable key pk_… is rejected.
base_urlTAPPAY_BASE_URLfrom the keyOnly for tests against your own stack. Never in production.
signing_secretTAPPAY_SIGNING_SECRETnoneSigns each request with HMAC when your system uses the API key + HMAC signature method.
timeout_ms—30000Time limit of one call in milliseconds.
max_retries—2Retries after a network error, 429 or 5xx.
max_retry_after_ms—60000Upper limit for Retry-After. Above it the SDK does not wait.
node_version—2026-09-27The TapPay-Version header. Each SDK version pins one API version, and this option overrides it.
import os
import tappay

# Options you leave out are read from TAPPAY_SECRET_KEY, TAPPAY_BASE_URL and TAPPAY_SIGNING_SECRET.
client = tappay.TapPay(
    api_key=os.environ["TAPPAY_SECRET_KEY"],
    signing_secret=os.environ.get("TAPPAY_SIGNING_SECRET"),
    timeout_ms=15000,
    max_retries=3,
    max_retry_after_ms=30000,
    node_version="2026-09-27",
)

# Per call: keyword arguments.
invoice = client.invoices.retrieve({"id": "YOUR_INVOICE_ID"}, timeout_ms=5000, node_version="2026-09-27")

Idempotency and retries

Every POST that creates something is sent with an Idempotency-Key. The SDK makes a new key for each call and sends the same key on each retry of that call, so a retry never creates a second invoice or refund. You can pass your own key, as shown in Idempotency. The SDK retries a network error, 429 and 5xx with exponential backoff and respects Retry-After.

Errors

Each API error is a subclass of TapPayError with status, code, message, requestId and docsUrl. The code is a XXX-NNN value from the error catalog.

ClassWhen
tappay.InvalidRequestError400, 422
tappay.AuthenticationError401
tappay.PermissionError403
tappay.NotFoundError404
tappay.ConflictError409
tappay.IdempotencyError409 VAL-010, same key with a different body
tappay.RateLimitError429
tappay.ApiError5xx and other answers
tappay.ConnectionErrornetwork error
tappay.TimeoutErrorthe call took longer than the time limit
import os
import tappay

client = tappay.TapPay(os.environ["TAPPAY_SECRET_KEY"])
try:
    client.invoices.retrieve({"id": "YOUR_INVOICE_ID"})
except tappay.NotFoundError as e:
    print("not found", e.code, e.request_id)
except tappay.TapPayError as e:
    print(e.status, e.code, e.docs_url)

Pagination

A list call returns a page with data, has_more and next_cursor. The iterator fetches the next pages as you go.

import os
import tappay

client = tappay.TapPay(os.environ["TAPPAY_SECRET_KEY"])
# Every page, fetched as you go.
for payment in client.payments.list({"limit": 50}).auto_paging_iter():
    print(payment["id"], payment["status"])
# Only the first page.
page = client.payments.list({"limit": 10}).first_page()
print(len(page.data), page.has_more, page.next_cursor)

Webhooks

Verify each webhook over the raw body, before any JSON parsing. During a secret rotation pass the new and the previous secret: either one may match. The event is thin, so read the object with events.retrieve_object. Read the webhook guide for the whole flow.

import os
import tappay
from flask import Flask, request

client = tappay.TapPay(os.environ["TAPPAY_SECRET_KEY"])
app = Flask(__name__)


@app.post("/webhooks/tappay")
def webhook():
    try:
        # request.get_data() is the raw body. A json.loads result fails with RAW_BODY_REQUIRED.
        event = client.webhooks.construct_event(
            request.get_data(),
            request.headers,
            # During a rotation both secrets are valid: the new one and the previous one.
            secrets=[s for s in (os.environ.get("TAPPAY_WEBHOOK_SECRET"), os.environ.get("TAPPAY_WEBHOOK_SECRET_PREVIOUS")) if s],
            path=request.full_path.rstrip("?"),
        )
    except tappay.SignatureVerificationError:
        return "", 400
    # The event is thin: read the object itself with GET before you act on it.
    obj = client.events.retrieve_object(event)
    print(event.type, obj["status"])
    return "", 200

POS client

PosClient calls the POS API of a card terminal with a partner credential. It gets and renews the token and signs each request. Read the POS API reference and the POS terminal guide.

import os
import tappay

pos = tappay.PosClient(
    client_id=os.environ["POS_CLIENT_ID"],
    client_secret=os.environ["POS_CLIENT_SECRET"],
    api_key=os.environ["POS_API_KEY"],
    signing_secret=os.environ["POS_SIGNING_SECRET"],
    environment="sandbox",
)

qr = pos.payments.create_qr({"body": {
    "pos_reference": "pos-1001",
    "narrative": "Order #1001",
    "amount": 1000,
    "currency": "MNT",
    "card_terminal": {"terminal_code": "T-SANDBOX-POS", "merchant_code": "M-SANDBOX-POS"},
}})
# Do not trust the callback: read the payment from the API.
payment = pos.payments.retrieve({"paymentId": qr["payment_id"]})
print(payment["status"])

Versioning

The SDK follows semantic versioning. A major version may break your code, and minor and patch versions do not. Each SDK version pins one TapPay-Version. The release notes are on the PyPI page and in the CHANGELOG.md of the package. The Changelog lists the SDK versions for each API version.