Appearance
Example: FastAPI Integration (FitnessQuasar)
FitnessQuasar is a small example project that shows how to connect a FastAPI backend to TiruPay. It simulates a fitness club that sells monthly memberships (unlimited gym access, optionally with sauna access) and single-entry day passes to non-members, and uses a QR code to let members check in at the gym entrance.
This guide walks through the example's source code and explains, step by step, how each part maps onto the TiruPay concepts covered elsewhere in these docs: Customer, Article, Order, Feature, and Balance.
Example project, not production code
FitnessQuasar is provided for illustration only. It is intentionally small and skips things a real integration would need (see Next steps for production at the end of this guide).
Architecture at a glance
Locally, three independent processes are involved. The browser is redirected between them during login and checkout:
plain
┌─────────────────────┐ ┌─────────────────────┐ ┌─────────────────────┐
│ FitnessQuasar │ API │ FitnessQuasar │ API │ TiruPay │
│ Frontend (React) │◄─────►│ Backend (FastAPI) │◄──────►│ API │
│ :9001 │ │ :9002 │ │ :8100 │
└──────────┬──────────┘ └───────────┬─────────┘ └──────────┬──────────┘
│ │ │
│ full-page redirect │ identity token exchange │
└─────────────────────────────►│────────────────────────────►│
│ │
│ redirect w/ auth code │
│◄────────────────────────────┘
│
▼
┌──────────────────┐
│ TiruPay Frontend │
│ :5173 │
└──────────────────┘FitnessQuasar's own frontend never talks to TiruPay directly — every interaction with TiruPay is brokered by FitnessQuasar's backend, which holds the TiruPay service credentials. The browser is only ever handed off via redirects.
Prerequisites & environment variables
Copy example.env to .env and fill in the values described below. All of them come from your TiruPay Service configuration.
| Variable | Where it comes from |
|---|---|
TIRUPAY_API_URL | The base URL of the TiruPay API you're integrating with. |
TIRUPAY_SERVICE_ID | Your Service ID. |
TIRUPAY_JWT_TOKEN | A Service account API key, see Service Account API Keys — issued by an Admin via POST /admin/users/{user_id}/new_token. Sent as Authorization: Bearer ... on every request to TiruPay. |
TIRUPAY_JWT_SECRET / TIRUPAY_JWT_ALGORITHM | The shared secret configured in the service's Login Information, used for JWT Token Exchange. |
TIRUPAY_FRONTEND_URL | The base URL of the TiruPay frontend the user gets redirected to for login/checkout. |
TIRUPAY_MONTHLY_SUB_ARTICLE_ID / TIRUPAY_ONE_TIME_PASS_ARTICLE_ID | IDs of the Articles you configured in TiruPay for the subscription and the day pass. |
TIRUPAY_UNLIMITED_ACCESS_FEATURE_ID / TIRUPAY_SAUNA_ACCESS_FEATURE_ID | Internal names/IDs of the Features granted by those articles. |
TIRUPAY_DAILY_PASS_BALANCE_TYPE_ID / TIRUPAY_DAILY_PASS_USAGE_CATEGORY_ID | IDs of the Balance type and usage category used to track day passes. |
Never expose the service API key to the frontend
TIRUPAY_JWT_TOKEN authenticates as your Service account and can manage all data in your TiruPay service. It is only ever used in backend code (connectors/tiru.py) and must never be sent to, or read by, the browser.
Step 1 — Modeling customers
Every FitnessQuasar User maps 1:1 to a TiruPay Customer, tracked via a tiru_customer_id column on the User model. The customer is created the first time we need it — either right at registration, or lazily on first TiruPay login if it doesn't exist yet.
crud/users.py creates the TiruPay customer as part of registration:
python
def create_user(session: Session, user_in: UserCreate) -> User:
...
customer_id = create_customer_on_tiru(user)
user.tiru_customer_id = customer_id
session.add(user)
session.commit()
session.refresh(user)
return userconnectors/tiru.py implements the actual API calls:
python
def create_customer_on_tiru(user: User) -> str:
response = requests.post(
f"{TIRUPAY_API_URL}/service/customers/",
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {TIRUPAY_JWT_TOKEN}",
},
json={
"first_name": user.first_name,
"last_name": user.last_name,
"street": user.address,
"city": user.city,
"postal_code": user.postal_code,
"email": user.email,
"ext_invoicing_id": str(user.id),
"locale": "de",
"is_company": False,
"service_id": TIRUPAY_SERVICE_ID,
"country_code": "DE",
},
)
if response.status_code != 201:
raise Exception(f"Failed to create customer on TiruPay: {response.text}")
return response.json()["id"]ext_invoicing_id
ext_invoicing_id is your own accounting-system reference for this customer — only relevant if you're not using TiruPay's built-in invoicing.
update_customer_on_tiru mirrors profile edits (PATCH /users/me) back to TiruPay via crud/users.py: update_user, keeping the TiruPay customer record in sync whenever the local profile changes.
Step 2 — Logging users into TiruPay (JWT Token Exchange)
Members interact with TiruPay itself for two things: finishing a checkout, and viewing/managing their subscription. Both require the user to be logged in on the TiruPay side too — without asking them to create a second account. FitnessQuasar achieves this with JWT Token Exchange.
routes/payments.py's /payments/tirupay-login endpoint is the bridge:
python
@router.get("/tirupay-login")
async def tiru_login(
request: Request,
session: Session = Depends(get_session),
redirect: Optional[str] = Query(default=None),
access_token: Optional[str] = Cookie(default=None, alias="fitness_token"),
):
...
if not access_token:
return RedirectResponse(url=frontend_login_url, status_code=status.HTTP_302_FOUND)
user = get_current_user(access_token, session)
if not user:
return RedirectResponse(url=frontend_login_url, status_code=status.HTTP_302_FOUND)
tiru_jwt = create_tiru_jwt_token(session, user)
code = exchange_our_jwt_for_tiru_auth_code_response(tiru_jwt)
tiru_frontend = f"{TIRUPAY_FRONTEND_URL}/user/{TIRUPAY_SERVICE_ID}/provisioning"
tiru_frontend_login_with_authcode = add_params_to_url(
tiru_frontend, {"redirect": redirect or tiru_frontend_dashboard, "code": code}
)
return RedirectResponse(url=tiru_frontend_login_with_authcode)It first resolves the FitnessQuasar access token — from the fitness_token cookie, an Authorization header, or an access_token query parameter — and if none is found, sends the browser to FitnessQuasar's own login page. Once it has a valid, logged-in User, it performs the token exchange:
python
def create_tiru_jwt_token(session: Session, user: User) -> str:
if not user.tiru_customer_id:
user.tiru_customer_id = create_customer_on_tiru(user)
session.add(user)
session.commit()
session.refresh(user)
payload = {
"sub": str(user.id),
"email": user.email,
"first_name": user.first_name,
"last_name": user.last_name,
"customer_ids": [user.tiru_customer_id],
}
return jwt.encode(payload, TIRUPAY_JWT_SECRET, algorithm=TIRUPAY_JWT_ALGORITHM)python
def exchange_our_jwt_for_tiru_auth_code_response(jwt: str) -> str:
response = requests.post(
f"{TIRUPAY_API_URL}/service/identity/token/exchange",
headers={"Authorization": f"Bearer {TIRUPAY_JWT_TOKEN}", ...},
json={"token": jwt, "service_id": TIRUPAY_SERVICE_ID},
)
...
return response.json()["code"]This is exactly the flow documented in JWT Token Exchange:
- FitnessQuasar signs a JWT with the shared
TIRUPAY_JWT_SECRET, containingsub,email,first_name,last_name, andcustomer_ids(linking the exchange to the customer created in Step 1). - It calls
POST /service/identity/token/exchangeand receives a short-lived authcode. - It redirects the browser to
{TIRUPAY_FRONTEND_URL}/user/{service_id}/provisioning?code=...&redirect=.... - The TiruPay frontend exchanges the code for a real TiruPay session and lands the user on
redirect(either back at a dashboard, or — as we'll see next — directly into a checkout).
Always exchange the JWT on the backend
The code comment in routes/payments.py says it plainly: "always perform this on the backend and NEVER on the frontend!" TIRUPAY_JWT_TOKEN is required to call /service/identity/token/exchange, and it must never reach browser-side code.
On the frontend, AuthContext.tsx mirrors the FitnessQuasar token into a fitness_token cookie (in addition to localStorage) whenever a user logs in. This lets /payments/tirupay-login pick up the session from the cookie automatically when TiruPay redirects the browser back here (for example if a not-yet-logged-in user's checkout session expires) — no token needs to be threaded through query parameters in that case.
Step 3 — Selling articles: orders & checkout sessions
Both the monthly subscription and the day pass are modeled in TiruPay as Articles — their IDs live in TIRUPAY_MONTHLY_SUB_ARTICLE_ID and TIRUPAY_ONE_TIME_PASS_ARTICLE_ID. Buying either one follows the Service-Initiated Flow: the backend creates the order and checkout session, then hands the browser off to TiruPay to complete payment.
connectors/tiru.py:
python
def create_order(tiru_customer_id: str, items: list[dict]) -> str:
response = requests.post(
f"{TIRUPAY_API_URL}/service/orders/",
headers={"Authorization": f"Bearer {TIRUPAY_JWT_TOKEN}", ...},
json={
"service_id": TIRUPAY_SERVICE_ID,
"customer_id": tiru_customer_id,
"items": items,
"valid_till": (datetime.datetime.now() + timedelta(hours=2)).isoformat(),
},
)
...
return response.json()["id"]
def create_checkout_session(order_id, final_redirect_url, partner=None, checkout_mode=None) -> str:
response = requests.post(
f"{TIRUPAY_API_URL}/service/orders/{order_id}/checkout-session",
headers={"Authorization": f"Bearer {TIRUPAY_JWT_TOKEN}", ...},
json={"final_redirect_url": final_redirect_url, ...},
)
...
return response.json()["checkout_url"]valid_till is per-order, not a TiruPay default
FitnessQuasar explicitly sets valid_till to 2 hours from now. Left unset, TiruPay defaults draft orders to a 14-day expiration — see Draft Expiration.
routes/users.py ties this together behind /users/subscribe and /users/buy-passes, both built on a shared helper:
python
def _build_checkout_response(current_user: User, access_token: str, article_id: str) -> dict:
order_id = create_order(
tiru_customer_id=current_user.tiru_customer_id,
items=[{"article_id": article_id, "quantity": "1.00"}],
)
redirect_url = create_checkout_session(
order_id=order_id,
final_redirect_url=OUR_FRONTEND_URL,
)
redirect_url_without_prefix = get_url_without_prefix(redirect_url)
our_redirect_url = add_params_to_url(
"http://localhost:9002/payments/tirupay-login",
{"access_token": access_token, "redirect": redirect_url_without_prefix},
)
return {
"redirect_url": redirect_url,
"our_redirect_url": our_redirect_url,
"redirect_url_without_prefix": redirect_url_without_prefix,
}Note that the checkout_url returned by TiruPay is not redirected to directly. It's wrapped through FitnessQuasar's own /payments/tirupay-login bridge first (our_redirect_url), passing the checkout URL as the redirect query parameter. This performs the exact JWT Token Exchange from Step 2 before continuing on to checkout — so the browser arrives at the TiruPay-hosted checkout page already authenticated as the right TiruPay user, rather than as an anonymous guest.
The frontend then simply full-page-redirects to our_redirect_url:
tsx
async function handleSubscribe() {
const { our_redirect_url } = await subscribe(token)
window.location.href = our_redirect_url
}A plain full navigation (not client-side routing) is required here, because the destination is a different origin — first FitnessQuasar's own backend, then TiruPay's frontend.
Step 4 — Checking entitlements: Features & Balances
Once an order completes, TiruPay activates whatever the purchased article grants. FitnessQuasar checks this in two different ways, matching the two entitlement mechanisms TiruPay provides:
- Features for the unlimited membership and sauna add-on — a boolean-ish flag: "a boolean is true if the quantity is 1, and false if it is 0".
- Balances for day passes — a consumable counter that gets decremented each time a pass is used.
Features
python
def get_features_for_customer(tiru_customer_id: str | None) -> dict:
response = requests.get(
f"{TIRUPAY_API_URL}/service/customers/{tiru_customer_id}/features/",
headers={"Authorization": f"Bearer {TIRUPAY_JWT_TOKEN}", ...},
)
...
return response.json()Used in routes/users.py's _get_user_details (which powers the /users/{id}/details endpoint the dashboard reads) and in routes/qr.py's entry check:
python
if features := get_features_for_customer(user.tiru_customer_id):
for feature in features:
if (
feature.get("feature_id") == TIRUPAY_UNLIMITED_ACCESS_FEATURE_ID
and feature.get("quantity") == 1
):
return QRVerifyResponse(valid=True, detail="Access granted (unlimited access)", ...)A member with the unlimited_access feature is let in immediately, without touching any balance.
Balances
Day passes are tracked as a Balance of a configured TIRUPAY_DAILY_PASS_BALANCE_TYPE_ID:
python
def get_balance_for_customer_and_type(tiru_customer_id: str, balance_type: str) -> dict | None:
response = requests.get(
f"{TIRUPAY_API_URL}/service/balances/items",
headers={"Authorization": f"Bearer {TIRUPAY_JWT_TOKEN}", ...},
params={
"customer_ids": [tiru_customer_id],
"service_ids": [TIRUPAY_SERVICE_ID],
"balance_types": [balance_type],
},
)
..._get_user_details reads current_balance from this to show "day passes left" on the dashboard. routes/qr.py's gym-entry check goes further and actually consumes a pass on entry:
python
if Decimal(balance.get("current_balance", 0)) > 0:
balance_usage = create_balance_usage(
balance_id=balance["id"],
items=[{"usage_category_id": TIRUPAY_DAILY_PASS_USAGE_CATEGORY_ID, "units_used": 1}],
description=f"Gym entry on {datetime.now().strftime('%Y-%m-%d')}",
title="Gym entry",
)create_balance_usage posts to /service/balances/usages/. TiruPay checks whether the balance has enough units left and responds with 402 if not — FitnessQuasar treats that as "access denied" rather than a hard error:
python
if response.status_code == 402:
raise Exception(f"Insufficient balance on TiruPay: {response.text}")Before consuming a pass, verify_qr also calls get_balance_usages_for_balance to check whether a pass was already used today, so a member can re-enter the gym on the same day without being charged a second pass:
python
usages = get_balance_usages_for_balance(
balance["id"], usage_item_category_ids=[TIRUPAY_DAILY_PASS_USAGE_CATEGORY_ID], limit=1
)
if usages and datetime.fromisoformat(usages[0]["created_at"]).date() == datetime.now().date():
return QRVerifyResponse(valid=True, detail="Access granted (daily pass already consumed today)", ...)A note from the example's own comments
The code that implements this same-day check flags itself as a simplification: "The current balance check only works for consumable balances and is rather unsecure ..., but fine to use in this case." For a production integration, treat balance usage as the source of truth for "was a pass consumed", not as a substitute for atomic, race-condition-safe entry logic.
Step 5 — Frontend wiring (brief)
The React frontend never calls TiruPay directly — it only talks to the FitnessQuasar backend (frontend/src/lib/api.ts) and follows the redirects the backend hands it:
subscribe()/buyPasses()call/users/subscribe//users/buy-passesand full-page redirect to the returnedour_redirect_url(Step 3).getTiruLoginUrl(token)builds a direct link to/payments/tirupay-login?access_token=..., used by the dashboard's "Manage subscription" button to jump straight into the TiruPay customer portal without starting a new order.AuthContext's cookie mirroring (Step 2) is what lets/payments/tirupay-loginauthenticate the browser even when TiruPay itself redirects back here later, without a token in the URL.
Running the example end-to-end
bash
cp example.env .env
# fill in the TiruPay values described aboveBackend:
bash
uv sync
uv run fastapi run --port 9002Frontend:
bash
cd frontend
bun install
bun run devNext steps for production
This example intentionally keeps things minimal. Before basing a real integration on it, consider:
- Webhooks. FitnessQuasar only reacts to TiruPay state at redirect time — it never learns about a payment failing, a subscription renewing, or a chargeback happening asynchronously. Implement a webhook receiver for
payment_updated,order_updated, andsubscription_updated(verify theX-Signatureheader as shown there) instead of relying only on the customer coming back through your app. - API key rotation. The Service API key (
TIRUPAY_JWT_TOKEN) expires after 180 days by default — see Service Account API Keys. Rotate it before expiry. - Checkout mode. FitnessQuasar lets TiruPay fall back to its checkout defaults.
- Read more: Orders & Subscriptions, Subscriptions, Balance System.