/Webhooks API

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.

MethodPOST
Signature HeaderChaime-Signature: sha256=<hex>
Event HeaderChaime-Event: <event_name>
Timeout8 seconds (expecting HTTP 200)

2. Deep-Link Parameters

Deep-linking allows your application to route customers straight into Chaime's checkout flow with prefilled context:

https://chaime.co.ke/:username/membership?tier=pro&interval=yearly&[email protected]&external_id=123&redirect_url=https://app.com/dashboard
Why You Should Use Query Parameters
  • 1. Instant 1-Click Checkout: Passing tier auto-selects the plan and immediately opens the checkout modal, preventing customer drop-off.
  • 2. Accurate Account Reconciliation: Passing external_id binds your platform's internal user ID to the session. Chaime returns this ID in data.metadata.externalId in all webhooks, eliminating fragile email-matching logic if a user pays with a different M-Pesa email.
  • 3. Seamless User Return: Supplying redirect_url routes subscribers straight back into your app, onboarding flow, or premium dashboard once payment succeeds.
  • 4. Reduced Mobile Friction: Pre-filling email, phone, and name turns checkout into a fast 1-tap M-Pesa STK push prompt.
ParameterTypeDescription
tierstringTier slug or name. Selects tier and auto-opens checkout.
intervalstringOptional billing cycle: monthly (default) or yearly. Pre-selects cycle in checkout.
emailstringCustomer email address. Pre-fills and locks identity.
external_idstringYour user ID. Returned in webhook payload under metadata.externalId.
redirect_urlstringReturn URL after payment. Falls back to creator dashboard Default Return URL.
namestringOptional customer full name.
phonestringOptional 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:

Subscriber Pays Exact Price

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.

Creator Net Payout (8% Fee)

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.

Understanding Membership Dashboard Metrics

The Chaime Creator Dashboard tracks both cumulative earnings and recurring run rate across several key metrics:

Total EarningsCash Collected

The total net revenue earned and settled to your payout account from all completed membership transactions (status = SUCCESS). This matches your main dashboard balance.

Monthly Revenue (MRR)Run Rate

Normalized Monthly Recurring Revenue from active members. Yearly subscriptions are divided by 12 (Monthly + Yearly/12), showing your predictable monthly baseline.

SubscribersActive

Count of unique paying supporters whose membership status is currently ACTIVE and whose access period has not expired.

Next Renewal DateBilling Cycle

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:

  1. Read raw body string before JSON parsing.
  2. Compute HMAC SHA-256 using your secret key.
  3. Format as sha256=<hash>.
  4. Compare with Chaime-Signature header using constant-time comparison.

5. Event Catalog & Payload Types

Inspect sample JSON payloads or copy production-ready TypeScript definitions:

subscription.activated
{
  "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"
    }
  }
}
Payload Attributes Reference
FieldTypeDescription
idstringUnique event delivery ID (evt_...). Store this to guarantee idempotency.
eventChaimeEventTypesubscription.activated, subscription.renewed, or subscription.canceled.
createdAtstring (ISO 8601)UTC timestamp when Chaime generated the webhook event.
data.subscriptionIdstringUnique Chaime subscription ID (sub_...) for this member.
data.customerChaimeCustomerContains subscriber email, name, and optional phone.
data.tierChaimeTierContains tier id, name, priceKes, and interval (MONTHLY | YEARLY).
data.periodChaimePeriodstart and end UTC timestamps marking the active membership duration.
data.metadataRecord<string, string>Custom parameters forwarded from deep-link checkout (e.g. externalId, userId).
data.canceledAtstring?Present only on subscription.canceled.
data.reasonstring?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.

Success Response (HTTP 200)200 OK

Return immediately upon verifying the signature and queuing the event:

{
  "received": true
}
Idempotent / Duplicate (HTTP 200)200 OK

If you receive an event ID you have already processed, acknowledge with 200:

{
  "received": true,
  "duplicate": true
}
Delivery & Timeout Rules
  • 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 Unauthorized for signature failures, and 400 Bad Request for malformed JSON bodies.

7. Implementation Code

Ready-to-use handlers with signature verification and timing-safe equality:

Next.js Handler
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:

1. Instant Webhook Inspector (Webhook.site)

Inspect live webhook deliveries directly in your browser without writing any code:

  1. Navigate to webhook.site to copy your unique HTTPS URL.
  2. Paste the URL into your Chaime Dashboard (Memberships → Webhooks) and save.
  3. Click Test Ping in Chaime Dashboard.
  4. Watch headers (Chaime-Signature, Chaime-Event) and payload arrive instantly.
2. Local Tunneling (ngrok & Cloudflare)

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.

3. In-Dashboard Test Ping

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#):

# Chaime Webhook & Integration Specification for AI Assistants ## 1. Checkout Deep-Link Format URL: https://chaime.co.ke/:username/membership?tier=:tier&interval=:interval&email=:email&external_id=:userId&redirect_url=:returnUrl Why use query parameters: - `tier`: Instantly opens checkout with the selected plan pre-selected, minimizing cart abandonment. - `interval`: Pre-selects `monthly` or `yearly` billing cycle in the checkout dialog. - `external_id`: Passes your database's internal user ID into the session; returned in `data.metadata.externalId` in webhooks so you can upgrade accounts without fragile email-matching logic. - `redirect_url`: Automatically returns customer back to your application/dashboard after successful payment. - `email`, `name`, `phone`: Pre-populates customer details so checkout is a 1-tap M-Pesa experience. Query Parameters Reference: - `tier`: Tier slug or name (e.g. "pro", "vip"). Auto-selects tier and opens checkout modal. - `interval`: Optional billing cycle ("monthly" or "yearly"). Defaults to "monthly". - `email`: Customer email address. Pre-fills identity and links webhook payload. - `external_id`: Internal platform user ID (e.g. "usr_123"). Returned in webhook `data.metadata.externalId`. - `redirect_url`: Browser return URL after successful payment. Falls back to dashboard Default Return URL. - `name`: Optional customer full name. - `phone`: Optional Safaricom M-Pesa phone number (e.g. "0712345678"). ## 2. Pricing, Platform Fees & Metrics - Subscriber Experience: The subscriber pays the exact tier price (e.g. KES 200). Zero checkout fees are added to the subscriber. - Creator Payout: Chaime charges an 8% platform fee (e.g. KES 16), which is deducted from creator earnings. The creator receives KES 184 directly to their linked M-Pesa or bank subaccount. - Total Earnings Metric: Cumulative all-time net revenue collected from all completed membership transactions (matches main dashboard earnings). - Monthly Revenue (MRR) Metric: Normalized monthly recurring revenue from currently active members (Monthly plans + Yearly plans / 12). - Active Subscribers Metric: Total count of members with active, unexpired paid periods. ## 3. Webhook Security & Verification - HTTP Method: POST - Header: `Chaime-Signature: sha256=<hex_digest>` - Header: `Chaime-Event: <event_name>` - Secret: Configured in Chaime Dashboard (Dashboard > Memberships > Developer Webhooks). - Verification: Compute HMAC SHA-256 over raw body using secret. Compare against signature using a constant-time / timing-safe equality check. - Timeout: Respond with HTTP 200 within 8 seconds. ## 4. Webhook Event Types & TypeScript Definitions Chaime delivers signed JSON events. Each payload adheres to the following TypeScript definitions: ```typescript export type ChaimeEventType = | "subscription.activated" | "subscription.renewed" | "subscription.canceled" | "test.ping"; export type ChaimeBillingInterval = "MONTHLY" | "YEARLY"; export interface ChaimeCustomer { email: string; name: string; phone?: string; } export interface ChaimeTier { id: string; name: string; priceKes?: number; interval?: ChaimeBillingInterval; } export interface ChaimePeriod { start: string; // ISO 8601 UTC end: string; // ISO 8601 UTC } export interface ChaimeSubscriptionActivatedPayload { id: string; // evt_<timestamp>_<hex> event: "subscription.activated"; createdAt: string; data: { subscriptionId: string; customer: ChaimeCustomer; tier: ChaimeTier; period: ChaimePeriod; metadata?: Record<string, string>; }; } export interface ChaimeSubscriptionRenewedPayload { id: string; event: "subscription.renewed"; createdAt: string; data: { subscriptionId: string; customer: ChaimeCustomer; tier: ChaimeTier; period: ChaimePeriod; metadata?: Record<string, string>; }; } export interface ChaimeSubscriptionCanceledPayload { id: string; event: "subscription.canceled"; createdAt: string; data: { subscriptionId: string; customer: ChaimeCustomer; tier: { id: string; name: string; }; canceledAt: string; reason: "EXPIRED_PERIOD" | "USER_REQUEST" | "PAYMENT_FAILED"; metadata?: Record<string, string>; }; } export interface ChaimeTestPingPayload { id: string; event: "test.ping"; createdAt: string; data: { message: string; endpointUrl: string; }; } export type ChaimeWebhookPayload = | ChaimeSubscriptionActivatedPayload | ChaimeSubscriptionRenewedPayload | ChaimeSubscriptionCanceledPayload | ChaimeTestPingPayload; ``` Sample JSON (`subscription.activated`): ```json { "id": "evt_1732205400000_a1b2c3d4", "event": "subscription.activated", "createdAt": "2026-11-21T18:30:00.000Z", "data": { "subscriptionId": "sub_cm7890abcdef", "customer": { "email": "[email protected]", "name": "Jane Doe", "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_12345" } } } ``` Additional Events: - `subscription.renewed`: Member successfully renewed next billing cycle. - `subscription.canceled`: Member subscription revoked or expired. - `test.ping`: Test dispatch triggered from Chaime Dashboard. ## 5. Expected Endpoint Response Shape HTTP Method Response: HTTP 200 OK within 8 seconds. Success Response Body: ```json { "received": true } ``` Idempotent / Already Handled (HTTP 200 OK): ```json { "received": true, "duplicate": true } ``` Error Responses (Logged in Creator Dashboard): - 401 Unauthorized: `{"error": "Invalid signature"}` - 400 Bad Request: `{"error": "Invalid payload format"}` - 500 Server Error: `{"error": "Database error"}` ## 6. Next.js App Router Verification Handler ```typescript import crypto from "node:crypto"; import { NextResponse } from "next/server"; const SECRET = process.env.CHAIME_WEBHOOK_SECRET!; export async function POST(req: Request) { const rawBody = await req.text(); const signature = req.headers.get("chaime-signature") || ""; const expected = "sha256=" + crypto.createHmac("sha256", SECRET).update(rawBody).digest("hex"); if ( signature.length !== expected.length || !crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected)) ) { return NextResponse.json({ error: "Invalid signature" }, { status: 401 }); } const payload = JSON.parse(rawBody); if (payload.event === "subscription.activated") { const { customer, tier, metadata } = payload.data; // Upgrade user: metadata.externalId or customer.email } return NextResponse.json({ received: true }, { status: 200 }); } ``` ## 7. Testing & Developer Resources - Webhook.site (https://webhook.site): Generate a temporary HTTPS endpoint to inspect raw headers and payloads instantly. - Localhost Tunnel: Use `ngrok http 3000` or `cloudflared tunnel --url http://localhost:3000` to forward webhooks to local dev. - Dashboard Test Ping: Click "Test Ping" in Chaime Webhooks tab to send a verified `test.ping` payload.