Skip to main content

Card-only invoices

This guide takes a card payment from end to end, split the way it should be split:

  1. Your backend creates a card-only invoice with the raw API. This is the step that fixes the amount, so it needs your secret credentials.
  2. Your backend forwards only the invoiceNo to your frontend.
  3. Your frontend hands the invoiceNo to the browser SDK (@taifapay/payments-js), which renders the card form inside your page.
  4. Your backend confirms the payment from a webhook before fulfilling the order.

The backend examples are Python and Django. The API itself is plain HTTP, so the same calls translate to any stack.

What makes an invoice card-only is one field: "methods": ["card"]. The customer sees a single card form — no M-Pesa, bank or wallet tabs — and pays with Visa or Mastercard. For what the card gateway itself supports, and when card money reaches your float, see Card payments.

Before you start​

  • Card is enabled for your company. Card runs on a gateway Taifa Pay configures for you. Without it a card-only invoice cannot be created — see If card is not enabled.
  • Company credentials. A client_id and client_secret, exchanged for a Bearer token as described in Authentication. Sandbox and production have separate credentials.
  • Identifier letters on your company. They prefix the invoice number; without them invoice creation returns 422.
  • Your site's origin allow-listed for framing. The checkout page can only be embedded by origins Taifa Pay has approved. Give your account manager the origin (for example https://shop.example.com) for each environment, or the iframe will be blocked by the browser.
  • A deposit webhook URL and secret. Card outcomes reach your backend by webhook.

1. Create the card-only invoice​

POST /v1/checkout/invoices (requires a company Bearer token)

curl -X POST https://sandbox.merchants.taifapay.africa/v1/checkout/invoices \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"amount": 1500,
"currency": "KES",
"accountReference": "ORD-1001-1",
"description": "Order #1001 - 2x widget",
"customerName": "Jane Doe",
"customerEmail": "jane@example.com",
"externalId": "order_8f3a",
"methods": ["card"],
"expiresInMinutes": 60
}'
FieldRequiredNotes
methodsyes, for card-onlyExactly ["card"].
amountyes1 to 10,000,000, up to two decimal places. Fixed — the customer cannot change it.
accountReferenceyesYour reference: up to 50 characters — letters, numbers, ., _, -. Joined to your identifier letters it becomes the invoice number (ABC + ORD-1001-1 → ABCORD-1001-1), so it must be unique within your company and cannot be reused, even after the invoice expires. Give every payment attempt its own.
currencynoThree-letter uppercase code. Defaults to KES.
descriptionnoUp to 200 characters. Shown on the page and recorded on the transaction.
customerNamenoUp to 100 characters. Comes back in webhooks as counterPartyName.
customerEmailnoA valid email address. Encrypted at rest.
externalIdnoYour own id, up to 50 characters. Comes back as externalId; defaults to accountReference.
returnUrlnoAn https URL. Only used when the customer opens the link directly — it is ignored when the page is embedded.
expiresInMinutesno1 to 10080. Defaults to 30.

customerPhone is not needed for card — it only pre-fills the M-Pesa prompt. Unknown fields are rejected with 400, so there is no cardOnly flag to look for: methods is the switch.

Response:

{
"message": "Invoice created",
"invoice": {
"transactionId": "a3f1c2d4-5e6b-7a8c-9d0e-1f2a3b4c5d6e",
"checkoutUrl": "https://pay.taifapay.africa/pay/ABCORD-1001-1",
"invoiceNo": "ABCORD-1001-1",
"amount": 1500,
"currency": "KES",
"status": "open",
"methods": ["card"],
"expiresAt": "2026-09-21T13:30:00.000Z"
}
}

Store the transactionId against your order: it is created with the invoice and is the one id that webhooks and polling report on for its whole life. The invoiceNo is what you forward to the browser.

An empty list is not card-only

"methods": [] is treated exactly like leaving methods out — the invoice offers every method available to your company, including wallet, which is always on. Name card explicitly.

If card is not enabled​

When you ask for card alongside other methods, an unavailable method is quietly dropped from the invoice. Card-only leaves nothing to drop, so the request fails instead:

StatusMessageWhat to do
422No payment gateways are configured, so no checkout methods can be offered.Card is not enabled or active for your company. Ask your account manager to enable it.
422An invoice already exists for ABCORD-1001-1.That accountReference has been used. Choose a new one.
422Your company has no identifierLetters configured; …Contact Taifa Pay support.
400Validation messages, e.g. returnUrl must be an https URLFix the field named in the message.
401—Your access token is missing or expired. Fetch a new one and retry once.

2. Forward the invoiceNo to your frontend (Django)​

Wrap the call in a view of your own. The browser asks to pay; your backend decides the amount from your own order, creates the invoice, and returns the invoiceNo — nothing else.

Start with your credentials, read from the environment:

# settings.py
TAIFA_API_BASE = os.environ.get("TAIFA_API_BASE", "https://sandbox.merchants.taifapay.africa/v1")
TAIFA_CLIENT_ID = os.environ["TAIFA_CLIENT_ID"]
TAIFA_CLIENT_SECRET = os.environ["TAIFA_CLIENT_SECRET"]
TAIFA_WEBHOOK_SECRET = os.environ["TAIFA_WEBHOOK_SECRET"]

A small client module. It caches the access token in Django's cache (shared between workers when you use Redis or Memcached) and retries once if the token expired mid-flight, as the Authentication guide advises:

# payments/taifa.py
import requests
from django.conf import settings
from django.core.cache import cache

TOKEN_KEY = "taifa:access-token"


def _token():
token = cache.get(TOKEN_KEY)
if token:
return token

res = requests.post(
f"{settings.TAIFA_API_BASE}/auth/token",
auth=(settings.TAIFA_CLIENT_ID, settings.TAIFA_CLIENT_SECRET), # HTTP Basic
json={"grant_type": "client_credentials"},
timeout=15,
)
res.raise_for_status()
body = res.json()

# Tokens last about an hour; refresh a minute early.
cache.set(TOKEN_KEY, body["access_token"], int(body["expires_in"]) - 60)
return body["access_token"]


def _request(method, path, **kwargs):
for attempt in (1, 2):
res = requests.request(
method,
f"{settings.TAIFA_API_BASE}{path}",
headers={"Authorization": f"Bearer {_token()}"},
timeout=30,
**kwargs,
)
if res.status_code == 401 and attempt == 1:
cache.delete(TOKEN_KEY) # expired mid-flight: fetch a fresh token and retry once
continue
res.raise_for_status()
return res.json()


def create_card_invoice(*, amount, account_reference, description, external_id):
body = _request(
"POST",
"/checkout/invoices",
json={
"amount": float(amount), # a Decimal is not JSON serializable
"accountReference": account_reference,
"description": description,
"externalId": external_id,
"methods": ["card"],
"expiresInMinutes": 60,
},
)
return body["invoice"]


def get_transaction(transaction_id):
return _request("GET", f"/transactions/{transaction_id}")

The view. It assumes an Order model with status, total, number, payment_attempts, invoice_no and transaction_id fields; rename to suit.

# payments/views.py
import logging

import requests
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, JsonResponse
from django.shortcuts import get_object_or_404
from django.views.decorators.http import require_POST

from . import taifa
from .models import Order

logger = logging.getLogger(__name__)


@login_required
@require_POST
def start_card_payment(request, order_id):
order = get_object_or_404(Order, pk=order_id, user=request.user)
if order.status == "paid":
return HttpResponse(status=409)

# A reference can never be reused, so every attempt gets its own.
# Use F() or select_for_update() here if a double-click could race.
order.payment_attempts += 1
order.save(update_fields=["payment_attempts"])

try:
invoice = taifa.create_card_invoice(
amount=order.total, # from your order, never from the request
account_reference=f"ORD-{order.number}-{order.payment_attempts}",
description=f"Order #{order.number}",
external_id=str(order.pk),
)
except requests.RequestException:
logger.exception("Taifa invoice creation failed for order %s", order.pk)
return JsonResponse({"error": "Could not start the payment"}, status=502)

order.invoice_no = invoice["invoiceNo"]
order.transaction_id = invoice["transactionId"]
order.save(update_fields=["invoice_no", "transaction_id"])

return JsonResponse({"invoiceNo": invoice["invoiceNo"]}) # the only thing the browser gets
# payments/urls.py
from django.urls import path

from . import views, webhooks

urlpatterns = [
path("api/orders/<int:order_id>/pay/", views.start_card_payment),
path("webhooks/taifa/", webhooks.taifa_webhook),
]
Never send the browser your token, your secret or the amount decision

Invoice creation sets what the customer owes, so it must stay on your server — otherwise a customer could mint a KES 1 invoice for a KES 1,500 order. The invoiceNo is public by design; the token and client_secret are not.

3. Show the card form in your page (frontend)​

Install the browser SDK:

npm install @taifapay/payments-js

Ask your backend for the invoiceNo, then mount the checkout into an element. Django rejects a POST without its CSRF token, so send it in the X-CSRFToken header:

import { mountCheckout } from '@taifapay/payments-js';

const { invoiceNo } = await fetch(`/api/orders/${orderId}/pay/`, {
method: 'POST',
headers: { 'X-CSRFToken': getCookie('csrftoken') }, // the helper from Django's CSRF docs
}).then((r) => r.json());

const checkout = mountCheckout('#pay', {
invoiceNo,
host: 'https://sandbox-pay.taifapay.africa', // sandbox; omit in production
onSuccess: () => {
checkout.unmount();
showPaymentPending(orderId); // then wait for your backend to mark the order paid
},
onFailure: ({ message }) => {
// A decline. The customer already sees it in the form and can retry.
console.warn('Card attempt failed:', message);
},
onExpired: () => {
checkout.unmount();
offerNewPayment(orderId); // create a fresh invoice
},
});

If your pages are Django templates and you have no bundler, the script-tag build does the same thing, and {{ csrf_token }} saves reading the cookie:

<div id="pay"></div>
<script src="https://unpkg.com/@taifapay/payments-js"></script>
<script>
fetch('/api/orders/{{ order.pk }}/pay/', {
method: 'POST',
headers: { 'X-CSRFToken': '{{ csrf_token }}' },
})
.then((r) => r.json())
.then(({ invoiceNo }) => {
TaifaPay.mountCheckout('#pay', {
invoiceNo,
host: 'https://sandbox-pay.taifapay.africa', // omit in production
onSuccess: () => { window.location.href = '{% url "order_pending" order.pk %}'; },
});
});
</script>

The SDK renders the hosted checkout in an iframe and sizes it to fit. Card details are typed into that iframe on Taifa Pay's own origin and go straight to the acquirer — they never touch your page or your servers.

What the callbacks mean for a card-only invoice​

CallbackFires whenWhat to do
onReadyThe page has loaded.Hide your own spinner.
onSuccess({ method, receiptNumber })The card was approved. method is "card". It also fires straight away, with no method or receiptNumber, if the customer opens an invoice that is already paid.Treat it as a UX signal: swap the form for a "confirming your payment" state. Do not fulfil the order from it — see step 4.
onFailure({ message })A card attempt was declined, for example Card declined: <acquirer message>.Do nothing drastic. The invoice is still payable and the form is still showing the message, so the customer can retry. Never cancel the order here.
onExpiredThe link can no longer be paid.Terminal. Create a new invoice.
onCancel—Present in the SDK, but the checkout page does not send it today. Do not build a flow around it.

Things that catch people out​

  • The invoice decides the methods, not the SDK. mountCheckout has no option for payment methods. If the form shows anything but card, the invoice was created without methods: ["card"].
  • host must match the environment that created the invoice. A sandbox invoice on the production host is simply not found. Omit host in production; use the sandbox host while testing.
  • Your origin must be allow-listed. If the iframe stays blank and the browser console mentions frame-ancestors, your origin has not been approved for that environment.
  • You own what happens after success. When embedded, the page's Done button does nothing and returnUrl is not used. Navigate or update your UI from onSuccess.
  • invoiceNo, never the URL. Pass the invoice number the API returned, not the checkoutUrl.
  • A 403 from your own view is Django's CSRF check. The browser never sees Taifa Pay's API, so a 403 on /api/orders/…/pay/ means the X-CSRFToken header is missing or wrong. If CSRF_COOKIE_HTTPONLY is on, JavaScript cannot read the cookie — render {{ csrf_token }} into the page instead.

4. Confirm the payment (backend)​

onSuccess only proves the customer's browser saw an approval. Fulfil from your backend, on a webhook or a poll.

A card payment resolves while the customer is still on the page, but the money reaches your float later, when the acquirer settles it. A card-only invoice therefore moves through these states:

MomentInvoice statusTransaction statusWebhook
Created, not yet paidopenPENDING—
Card declinedopen — the customer can retryPENDING—
Card approvedcompleteAWAITING_SETTLEMENTtransaction.completed with status: "AWAITING_SETTLEMENT"
Acquirer has settledcompleteCOMPLETEDtransaction.settled, and transaction.completed with status: "COMPLETED" for existing integrations
Expired unpaidexpiredFAILEDtransaction.failed

Settlement takes hours, not minutes, and follows the acquirer's cycle — ask your account manager for your timetable. A payment still AWAITING_SETTLEMENT after 30 days is no longer checked automatically; contact Taifa Pay support.

Webhooks​

A card payment sends transaction.completed when the card is approved, and transaction.settled when the acquirer settles it. Settlement also still sends a second transaction.completed with status: "COMPLETED", which older integrations key on; new integrations should ignore it and use transaction.settled. The settled event is subscribable as deposit.transaction.settled. This is the approval:

{
"id": "0b0e9a3c-8f1d-4a7b-b1a2-3c4d5e6f7a8b",
"eventType": "transaction.completed",
"timestamp": "2026-09-21T12:41:07.000Z",
"data": {
"id": "a3f1c2d4-5e6b-7a8c-9d0e-1f2a3b4c5d6e",
"amount": 1500,
"currency": "KES",
"status": "AWAITING_SETTLEMENT",
"invoiceNo": "ABCORD-1001-1",
"accountReference": "ORD-1001-1",
"externalId": "order_8f3a",
"counterPartyName": "Jane Doe",
"receiptNumber": "123456789012",
"resultCode": "0",
"resultDesc": "Card payment captured",
"errorMessage": ""
},
"metadata": {}
}

The payload is abridged. The fields to key on:

  • data.id — the transactionId returned when you created the invoice.
  • data.status — AWAITING_SETTLEMENT, then COMPLETED.
  • data.externalId — the id you passed at creation, handy for finding your order.
  • data.receiptNumber — the acquirer's receipt. It is what a cardholder's bank recognises in a dispute, so store it against your order.

A view that verifies the signature, then moves the order along. Django's request.body is the raw payload, which is exactly what the HMAC must be computed over:

# payments/webhooks.py
import hashlib
import hmac
import json

from django.conf import settings
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST

from .models import Order


def _signature_ok(request):
header = request.headers.get("X-Webhook-Signature", "")
received = header.split("=", 1)[-1] # drop the "sha512=" prefix
expected = hmac.new(
settings.TAIFA_WEBHOOK_SECRET.encode(), request.body, hashlib.sha512
).hexdigest()
return hmac.compare_digest(received.encode(), expected.encode())


@csrf_exempt # Taifa Pay is not a browser, so it has no CSRF token
@require_POST
def taifa_webhook(request):
if not _signature_ok(request):
return HttpResponse(status=401)

event = json.loads(request.body)
data = event.get("data", {})

if event["eventType"] == "transaction.completed":
if data["status"] == "AWAITING_SETTLEMENT":
# Idempotent: a redelivery finds nothing still "pending" and changes nothing.
Order.objects.filter(transaction_id=data["id"], status="pending").update(
status="paid", card_receipt=data["receiptNumber"]
)
# The COMPLETED copy of this event is ignored; settlement arrives as its own event below.
elif event["eventType"] == "transaction.settled":
Order.objects.filter(transaction_id=data["id"]).update(settled=True)
elif event["eventType"] == "transaction.failed":
Order.objects.filter(transaction_id=data["id"], status="pending").update(
status="payment_expired"
)

return HttpResponse(status=200) # webhook.test and any other event are simply acknowledged
De-duplicate on id and status

One card invoice sends transaction.completed twice — once at approval, once at settlement, the second kept for older integrations — and then transaction.settled. If you de-duplicate on data.id plus eventType, the second transaction.completed looks like a repeat and is dropped. De-duplicate on data.id plus eventType plus data.status, and make each step idempotent, as the filter(..., status="pending") above does.

Register the exact URL Django serves

Deliveries do not follow redirects. Django's APPEND_SLASH answers /webhooks/taifa with a 301 to /webhooks/taifa/, and SECURE_SSL_REDIRECT does the same for http:// — either one makes every delivery fail. Register the final URL, https://shop.example.com/webhooks/taifa/, trailing slash included.

Signature headers, retries and the test endpoint are covered in Webhooks. A failing webhook endpoint never undoes a payment — it is logged and skipped — so keep a poll as a backstop.

Polling​

Your browser has no token, so poll from your backend, or have your frontend poll your endpoint for the order's status. GET /v1/transactions/{transactionId} returns the same fields as the webhook's data, flat:

curl https://sandbox.merchants.taifapay.africa/v1/transactions/a3f1c2d4-5e6b-7a8c-9d0e-1f2a3b4c5d6e \
-H "Authorization: Bearer $ACCESS_TOKEN"
{
"id": "a3f1c2d4-5e6b-7a8c-9d0e-1f2a3b4c5d6e",
"amount": 1500,
"currency": "KES",
"status": "AWAITING_SETTLEMENT",
"invoiceNo": "ABCORD-1001-1",
"receiptNumber": "123456789012"
}

With the client module above that is taifa.get_transaction(order.transaction_id). To look at the invoice itself, GET /v1/checkout/invoices/ABCORD-1001-1. An invoice reading status: "open" with selectedMethod: "card" means the customer has tried a card and has not yet succeeded.

What to do in each state​

You seeIt meansYou should
PENDING, invoice openNot paid yet.Wait. Do not cancel the order on a decline — the customer can try again.
AWAITING_SETTLEMENTThe card was charged and the invoice is complete; the cash has not cleared to you yet.Treat the order as paid, fulfil it, and store receiptNumber. The money is not spendable yet.
COMPLETEDThe acquirer has settled it into your float.The funds are yours to spend or settle.
FAILEDThe link expired unpaid.Create a new invoice with a new accountReference if the customer still wants to pay.
Not the same as pending settlement

AWAITING_SETTLEMENT is card money coming in that you cannot spend yet. pending_settlement is the opposite — money you can spend, held behind a settlement request you raised. Keep them apart in any status filter.

Declines, retries and expiry​

  • A decline is not a failure. The customer sees Card declined: <acquirer message> above the Pay button, and onFailure fires in your page. They can correct the details or try another card. The invoice stays open, nothing is posted to your account, and no webhook is sent.
  • Only Visa and Mastercard. Any other card is rejected with Only Visa and Mastercard are supported. As card is the only method, the customer has no other way to pay on this invoice. Say so before they reach the form, or offer ["card", "mpesa_stk"] instead.
  • Attempts are rate-limited. The checkout page throttles repeated card attempts from one network address, to slow down card-testing. A customer who retries rapidly may be asked to wait a moment.
  • Expiry is final. An invoice past expiresAt cannot be paid and onExpired fires. The transaction is marked FAILED a few minutes later and you are sent transaction.failed. Because the accountReference cannot be reused, raise a replacement under a new one — this is why the view above increments payment_attempts. For an embedded form the customer is on the page now, so the default 30 minutes is usually enough; expiresInMinutes accepts up to 10080 (seven days) for links sent by message.
  • A paid invoice cannot be paid twice. Reopening it shows This invoice has already been paid. and no second charge is attempted.

Skip step 3. Send the customer the checkoutUrl from the invoice by SMS, email or WhatsApp, or redirect to it from your site. The page is the same card form on its own screen, and returnUrl decides where its Done button goes. Everything in steps 1, 2 and 4 stays the same. returnUrl is navigation, not proof: confirm with the webhook or a poll before you release anything.

Testing before you go live​

Use the sandbox API host and the sandbox checkout host, with the sandbox card credentials Taifa Pay issues alongside your card gateway. Check each of these:

  1. Create a card-only invoice and confirm the form shows only card — no other tabs.
  2. Send a test delivery with POST /v1/webhooks/test and confirm your view answers 200 with no redirect in between.
  3. Pay an invoice. Confirm onSuccess fires, the invoice is complete, the transaction is AWAITING_SETTLEMENT, your webhook arrives, and receiptNumber reaches your order record.
  4. Confirm your view handles transaction.settled once the payment settles, and ignores the second transaction.completed rather than treating it as a new payment.
  5. Use a card that declines. Confirm onFailure fires, your order is not cancelled, and the customer can retry in the same form.
  6. Let an invoice expire. Confirm onExpired fires, you receive transaction.failed, and you can raise a replacement under a new accountReference.
  7. Load the page from an origin that is not allow-listed and confirm you know what a blocked iframe looks like.

Where to go next​