Chaime Webhook Integration
Connect external applications to Chaime. Redirect users to M-Pesa membership checkouts, receive signed event notifications, and upgrade accounts automatically.
1. Overview
Chaime processes M-Pesa STK push payments directly in Kenyan Shillings (KES). When a payment succeeds, Chaime dispatches an HTTP POST request signed with HMAC SHA-256 to your configured endpoint.
2. Deep-Link Parameters
Deep-linking allows your application to route customers straight into Chaime's checkout flow with prefilled context:
- 1. Instant 1-Click Checkout: Passing
tierauto-selects the plan and immediately opens the checkout modal, preventing customer drop-off. - 2. Accurate Account Reconciliation: Passing
external_idbinds your platform's internal user ID to the session. Chaime returns this ID indata.metadata.externalIdin all webhooks, eliminating fragile email-matching logic if a user pays with a different M-Pesa email. - 3. Seamless User Return: Supplying
redirect_urlroutes subscribers straight back into your app, onboarding flow, or premium dashboard once payment succeeds. - 4. Reduced Mobile Friction: Pre-filling
email,phone, andnameturns checkout into a fast 1-tap M-Pesa STK push prompt.
| Parameter | Type | Description |
|---|---|---|
| tier | string | Tier slug or name. Selects tier and auto-opens checkout. |
| interval | string | Optional billing cycle: monthly (default) or yearly. Pre-selects cycle in checkout. |
| string | Customer email address. Pre-fills and locks identity. | |
| external_id | string | Your user ID. Returned in webhook payload under metadata.externalId. |
| redirect_url | string | Return URL after payment. Falls back to creator dashboard Default Return URL. |
| name | string | Optional customer full name. |
| phone | string | Optional M-Pesa phone number (e.g. 0712345678). |
3. Pricing, Fees & Dashboard Metrics
Chaime uses a transparent, creator-absorbed fee structure. Your subscribers are never surprised with checkout fees or markups:
If your tier price is KES 200, the subscriber is charged exactly KES 200 via M-Pesa. No transaction surcharge is added to the checkout total.
Chaime deducts an 8% platform fee (e.g. KES 16 on a KES 200 charge) upon settlement. The remaining KES 184 is credited directly to your bank or M-Pesa account.
The Chaime Creator Dashboard tracks both cumulative earnings and recurring run rate across several key metrics:
The total net revenue earned and settled to your payout account from all completed membership transactions (status = SUCCESS). This matches your main dashboard balance.
Normalized Monthly Recurring Revenue from active members. Yearly subscriptions are divided by 12 (Monthly + Yearly/12), showing your predictable monthly baseline.
Count of unique paying supporters whose membership status is currently ACTIVE and whose access period has not expired.
The timestamp when the current term ends. Subscriptions auto-extend on renewal and fire subscription.renewed webhooks to your server.
4. Signature Verification
Chaime signs request bodies using HMAC SHA-256 with your signing secret. Verify signatures using the raw, unparsed request payload:
Verification Steps:
- Read raw body string before JSON parsing.
- Compute HMAC SHA-256 using your secret key.
- Format as
sha256=<hash>. - Compare with
Chaime-Signatureheader using constant-time comparison.
5. Event Catalog & Payload Types
Inspect sample JSON payloads or copy production-ready TypeScript definitions:
{
"id": "evt_1732205400000_a1b2c3d4",
"event": "subscription.activated",
"createdAt": "2026-11-21T18:30:00.000Z",
"data": {
"subscriptionId": "sub_cm7890abcdef",
"customer": {
"email": "[email protected]",
"name": "Alex Kim",
"phone": "254712345678"
},
"tier": {
"id": "tier_cm123456",
"name": "Pro Tier",
"priceKes": 200,
"interval": "MONTHLY"
},
"period": {
"start": "2026-11-21T18:30:00.000Z",
"end": "2026-12-21T18:30:00.000Z"
},
"metadata": {
"externalId": "usr_99812"
}
}
}| Field | Type | Description |
|---|---|---|
| id | string | Unique event delivery ID (evt_...). Store this to guarantee idempotency. |
| event | ChaimeEventType | subscription.activated, subscription.renewed, or subscription.canceled. |
| createdAt | string (ISO 8601) | UTC timestamp when Chaime generated the webhook event. |
| data.subscriptionId | string | Unique Chaime subscription ID (sub_...) for this member. |
| data.customer | ChaimeCustomer | Contains subscriber email, name, and optional phone. |
| data.tier | ChaimeTier | Contains tier id, name, priceKes, and interval (MONTHLY | YEARLY). |
| data.period | ChaimePeriod | start and end UTC timestamps marking the active membership duration. |
| data.metadata | Record<string, string> | Custom parameters forwarded from deep-link checkout (e.g. externalId, userId). |
| data.canceledAt | string? | Present only on subscription.canceled. |
| data.reason | string? | Cancellation reason (EXPIRED_PERIOD, USER_REQUEST). |
6. Expected Endpoint Response
To acknowledge receipt of a webhook delivery, your endpoint must return an HTTP 2xx status code within 8 seconds. Chaime inspects the response status and records delivery telemetry in your dashboard.
Return immediately upon verifying the signature and queuing the event:
"received": true
}
If you receive an event ID you have already processed, acknowledge with 200:
"received": true,
"duplicate": true
}
- 8-Second Timeout: Chaime aborts the connection if your server takes longer than 8 seconds to respond. For asynchronous tasks (sending emails, provisioning accounts), return HTTP 200 first and perform the task in the background.
- Dashboard Telemetry: Non-2xx responses (e.g. 401 for bad signature, 500 for server errors) are logged with HTTP status, duration, and response body in your Dashboard Webhook History.
- Standard Error Codes: Return
401 Unauthorizedfor signature failures, and400 Bad Requestfor malformed JSON bodies.
7. Implementation Code
Ready-to-use handlers with signature verification and timing-safe equality:
import crypto from "node:crypto";
import { NextResponse } from "next/server";
import type { ChaimeWebhookPayload } from "@/types/chaime-webhooks";
const WEBHOOK_SECRET = process.env.CHAIME_WEBHOOK_SECRET!;
export async function POST(req: Request) {
try {
const rawBody = await req.text();
const signature = req.headers.get("chaime-signature") || "";
const expected = "sha256=" + crypto
.createHmac("sha256", WEBHOOK_SECRET)
.update(rawBody)
.digest("hex");
const isValid =
signature.length === expected.length &&
crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
if (!isValid) {
return NextResponse.json({ error: "Invalid signature" }, { status: 401 });
}
const payload = JSON.parse(rawBody) as ChaimeWebhookPayload;
if (payload.event === "subscription.activated") {
const { customer, tier, metadata } = payload.data;
const userId = metadata?.externalId;
const email = customer?.email;
// Update customer in database:
// await db.user.update({
// where: userId ? { id: userId } : { email },
// data: { plan: tier.name, isSubscribed: true }
// });
}
return NextResponse.json({ received: true }, { status: 200 });
} catch (error) {
return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
}
}8. Testing & Developer Tools
Test your webhook integration safely without waiting for real customer payments:
Inspect live webhook deliveries directly in your browser without writing any code:
- Navigate to webhook.site to copy your unique HTTPS URL.
- Paste the URL into your Chaime Dashboard (Memberships → Webhooks) and save.
- Click Test Ping in Chaime Dashboard.
- Watch headers (
Chaime-Signature,Chaime-Event) and payload arrive instantly.
To receive Chaime webhooks on your local development server (e.g. localhost:3000), expose your port using a tunnel:
# Using ngrok
ngrok http 3000
# Or using Cloudflare Tunnels
cloudflared tunnel --url http://localhost:3000
Copy the generated public HTTPS URL (e.g. https://xxxx.ngrok-free.app/api/webhooks/chaime) and paste it into your Chaime Webhook configuration.
You can test connectivity and signature validation at any time by clicking the Test Ping button inside your Chaime Webhook settings. Chaime will deliver a signed test.ping event and report the HTTP status code received.
9. AI Integration Spec
Copy this concise specification and paste it directly into Cursor, Claude, or ChatGPT to generate webhook handlers in any programming language (Go, Rust, Ruby, C#):