Adds /payments/chapa/direct initiate and authorize endpoints alongside existing hosted checkout. Includes 3DES OTP authorization, verify routing for CHAPA_DIRECT payments, tests, and client app integration guide. Co-authored-by: Cursor <cursoragent@cursor.com>
982 lines
29 KiB
Markdown
982 lines
29 KiB
Markdown
# Chapa Direct Charge (USSD) — Client App Integration Guide
|
||
|
||
This guide documents how to integrate **Chapa Direct Charge** subscription payments into the Yimaru **learner client app** (mobile or web). Direct charge lets users pay with Ethiopian mobile wallets **inside your app** — no browser redirect to Chapa’s hosted checkout page. For Telebirr and similar wallets, the user receives a **USSD push** on their phone and approves the payment there.
|
||
|
||
> **Scope:** Subscription checkout only. Uses `POST /api/v1/payments/chapa/direct` and related endpoints. **Hosted Chapa checkout** (`POST /api/v1/payments/subscribe` with `provider: "CHAPA"`) remains available and unchanged — use it when you want a full payment page with cards and all wallets.
|
||
|
||
---
|
||
|
||
## Table of contents
|
||
|
||
1. [Feature overview](#feature-overview)
|
||
2. [Choose the right payment flow](#choose-the-right-payment-flow)
|
||
3. [Architecture](#architecture)
|
||
4. [Prerequisites](#prerequisites)
|
||
5. [Authentication & permissions](#authentication--permissions)
|
||
6. [Response envelopes](#response-envelopes)
|
||
7. [API reference](#api-reference)
|
||
8. [Payment method catalog](#payment-method-catalog)
|
||
9. [USSD flow (Telebirr and similar)](#ussd-flow-telebirr-and-similar)
|
||
10. [OTP flow (CBE Birr, Amole, E-Birr)](#otp-flow-cbe-birr-amole-e-birr)
|
||
11. [Portal flow (Enat Bank)](#portal-flow-enat-bank)
|
||
12. [Verify payment & activate subscription](#verify-payment--activate-subscription)
|
||
13. [Recommended client UI](#recommended-client-ui)
|
||
14. [Phone number formatting](#phone-number-formatting)
|
||
15. [TypeScript types & API client](#typescript-types--api-client)
|
||
16. [React / React Native patterns](#react--react-native-patterns)
|
||
17. [Polling & state machine](#polling--state-machine)
|
||
18. [Error handling](#error-handling)
|
||
19. [Comparison: direct vs hosted checkout](#comparison-direct-vs-hosted-checkout)
|
||
20. [Integration checklist](#integration-checklist)
|
||
21. [Limitations](#limitations)
|
||
22. [Quick reference](#quick-reference)
|
||
|
||
---
|
||
|
||
## Feature overview
|
||
|
||
| Capability | Client app | Backend |
|
||
|------------|------------|---------|
|
||
| List direct charge wallets | `GET .../chapa/direct/methods` | Static catalog + `auth_type` |
|
||
| Start subscription payment in-app | `POST .../chapa/direct` | Calls Chapa `POST /v1/charges?type=...` |
|
||
| USSD push to user’s phone | User action on device | Chapa → wallet (Telebirr, M-Pesa, …) |
|
||
| OTP authorization in-app | `POST .../chapa/direct/authorize` | Encrypted validate call to Chapa |
|
||
| Confirm payment & unlock subscription | `GET .../payments/verify/:session_id` | Verifies with Chapa, creates subscription |
|
||
| Hosted checkout redirect | `POST .../payments/subscribe` + `payment_url` | Unchanged |
|
||
|
||
### What problem this solves
|
||
|
||
**Hosted checkout** opens an external browser/WebView. **Direct charge** keeps the user in your app:
|
||
|
||
1. User picks a plan and wallet (e.g. Telebirr).
|
||
2. App calls your API → Chapa sends USSD push to the phone number provided.
|
||
3. User approves on their phone.
|
||
4. App polls verify until `status: SUCCESS` → subscription is active.
|
||
|
||
---
|
||
|
||
## Choose the right payment flow
|
||
|
||
| User experience | API | When to use |
|
||
|-----------------|-----|-------------|
|
||
| **In-app USSD / OTP** | `POST /payments/chapa/direct` | Native mobile app; user pays with Telebirr/M-Pesa/etc. without leaving the app |
|
||
| **Browser checkout** | `POST /payments/subscribe` + `provider: "CHAPA"` | Web app, or when you need cards + all Chapa checkout options |
|
||
| **ArifPay direct** | `POST /payments/direct` | Legacy ArifPay USSD (separate integration) |
|
||
|
||
This guide covers **Chapa Direct Charge** only.
|
||
|
||
---
|
||
|
||
## Architecture
|
||
|
||
```mermaid
|
||
sequenceDiagram
|
||
participant App as Client app
|
||
participant API as Yimaru API
|
||
participant Chapa as Chapa API
|
||
participant Wallet as User wallet (Telebirr)
|
||
|
||
App->>API: GET /subscription-plans
|
||
App->>API: GET /payments/chapa/direct/methods
|
||
App->>API: POST /payments/chapa/direct
|
||
API->>Chapa: POST /v1/charges?type=telebirr
|
||
Chapa->>Wallet: USSD push
|
||
Wallet-->>User: Approve payment
|
||
loop Poll until SUCCESS or timeout
|
||
App->>API: GET /payments/verify/{session_id}
|
||
API->>Chapa: GET /v1/transaction/verify/{tx_ref}
|
||
API-->>App: status PENDING | PROCESSING | SUCCESS
|
||
end
|
||
App->>API: GET /subscriptions/me
|
||
API-->>App: Active subscription
|
||
```
|
||
|
||
**OTP methods** add one step between initiate and verify:
|
||
|
||
```mermaid
|
||
sequenceDiagram
|
||
participant App as Client app
|
||
participant API as Yimaru API
|
||
participant Chapa as Chapa API
|
||
|
||
App->>API: POST /payments/chapa/direct
|
||
API->>Chapa: POST /v1/charges?type=cbebirr
|
||
Chapa-->>API: request_id + reference
|
||
API-->>App: requires_authorize true, request_id
|
||
App->>User: Enter OTP
|
||
App->>API: POST /payments/chapa/direct/authorize
|
||
API->>Chapa: POST /v1/validate?type=cbebirr
|
||
App->>API: GET /payments/verify/{session_id}
|
||
```
|
||
|
||
---
|
||
|
||
## Prerequisites
|
||
|
||
### Client app
|
||
|
||
1. User must be **logged in** (Bearer access token).
|
||
2. Collect **plan ID**, **phone**, and **email** before payment.
|
||
3. Phone must be a valid Ethiopian mobile number (see [Phone number formatting](#phone-number-formatting)).
|
||
4. Implement **verify polling** after USSD approval or OTP authorization.
|
||
|
||
### Backend / environment
|
||
|
||
1. API deployed with Chapa Direct Charge support.
|
||
2. Server env: `CHAPA_SECRET_KEY`, `CHAPA_BASE_URL` (optional, defaults to `https://api.chapa.co/v1`).
|
||
3. For **OTP methods**: server must have `CHAPA_ENCRYPTION_KEY` configured (client does not handle encryption).
|
||
|
||
### Base URL
|
||
|
||
Replace `{API_BASE}` with your environment:
|
||
|
||
| Environment | Example |
|
||
|-------------|---------|
|
||
| Production | `https://api.yimaru.com` |
|
||
| Staging | Your staging API host |
|
||
|
||
All paths below are prefixed with `/api/v1`.
|
||
|
||
---
|
||
|
||
## Authentication & permissions
|
||
|
||
Every payment request (except public method list) requires:
|
||
|
||
```http
|
||
Authorization: Bearer <access_token>
|
||
Content-Type: application/json
|
||
```
|
||
|
||
### Permissions (learner role)
|
||
|
||
| Action | Permission | Endpoint |
|
||
|--------|------------|----------|
|
||
| List direct methods | None (public) | `GET /payments/chapa/direct/methods` |
|
||
| Start direct payment | `payments.direct_initiate` | `POST /payments/chapa/direct` |
|
||
| Submit OTP | `payments.direct_verify_otp` | `POST /payments/chapa/direct/authorize` |
|
||
| Verify payment | `payments.verify` | `GET /payments/verify/:session_id` |
|
||
| Read subscription | `subscriptions.get_mine` | `GET /subscriptions/me` |
|
||
| List plans | None (public) | `GET /subscription-plans` |
|
||
|
||
Standard learner accounts include these permissions. If verify returns `403`, check RBAC on the user’s role.
|
||
|
||
---
|
||
|
||
## Response envelopes
|
||
|
||
### Success
|
||
|
||
```json
|
||
{
|
||
"message": "Chapa direct payment initiated successfully",
|
||
"data": { },
|
||
"success": true,
|
||
"status_code": 200
|
||
}
|
||
```
|
||
|
||
### Error
|
||
|
||
```json
|
||
{
|
||
"message": "Failed to initiate Chapa direct payment",
|
||
"error": "user already has an active subscription for this category"
|
||
}
|
||
```
|
||
|
||
Always read both `message` (user-friendly) and `error` (detail) for debugging and UI copy.
|
||
|
||
---
|
||
|
||
## API reference
|
||
|
||
### List subscription plans
|
||
|
||
```http
|
||
GET /api/v1/subscription-plans
|
||
```
|
||
|
||
Use to show plan cards before checkout. Each plan has `id`, `name`, `price`, `currency`, `category`, etc.
|
||
|
||
### List Chapa direct charge methods
|
||
|
||
```http
|
||
GET /api/v1/payments/chapa/direct/methods
|
||
```
|
||
|
||
No auth required.
|
||
|
||
**Response `data`:**
|
||
|
||
```json
|
||
[
|
||
{ "name": "telebirr", "display_name": "Telebirr", "auth_type": "ussd" },
|
||
{ "name": "mpesa", "display_name": "M-Pesa", "auth_type": "ussd" },
|
||
{ "name": "cbebirr", "display_name": "CBE Birr", "auth_type": "otp" },
|
||
{ "name": "ebirr", "display_name": "E-Birr", "auth_type": "otp" },
|
||
{ "name": "awashbirr", "display_name": "Awash Birr", "auth_type": "ussd" },
|
||
{ "name": "yaya", "display_name": "Yaya Wallet", "auth_type": "ussd" },
|
||
{ "name": "boa_ussd", "display_name": "BOA USSD", "auth_type": "ussd" },
|
||
{ "name": "coopay-ebirr", "display_name": "Coopay E-Birr", "auth_type": "ussd" },
|
||
{ "name": "amole", "display_name": "Amole", "auth_type": "otp" },
|
||
{ "name": "enat_bank", "display_name": "Enat Bank", "auth_type": "portal" }
|
||
]
|
||
```
|
||
|
||
Filter UI by `auth_type` to show the correct next step (USSD instructions vs OTP input vs external portal).
|
||
|
||
### Initiate direct charge (subscription)
|
||
|
||
```http
|
||
POST /api/v1/payments/chapa/direct
|
||
Authorization: Bearer <token>
|
||
Content-Type: application/json
|
||
```
|
||
|
||
**Request body:**
|
||
|
||
| Field | Type | Required | Description |
|
||
|-------|------|----------|-------------|
|
||
| `plan_id` | number | Yes | Subscription plan ID from `GET /subscription-plans` |
|
||
| `phone` | string | Yes | Customer mobile (`09xxxxxxxx` or `07xxxxxxxx` preferred) |
|
||
| `email` | string | Yes | Valid email (receipt / Chapa requirement) |
|
||
| `payment_method` | string | Yes | Wallet key from methods list, e.g. `"telebirr"` |
|
||
|
||
**Example:**
|
||
|
||
```json
|
||
{
|
||
"plan_id": 3,
|
||
"phone": "0912345678",
|
||
"email": "learner@example.com",
|
||
"payment_method": "telebirr"
|
||
}
|
||
```
|
||
|
||
**Success `data`:**
|
||
|
||
```json
|
||
{
|
||
"payment_id": 842,
|
||
"session_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
|
||
"chapa_reference": "CHcuKjgnN0Dk0",
|
||
"request_id": "",
|
||
"auth_type": "ussd",
|
||
"requires_authorize": false,
|
||
"message": "USSD push sent to your phone. Approve the payment to continue.",
|
||
"portal_html": "",
|
||
"amount": 499.0,
|
||
"currency": "ETB",
|
||
"expires_at": "2026-06-26T15:30:00Z"
|
||
}
|
||
```
|
||
|
||
| Field | Client usage |
|
||
|-------|----------------|
|
||
| `session_id` | **Save this.** Use as `tx_ref` for `GET /payments/verify/{session_id}` |
|
||
| `payment_id` | Optional: cancel via `POST /payments/{id}/cancel` |
|
||
| `requires_authorize` | `true` → show OTP screen before verify |
|
||
| `request_id` | Required for OTP authorize when `requires_authorize` is `true` |
|
||
| `auth_type` | `ussd`, `otp`, or `portal` — drives UI |
|
||
| `message` | Show to user |
|
||
| `portal_html` | Only for `enat_bank` — HTML to open in WebView/browser |
|
||
| `expires_at` | Direct charge session expires in **~15 minutes** |
|
||
|
||
### Authorize OTP (OTP methods only)
|
||
|
||
```http
|
||
POST /api/v1/payments/chapa/direct/authorize
|
||
Authorization: Bearer <token>
|
||
Content-Type: application/json
|
||
```
|
||
|
||
**Request body:**
|
||
|
||
| Field | Type | Required | Description |
|
||
|-------|------|----------|-------------|
|
||
| `session_id` | string | Yes | `session_id` from initiate response |
|
||
| `request_id` | string | Yes | `request_id` from initiate response |
|
||
| `otp` | string | Yes | OTP received by SMS / app |
|
||
|
||
**Example:**
|
||
|
||
```json
|
||
{
|
||
"session_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
|
||
"request_id": "13434jjfhd8ududfy82e324234234jkhjsfhdfhskdjfh89fjhduohdfjhsgkdfksjdfskldhfkjs",
|
||
"otp": "123456"
|
||
}
|
||
```
|
||
|
||
**Success `data`:**
|
||
|
||
```json
|
||
{
|
||
"success": true,
|
||
"message": "Payment authorized successfully",
|
||
"payment_id": 842
|
||
}
|
||
```
|
||
|
||
If `success` is `false`, show `message` and allow retry.
|
||
|
||
### Verify payment
|
||
|
||
```http
|
||
GET /api/v1/payments/verify/{session_id}
|
||
Authorization: Bearer <token>
|
||
```
|
||
|
||
Pass the **`session_id`** from initiate (not `chapa_reference`).
|
||
|
||
**Success `data` (payment object):**
|
||
|
||
```json
|
||
{
|
||
"id": 842,
|
||
"user_id": 15,
|
||
"plan_id": 3,
|
||
"subscription_id": 120,
|
||
"session_id": "CHcuKjgnN0Dk0",
|
||
"amount": 499.0,
|
||
"currency": "ETB",
|
||
"payment_method": "telebirr",
|
||
"status": "SUCCESS",
|
||
"plan_name": "Monthly Premium",
|
||
"paid_at": "2026-06-26T15:12:00Z",
|
||
"expires_at": "2026-06-26T15:25:00Z",
|
||
"created_at": "2026-06-26T15:10:00Z"
|
||
}
|
||
```
|
||
|
||
| `status` | Meaning | Client action |
|
||
|----------|---------|---------------|
|
||
| `PENDING` | Awaiting user action | Keep polling or prompt user to approve USSD |
|
||
| `PROCESSING` | Authorized, confirmation in progress | Poll verify |
|
||
| `SUCCESS` | Paid; subscription created | Navigate to success; refresh `GET /subscriptions/me` |
|
||
| `FAILED` | Payment failed | Show error; offer retry |
|
||
| `CANCELLED` | User cancelled | Return to plan selection |
|
||
| `EXPIRED` | Session timed out (~15 min) | Start new payment |
|
||
|
||
When `status` is `SUCCESS`, `subscription_id` is set and the user’s subscription for that plan category is active.
|
||
|
||
### Confirm subscription
|
||
|
||
```http
|
||
GET /api/v1/subscriptions/me
|
||
Authorization: Bearer <token>
|
||
```
|
||
|
||
Optional after verify — confirms active subscription details for the home screen.
|
||
|
||
### Cancel pending payment (optional)
|
||
|
||
```http
|
||
POST /api/v1/payments/{payment_id}/cancel
|
||
Authorization: Bearer <token>
|
||
```
|
||
|
||
Only works while `status` is `PENDING`.
|
||
|
||
---
|
||
|
||
## Payment method catalog
|
||
|
||
| `payment_method` | Display name | `auth_type` | Client flow |
|
||
|------------------|--------------|-------------|-------------|
|
||
| `telebirr` | Telebirr | `ussd` | Initiate → USSD approve → verify poll |
|
||
| `mpesa` | M-Pesa | `ussd` | Same as Telebirr |
|
||
| `awashbirr` | Awash Birr | `ussd` | Same |
|
||
| `yaya` | Yaya Wallet | `ussd` | Same |
|
||
| `boa_ussd` | BOA USSD | `ussd` | Same |
|
||
| `coopay-ebirr` | Coopay E-Birr | `ussd` | Same |
|
||
| `cbebirr` | CBE Birr | `otp` | Initiate → OTP screen → authorize → verify poll |
|
||
| `ebirr` | E-Birr | `otp` | Same |
|
||
| `amole` | Amole | `otp` | Same |
|
||
| `enat_bank` | Enat Bank | `portal` | Initiate → open `portal_html` in WebView → verify poll |
|
||
|
||
**Recommended default for “Pay with Telebirr” button:** `payment_method: "telebirr"`.
|
||
|
||
---
|
||
|
||
## USSD flow (Telebirr and similar)
|
||
|
||
### Step-by-step
|
||
|
||
1. **Load plans** — `GET /subscription-plans`
|
||
2. **Load wallets** (optional) — `GET /payments/chapa/direct/methods`; filter `auth_type === "ussd"`
|
||
3. **Show checkout** — plan summary, phone (pre-fill from profile), email
|
||
4. **Initiate** — `POST /payments/chapa/direct` with `payment_method: "telebirr"`
|
||
5. **Instruct user** — display `message`; e.g. “Check your phone for a Telebirr prompt and approve the payment.”
|
||
6. **Poll verify** — `GET /payments/verify/{session_id}` every 3–5 seconds
|
||
7. **Success** — when `status === "SUCCESS"`, show confirmation and refresh subscription state
|
||
8. **Timeout** — stop polling after `expires_at` or ~15 minutes; offer “Try again”
|
||
|
||
### Example initiate + poll (fetch)
|
||
|
||
```typescript
|
||
async function payWithTelebirr(planId: number, phone: string, email: string, token: string) {
|
||
const initiateRes = await fetch(`${API_BASE}/api/v1/payments/chapa/direct`, {
|
||
method: "POST",
|
||
headers: {
|
||
Authorization: `Bearer ${token}`,
|
||
"Content-Type": "application/json",
|
||
},
|
||
body: JSON.stringify({
|
||
plan_id: planId,
|
||
phone,
|
||
email,
|
||
payment_method: "telebirr",
|
||
}),
|
||
});
|
||
|
||
if (!initiateRes.ok) {
|
||
const err = await initiateRes.json();
|
||
throw new Error(err.error || err.message);
|
||
}
|
||
|
||
const { data } = await initiateRes.json();
|
||
// Show data.message to user — USSD push sent
|
||
|
||
const sessionId = data.session_id;
|
||
const deadline = new Date(data.expires_at).getTime();
|
||
|
||
while (Date.now() < deadline) {
|
||
await sleep(4000);
|
||
|
||
const verifyRes = await fetch(`${API_BASE}/api/v1/payments/verify/${sessionId}`, {
|
||
headers: { Authorization: `Bearer ${token}` },
|
||
});
|
||
if (!verifyRes.ok) continue;
|
||
|
||
const verifyBody = await verifyRes.json();
|
||
const payment = verifyBody.data;
|
||
|
||
if (payment.status === "SUCCESS") {
|
||
return payment;
|
||
}
|
||
if (payment.status === "FAILED" || payment.status === "CANCELLED" || payment.status === "EXPIRED") {
|
||
throw new Error(`Payment ${payment.status.toLowerCase()}`);
|
||
}
|
||
}
|
||
|
||
throw new Error("Payment timed out. Please try again.");
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## OTP flow (CBE Birr, Amole, E-Birr)
|
||
|
||
### Step-by-step
|
||
|
||
1. Initiate with `payment_method: "cbebirr"` (or `amole`, `ebirr`)
|
||
2. Response has `requires_authorize: true`, `request_id`, `auth_type: "otp"`
|
||
3. Show OTP input screen
|
||
4. `POST /payments/chapa/direct/authorize` with `session_id`, `request_id`, `otp`
|
||
5. On `success: true`, poll `GET /payments/verify/{session_id}` until `SUCCESS`
|
||
|
||
### Important
|
||
|
||
- Store **`session_id`** and **`request_id`** from initiate in checkout state (memory / secure storage) until authorize completes.
|
||
- Do **not** encrypt OTP on the client — the server encrypts with `CHAPA_ENCRYPTION_KEY`.
|
||
- Allow OTP resend only by **starting a new initiate** if the session expired.
|
||
|
||
---
|
||
|
||
## Portal flow (Enat Bank)
|
||
|
||
1. Initiate with `payment_method: "enat_bank"`
|
||
2. If `portal_html` is non-empty, open it in an **external browser or WebView** (Chapa docs: portal views may not work in embedded frames).
|
||
3. Poll verify while the user completes the bank portal.
|
||
4. Treat like USSD for polling logic.
|
||
|
||
---
|
||
|
||
## Verify payment & activate subscription
|
||
|
||
The client **never** calls Chapa directly. Verification always goes through:
|
||
|
||
```http
|
||
GET /api/v1/payments/verify/{session_id}
|
||
```
|
||
|
||
The backend:
|
||
|
||
1. Looks up the payment by `session_id` (`tx_ref`)
|
||
2. Calls Chapa `GET /v1/transaction/verify/{tx_ref}`
|
||
3. On success, creates the user subscription and links it to the payment
|
||
4. Returns updated payment with `subscription_id`
|
||
|
||
You do **not** need a separate “activate subscription” call after successful verify.
|
||
|
||
---
|
||
|
||
## Recommended client UI
|
||
|
||
### Checkout screen
|
||
|
||
| Element | Notes |
|
||
|---------|-------|
|
||
| Plan name & price | From selected plan |
|
||
| Wallet picker | From `GET /payments/chapa/direct/methods`; icons per wallet |
|
||
| Phone field | Pre-fill from profile; validate `09` / `07` |
|
||
| Email field | Pre-fill from profile |
|
||
| Pay button | Disabled until valid phone + email |
|
||
|
||
### After initiate (`auth_type: ussd`)
|
||
|
||
| Element | Notes |
|
||
|---------|-------|
|
||
| Status illustration | Phone + wallet icon |
|
||
| Instruction text | Use API `message` |
|
||
| Spinner | “Waiting for approval…” |
|
||
| Poll indicator | Optional countdown to `expires_at` |
|
||
| Cancel | `POST /payments/{id}/cancel` if still pending |
|
||
|
||
### After initiate (`auth_type: otp`)
|
||
|
||
| Element | Notes |
|
||
|---------|-------|
|
||
| OTP input | 4–6 digits |
|
||
| Submit | Calls authorize endpoint |
|
||
| Resend | New initiate only (new session) |
|
||
|
||
### Success screen
|
||
|
||
| Element | Notes |
|
||
|---------|-------|
|
||
| Confirmation | “Subscription active” |
|
||
| Plan name | From verify response `plan_name` |
|
||
| CTA | “Start learning” → home |
|
||
|
||
---
|
||
|
||
## Phone number formatting
|
||
|
||
The API normalizes phone numbers server-side. Send any of these formats; prefer **`09xxxxxxxx`** or **`07xxxxxxxx`** (10 digits):
|
||
|
||
| Input | Accepted |
|
||
|-------|----------|
|
||
| `0912345678` | Yes (preferred) |
|
||
| `0712345678` | Yes |
|
||
| `+251912345678` | Yes (converted) |
|
||
| `251912345678` | Yes (converted) |
|
||
| `912345678` | Yes (leading `0` added) |
|
||
|
||
Invalid or empty phone → `400` with `"phone is required for direct charge"`.
|
||
|
||
---
|
||
|
||
## TypeScript types & API client
|
||
|
||
```typescript
|
||
const API_BASE = "https://api.yimaru.com";
|
||
|
||
export interface ApiResponse<T> {
|
||
message: string;
|
||
data: T;
|
||
success?: boolean;
|
||
status_code?: number;
|
||
}
|
||
|
||
export interface ApiError {
|
||
message: string;
|
||
error?: string;
|
||
}
|
||
|
||
export interface ChapaDirectChargeMethod {
|
||
name: string;
|
||
display_name: string;
|
||
auth_type: "ussd" | "otp" | "portal";
|
||
}
|
||
|
||
export interface InitiateChapaDirectChargeRequest {
|
||
plan_id: number;
|
||
phone: string;
|
||
email: string;
|
||
payment_method: string;
|
||
}
|
||
|
||
export interface InitiateChapaDirectChargeResponse {
|
||
payment_id: number;
|
||
session_id: string;
|
||
chapa_reference?: string;
|
||
request_id?: string;
|
||
auth_type?: string;
|
||
requires_authorize: boolean;
|
||
message: string;
|
||
portal_html?: string;
|
||
amount: number;
|
||
currency: string;
|
||
expires_at: string;
|
||
}
|
||
|
||
export interface AuthorizeChapaDirectChargeRequest {
|
||
session_id: string;
|
||
request_id: string;
|
||
otp: string;
|
||
}
|
||
|
||
export interface AuthorizeChapaDirectChargeResponse {
|
||
success: boolean;
|
||
message: string;
|
||
payment_id?: number;
|
||
}
|
||
|
||
export type PaymentStatus =
|
||
| "PENDING"
|
||
| "PROCESSING"
|
||
| "SUCCESS"
|
||
| "FAILED"
|
||
| "CANCELLED"
|
||
| "EXPIRED";
|
||
|
||
export interface Payment {
|
||
id: number;
|
||
user_id: number;
|
||
plan_id?: number;
|
||
subscription_id?: number;
|
||
session_id?: string;
|
||
amount: number;
|
||
currency: string;
|
||
payment_method?: string;
|
||
status: PaymentStatus;
|
||
payment_url?: string;
|
||
plan_name?: string;
|
||
paid_at?: string;
|
||
expires_at?: string;
|
||
created_at: string;
|
||
}
|
||
|
||
export async function getChapaDirectMethods(): Promise<ChapaDirectChargeMethod[]> {
|
||
const res = await fetch(`${API_BASE}/api/v1/payments/chapa/direct/methods`);
|
||
const json: ApiResponse<ChapaDirectChargeMethod[]> = await res.json();
|
||
return json.data;
|
||
}
|
||
|
||
export async function initiateChapaDirectCharge(
|
||
token: string,
|
||
body: InitiateChapaDirectChargeRequest
|
||
): Promise<InitiateChapaDirectChargeResponse> {
|
||
const res = await fetch(`${API_BASE}/api/v1/payments/chapa/direct`, {
|
||
method: "POST",
|
||
headers: {
|
||
Authorization: `Bearer ${token}`,
|
||
"Content-Type": "application/json",
|
||
},
|
||
body: JSON.stringify(body),
|
||
});
|
||
const json = await res.json();
|
||
if (!res.ok) throw new Error(json.error || json.message);
|
||
return json.data;
|
||
}
|
||
|
||
export async function authorizeChapaDirectCharge(
|
||
token: string,
|
||
body: AuthorizeChapaDirectChargeRequest
|
||
): Promise<AuthorizeChapaDirectChargeResponse> {
|
||
const res = await fetch(`${API_BASE}/api/v1/payments/chapa/direct/authorize`, {
|
||
method: "POST",
|
||
headers: {
|
||
Authorization: `Bearer ${token}`,
|
||
"Content-Type": "application/json",
|
||
},
|
||
body: JSON.stringify(body),
|
||
});
|
||
const json = await res.json();
|
||
if (!res.ok) throw new Error(json.error || json.message);
|
||
if (!json.data?.success) throw new Error(json.message || "Authorization failed");
|
||
return json.data;
|
||
}
|
||
|
||
export async function verifyPayment(token: string, sessionId: string): Promise<Payment> {
|
||
const res = await fetch(`${API_BASE}/api/v1/payments/verify/${encodeURIComponent(sessionId)}`, {
|
||
headers: { Authorization: `Bearer ${token}` },
|
||
});
|
||
const json = await res.json();
|
||
if (!res.ok) throw new Error(json.error || json.message);
|
||
return json.data;
|
||
}
|
||
|
||
export function sleep(ms: number): Promise<void> {
|
||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||
}
|
||
|
||
export async function pollPaymentUntilDone(
|
||
token: string,
|
||
sessionId: string,
|
||
expiresAt: string,
|
||
intervalMs = 4000
|
||
): Promise<Payment> {
|
||
const deadline = new Date(expiresAt).getTime();
|
||
|
||
while (Date.now() < deadline) {
|
||
const payment = await verifyPayment(token, sessionId);
|
||
|
||
if (payment.status === "SUCCESS") return payment;
|
||
if (["FAILED", "CANCELLED", "EXPIRED"].includes(payment.status)) {
|
||
throw new Error(`Payment ${payment.status.toLowerCase()}`);
|
||
}
|
||
|
||
await sleep(intervalMs);
|
||
}
|
||
|
||
throw new Error("Payment timed out");
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## React / React Native patterns
|
||
|
||
### Wallet picker
|
||
|
||
```tsx
|
||
function WalletPicker({
|
||
methods,
|
||
selected,
|
||
onSelect,
|
||
}: {
|
||
methods: ChapaDirectChargeMethod[];
|
||
selected: string | null;
|
||
onSelect: (name: string) => void;
|
||
}) {
|
||
const ussdMethods = methods.filter((m) => m.auth_type === "ussd");
|
||
|
||
return (
|
||
<View>
|
||
<Text>Pay with</Text>
|
||
{ussdMethods.map((m) => (
|
||
<Pressable
|
||
key={m.name}
|
||
onPress={() => onSelect(m.name)}
|
||
style={{ borderWidth: selected === m.name ? 2 : 1 }}
|
||
>
|
||
<Text>{m.display_name}</Text>
|
||
</Pressable>
|
||
))}
|
||
</View>
|
||
);
|
||
}
|
||
```
|
||
|
||
### Checkout orchestrator
|
||
|
||
```tsx
|
||
async function handlePayTelebirr() {
|
||
setLoading(true);
|
||
setError(null);
|
||
try {
|
||
const initiated = await initiateChapaDirectCharge(token, {
|
||
plan_id: plan.id,
|
||
phone,
|
||
email,
|
||
payment_method: "telebirr",
|
||
});
|
||
|
||
setStatusMessage(initiated.message);
|
||
setPhase("waiting_ussd");
|
||
|
||
if (initiated.requires_authorize) {
|
||
setPhase("otp");
|
||
setCheckoutSession({
|
||
sessionId: initiated.session_id,
|
||
requestId: initiated.request_id ?? "",
|
||
expiresAt: initiated.expires_at,
|
||
paymentId: initiated.payment_id,
|
||
});
|
||
return;
|
||
}
|
||
|
||
const payment = await pollPaymentUntilDone(
|
||
token,
|
||
initiated.session_id,
|
||
initiated.expires_at
|
||
);
|
||
navigation.navigate("SubscriptionSuccess", { payment });
|
||
} catch (e) {
|
||
setError(e instanceof Error ? e.message : "Payment failed");
|
||
} finally {
|
||
setLoading(false);
|
||
}
|
||
}
|
||
```
|
||
|
||
### OTP submit
|
||
|
||
```tsx
|
||
async function handleSubmitOtp(otp: string) {
|
||
if (!checkoutSession) return;
|
||
|
||
await authorizeChapaDirectCharge(token, {
|
||
session_id: checkoutSession.sessionId,
|
||
request_id: checkoutSession.requestId,
|
||
otp,
|
||
});
|
||
|
||
const payment = await pollPaymentUntilDone(
|
||
token,
|
||
checkoutSession.sessionId,
|
||
checkoutSession.expiresAt
|
||
);
|
||
navigation.navigate("SubscriptionSuccess", { payment });
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## Polling & state machine
|
||
|
||
```mermaid
|
||
stateDiagram-v2
|
||
[*] --> Idle
|
||
Idle --> Initiating: User taps Pay
|
||
Initiating --> WaitingUSSD: requires_authorize false
|
||
Initiating --> EnterOTP: requires_authorize true
|
||
Initiating --> Failed: API error
|
||
WaitingUSSD --> Polling: Show USSD instructions
|
||
EnterOTP --> Authorizing: User submits OTP
|
||
Authorizing --> Polling: authorize success
|
||
Authorizing --> Failed: authorize failed
|
||
Polling --> Success: verify status SUCCESS
|
||
Polling --> Failed: FAILED / CANCELLED / EXPIRED
|
||
Polling --> Polling: PENDING / PROCESSING
|
||
Success --> [*]
|
||
Failed --> Idle: Try again
|
||
```
|
||
|
||
**Polling guidelines:**
|
||
|
||
| Setting | Value |
|
||
|---------|-------|
|
||
| Interval | 3–5 seconds |
|
||
| Max duration | Until `expires_at` (~15 min for direct charge) |
|
||
| Backoff | Optional: increase to 8s after 2 minutes |
|
||
| Background | Pause polling when app backgrounded; resume on foreground |
|
||
|
||
---
|
||
|
||
## Error handling
|
||
|
||
| HTTP | `message` / `error` | Client action |
|
||
|------|---------------------|---------------|
|
||
| 400 | Invalid payment method | Refresh methods list; fix selection |
|
||
| 400 | Phone required | Validate phone field |
|
||
| 400 | Plan not active | Remove plan from UI |
|
||
| 409 | Already has active subscription | Redirect to `GET /subscriptions/me` |
|
||
| 401 | Unauthorized | Refresh token or re-login |
|
||
| 403 | Permission denied | Show support message |
|
||
| 404 | Payment not found (verify) | Session invalid; restart checkout |
|
||
| 503 | Chapa not configured | Show “payments unavailable” |
|
||
| 500 | Chapa direct charge failed | Show retry; log `error` for support |
|
||
|
||
### User-facing copy (suggested)
|
||
|
||
| Situation | Message |
|
||
|-----------|---------|
|
||
| USSD sent | “Approve the payment on your phone, then return here.” |
|
||
| Polling | “Confirming your payment…” |
|
||
| Timeout | “Payment timed out. If you were charged, contact support with your phone number.” |
|
||
| Success | “You’re subscribed! Enjoy full access.” |
|
||
|
||
---
|
||
|
||
## Comparison: direct vs hosted checkout
|
||
|
||
| | Chapa Direct (`/payments/chapa/direct`) | Chapa Hosted (`/payments/subscribe`) |
|
||
|--|----------------------------------------|--------------------------------------|
|
||
| UX | Stays in app | Opens `payment_url` in browser/WebView |
|
||
| Telebirr USSD | Yes | Yes (on Chapa page) |
|
||
| Cards | No | Yes |
|
||
| Session TTL | ~15 minutes | ~3 hours |
|
||
| OTP in your UI | Yes (CBE Birr, Amole) | On Chapa page |
|
||
| `provider` field | Not used | `"CHAPA"` required |
|
||
| Verify key | `session_id` from direct response | `session_id` from subscribe response |
|
||
|
||
**You can offer both** in settings: “Pay in app (Telebirr)” vs “Pay with card or other methods”.
|
||
|
||
---
|
||
|
||
## Integration checklist
|
||
|
||
### API wiring
|
||
|
||
- [ ] `GET /subscription-plans` on plan selection screen
|
||
- [ ] `GET /payments/chapa/direct/methods` for wallet list
|
||
- [ ] `POST /payments/chapa/direct` on pay
|
||
- [ ] `POST /payments/chapa/direct/authorize` for OTP methods
|
||
- [ ] `GET /payments/verify/{session_id}` polling
|
||
- [ ] `GET /subscriptions/me` after success
|
||
|
||
### UX
|
||
|
||
- [ ] Phone + email validation before pay
|
||
- [ ] USSD instruction screen with `message` from API
|
||
- [ ] OTP screen when `requires_authorize === true`
|
||
- [ ] Loading / polling state with timeout from `expires_at`
|
||
- [ ] Success navigation refreshes subscription entitlements
|
||
- [ ] Error states with retry
|
||
|
||
### QA scenarios
|
||
|
||
- [ ] Telebirr USSD — approve on phone → verify → subscription active
|
||
- [ ] Telebirr USSD — decline on phone → verify returns `FAILED`
|
||
- [ ] CBE Birr OTP — full initiate → authorize → verify flow
|
||
- [ ] Expired session — wait past `expires_at` → verify `EXPIRED`
|
||
- [ ] Duplicate subscribe — active subscription → `409`
|
||
- [ ] Invalid phone — `400`
|
||
- [ ] App backgrounded during poll — resume polling on foreground
|
||
- [ ] Hosted checkout still works (`POST /payments/subscribe` + WebView) — regression
|
||
|
||
---
|
||
|
||
## Limitations
|
||
|
||
| Topic | Behavior |
|
||
|-------|----------|
|
||
| Chapa API calls | Server-side only; client never holds `CHAPA_SECRET_KEY` |
|
||
| OTP encryption | Server-only (`CHAPA_ENCRYPTION_KEY`) |
|
||
| Enat Bank portal | `portal_html` may require external browser |
|
||
| One active subscription per category | Duplicate pay returns `409` |
|
||
| ArifPay direct | Separate endpoints under `/payments/direct` — not this guide |
|
||
| Real-time push to app | No WebSocket; use verify polling |
|
||
| Refunds | Not exposed on client; admin/support process |
|
||
|
||
---
|
||
|
||
## Quick reference
|
||
|
||
### Endpoints
|
||
|
||
| Action | Method | Path |
|
||
|--------|--------|------|
|
||
| List wallets | `GET` | `/api/v1/payments/chapa/direct/methods` |
|
||
| Start payment | `POST` | `/api/v1/payments/chapa/direct` |
|
||
| Authorize OTP | `POST` | `/api/v1/payments/chapa/direct/authorize` |
|
||
| Verify | `GET` | `/api/v1/payments/verify/{session_id}` |
|
||
| My subscription | `GET` | `/api/v1/subscriptions/me` |
|
||
| Hosted checkout (alt.) | `POST` | `/api/v1/payments/subscribe` |
|
||
|
||
### Minimal Telebirr payload
|
||
|
||
```json
|
||
POST /api/v1/payments/chapa/direct
|
||
{
|
||
"plan_id": 3,
|
||
"phone": "0912345678",
|
||
"email": "learner@example.com",
|
||
"payment_method": "telebirr"
|
||
}
|
||
```
|
||
|
||
### Minimal verify
|
||
|
||
```http
|
||
GET /api/v1/payments/verify/a1b2c3d4-e5f6-7890-abcd-ef1234567890
|
||
Authorization: Bearer <token>
|
||
```
|
||
|
||
Look for `"status": "SUCCESS"` and `"subscription_id"` in the response.
|