diff --git a/docs/chapa-direct-charge-client-app-integration.md b/docs/chapa-direct-charge-client-app-integration.md new file mode 100644 index 00000000..7ca0da83 --- /dev/null +++ b/docs/chapa-direct-charge-client-app-integration.md @@ -0,0 +1,981 @@ +# 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 +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 +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 +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 +``` + +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 +``` + +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 +``` + +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 { + 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 { + const res = await fetch(`${API_BASE}/api/v1/payments/chapa/direct/methods`); + const json: ApiResponse = await res.json(); + return json.data; +} + +export async function initiateChapaDirectCharge( + token: string, + body: InitiateChapaDirectChargeRequest +): Promise { + 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 { + 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 { + 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 { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +export async function pollPaymentUntilDone( + token: string, + sessionId: string, + expiresAt: string, + intervalMs = 4000 +): Promise { + 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 ( + + Pay with + {ussdMethods.map((m) => ( + onSelect(m.name)} + style={{ borderWidth: selected === m.name ? 2 : 1 }} + > + {m.display_name} + + ))} + + ); +} +``` + +### 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 +``` + +Look for `"status": "SUCCESS"` and `"subscription_id"` in the response. diff --git a/internal/domain/chapa.go b/internal/domain/chapa.go index d74a6877..b92290c3 100644 --- a/internal/domain/chapa.go +++ b/internal/domain/chapa.go @@ -3,6 +3,7 @@ package domain import ( "encoding/json" "fmt" + "strings" ) // ChapaFlexibleString unmarshals JSON string or number (Chapa verify/webhook payloads vary). @@ -101,3 +102,128 @@ type ChapaPaymentMethod struct { Name string `json:"name"` DisplayName string `json:"display_name"` } + +// ChapaDirectChargeMethod is a wallet/method supported by Chapa Direct Charge API. +type ChapaDirectChargeMethod struct { + Name string `json:"name"` + DisplayName string `json:"display_name"` + AuthType string `json:"auth_type"` // "ussd" or "otp" +} + +// ChapaDirectChargeType is the ?type= query value for POST /charges. +type ChapaDirectChargeType string + +const ( + ChapaDirectChargeTelebirr ChapaDirectChargeType = "telebirr" + ChapaDirectChargeMPesa ChapaDirectChargeType = "mpesa" + ChapaDirectChargeCBEBirr ChapaDirectChargeType = "cbebirr" + ChapaDirectChargeEBirr ChapaDirectChargeType = "ebirr" + ChapaDirectChargeAwashBirr ChapaDirectChargeType = "awashbirr" + ChapaDirectChargeYaya ChapaDirectChargeType = "yaya" + ChapaDirectChargeBOAUSSD ChapaDirectChargeType = "boa_ussd" + ChapaDirectChargeCoopayEBirr ChapaDirectChargeType = "coopay-ebirr" + ChapaDirectChargeEnatBank ChapaDirectChargeType = "enat_bank" + ChapaDirectChargeAmole ChapaDirectChargeType = "amole" +) + +// ParseChapaDirectChargeType normalizes API input to a supported direct charge type. +func ParseChapaDirectChargeType(raw string) (ChapaDirectChargeType, error) { + switch strings.ToLower(strings.TrimSpace(raw)) { + case string(ChapaDirectChargeTelebirr): + return ChapaDirectChargeTelebirr, nil + case string(ChapaDirectChargeMPesa): + return ChapaDirectChargeMPesa, nil + case string(ChapaDirectChargeCBEBirr), "cbe_birr": + return ChapaDirectChargeCBEBirr, nil + case string(ChapaDirectChargeEBirr): + return ChapaDirectChargeEBirr, nil + case string(ChapaDirectChargeAwashBirr), "awash_birr": + return ChapaDirectChargeAwashBirr, nil + case string(ChapaDirectChargeYaya): + return ChapaDirectChargeYaya, nil + case string(ChapaDirectChargeBOAUSSD): + return ChapaDirectChargeBOAUSSD, nil + case string(ChapaDirectChargeCoopayEBirr), "coopay_ebirr": + return ChapaDirectChargeCoopayEBirr, nil + case string(ChapaDirectChargeEnatBank): + return ChapaDirectChargeEnatBank, nil + case string(ChapaDirectChargeAmole): + return ChapaDirectChargeAmole, nil + default: + return "", fmt.Errorf("unsupported chapa direct charge type %q", raw) + } +} + +// ChapaDirectChargePaymentMethod returns the persisted payment_method value for a direct charge. +func ChapaDirectChargePaymentMethod(chargeType ChapaDirectChargeType) string { + return "CHAPA_DIRECT:" + string(chargeType) +} + +// IsChapaPaymentMethod reports whether verify/webhook handling should use the Chapa service. +func IsChapaPaymentMethod(method string) bool { + m := strings.ToUpper(strings.TrimSpace(method)) + if m == string(PaymentProviderChapa) { + return true + } + return strings.HasPrefix(m, "CHAPA_DIRECT:") +} + +type InitiateChapaDirectChargeRequest struct { + PlanID int64 `json:"plan_id" validate:"required"` + Phone string `json:"phone" validate:"required"` + Email string `json:"email" validate:"required,email"` + PaymentMethod string `json:"payment_method" validate:"required"` +} + +type InitiateChapaDirectChargeResponse struct { + PaymentID int64 `json:"payment_id"` + SessionID string `json:"session_id"` // tx_ref for verify polling + ChapaReference string `json:"chapa_reference,omitempty"` + RequestID string `json:"request_id,omitempty"` // OTP flows only + AuthType string `json:"auth_type,omitempty"` // ussd | otp + RequiresAuthorize bool `json:"requires_authorize"` + Message string `json:"message"` + PortalHTML string `json:"portal_html,omitempty"` + Amount float64 `json:"amount"` + Currency string `json:"currency"` + ExpiresAt string `json:"expires_at"` +} + +type AuthorizeChapaDirectChargeRequest struct { + SessionID string `json:"session_id" validate:"required"` // tx_ref from initiate + RequestID string `json:"request_id" validate:"required"` + OTP string `json:"otp" validate:"required"` +} + +type AuthorizeChapaDirectChargeResponse struct { + Success bool `json:"success"` + Message string `json:"message"` + PaymentID int64 `json:"payment_id,omitempty"` +} + +type ChapaDirectChargeResponse struct { + Status string `json:"status"` + Message string `json:"message"` + Data json.RawMessage `json:"data"` +} + +type ChapaDirectChargeData struct { + Reference string `json:"reference"` + Status string `json:"status"` + AuthType string `json:"auth_type"` + PortalHTML string `json:"data"` // enat_bank portal HTML is returned in data + Meta *ChapaDirectChargeMeta `json:"meta"` +} + +type ChapaDirectChargeMeta struct { + Message string `json:"message"` + RefID string `json:"ref_id"` + VerificationType string `json:"verification_type"` + Data string `json:"data"` + PaymentStatus string `json:"payment_status"` +} + +type ChapaAuthorizeDirectChargeResponse struct { + Status string `json:"status"` + Message string `json:"message"` +} diff --git a/internal/domain/chapa_direct_test.go b/internal/domain/chapa_direct_test.go new file mode 100644 index 00000000..e42eafe8 --- /dev/null +++ b/internal/domain/chapa_direct_test.go @@ -0,0 +1,28 @@ +package domain + +import "testing" + +func TestParseChapaDirectChargeType(t *testing.T) { + got, err := ParseChapaDirectChargeType("telebirr") + if err != nil || got != ChapaDirectChargeTelebirr { + t.Fatalf("got %q err=%v", got, err) + } +} + +func TestIsChapaPaymentMethod(t *testing.T) { + if !IsChapaPaymentMethod("CHAPA") { + t.Fatal("expected CHAPA") + } + if !IsChapaPaymentMethod("CHAPA_DIRECT:telebirr") { + t.Fatal("expected CHAPA_DIRECT prefix") + } + if IsChapaPaymentMethod("ARIFPAY") { + t.Fatal("did not expect ARIFPAY") + } +} + +func TestChapaDirectChargePaymentMethod(t *testing.T) { + if got := ChapaDirectChargePaymentMethod(ChapaDirectChargeTelebirr); got != "CHAPA_DIRECT:telebirr" { + t.Fatalf("got %q", got) + } +} diff --git a/internal/services/chapa/direct_charge.go b/internal/services/chapa/direct_charge.go new file mode 100644 index 00000000..db8f9274 --- /dev/null +++ b/internal/services/chapa/direct_charge.go @@ -0,0 +1,393 @@ +package chapa + +import ( + "Yimaru-Backend/internal/domain" + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "strings" + "time" + + "github.com/google/uuid" +) + +var ( + ErrInvalidChapaDirectChargeMethod = errors.New("invalid chapa direct charge method") + ErrChapaDirectChargeFailed = errors.New("chapa direct charge failed") +) + +type subscriptionPaymentPrep struct { + Plan *domain.SubscriptionPlan + Email string + TxRef string + ExpiresAt time.Time +} + +func (s *Service) prepareSubscriptionPayment(ctx context.Context, userID, planID int64, email string) (*subscriptionPaymentPrep, error) { + plan, err := s.subscriptionStore.GetSubscriptionPlanByID(ctx, planID) + if err != nil { + return nil, fmt.Errorf("failed to get subscription plan: %w", err) + } + if !plan.IsActive { + return nil, errors.New("subscription plan is not active") + } + + hasActive, err := s.subscriptionStore.HasActiveSubscriptionByCategory(ctx, userID, plan.Category) + if err != nil { + return nil, fmt.Errorf("failed to check active subscription: %w", err) + } + if hasActive { + return nil, errors.New("user already has an active subscription for this category") + } + + user, err := s.userStore.GetUserByID(ctx, userID) + if err != nil { + return nil, fmt.Errorf("failed to get user: %w", err) + } + + resolvedEmail := strings.TrimSpace(email) + if resolvedEmail == "" { + resolvedEmail = user.Email + } + if resolvedEmail == "" { + return nil, errors.New("email is required for payment") + } + + return &subscriptionPaymentPrep{ + Plan: plan, + Email: resolvedEmail, + TxRef: uuid.NewString(), + ExpiresAt: time.Now().Add(15 * time.Minute), + }, nil +} + +// InitiateDirectChargeSubscription starts a Chapa Direct Charge for a subscription plan. +func (s *Service) InitiateDirectChargeSubscription(ctx context.Context, userID int64, req domain.InitiateChapaDirectChargeRequest) (*domain.InitiateChapaDirectChargeResponse, error) { + if err := s.configured(); err != nil { + return nil, err + } + + chargeType, err := domain.ParseChapaDirectChargeType(req.PaymentMethod) + if err != nil { + return nil, fmt.Errorf("%w: %s", ErrInvalidChapaDirectChargeMethod, err.Error()) + } + + prep, err := s.prepareSubscriptionPayment(ctx, userID, req.PlanID, req.Email) + if err != nil { + return nil, err + } + + phone := formatChapaPhone(req.Phone) + if phone == "" { + user, userErr := s.userStore.GetUserByID(ctx, userID) + if userErr == nil && user.PhoneNumber != "" { + phone = formatChapaPhone(user.PhoneNumber) + } + } + if phone == "" { + return nil, errors.New("phone is required for direct charge") + } + + method := domain.ChapaDirectChargePaymentMethod(chargeType) + payment, err := s.paymentStore.CreatePayment(ctx, domain.CreatePaymentInput{ + UserID: userID, + PlanID: &req.PlanID, + Amount: prep.Plan.Price, + Currency: prep.Plan.Currency, + PaymentMethod: &method, + Nonce: prep.TxRef, + ExpiresAt: &prep.ExpiresAt, + }) + if err != nil { + return nil, fmt.Errorf("failed to create payment record: %w", err) + } + + chargeData, err := s.initiateDirectCharge(ctx, chargeType, directChargeFields{ + Amount: formatAmount(prep.Plan.Price), + Currency: normalizeCurrency(prep.Plan.Currency), + Mobile: phone, + TxRef: prep.TxRef, + Email: prep.Email, + }) + if err != nil { + _ = s.paymentStore.UpdatePaymentStatus(ctx, payment.ID, string(domain.PaymentStatusFailed)) + return nil, err + } + + chapaRef := chargeData.reference() + requestID := chargeData.requestID() + authType := strings.ToLower(strings.TrimSpace(chargeData.authType())) + if authType == "" { + authType = strings.ToLower(strings.TrimSpace(chargeData.metaVerificationType())) + } + requiresAuthorize := authType == "otp" || strings.EqualFold(chargeData.metaVerificationType(), "otp") + + if chapaRef != "" { + if err := s.paymentStore.UpdatePaymentSessionID(ctx, payment.ID, chapaRef, ""); err != nil { + return nil, fmt.Errorf("failed to update payment session: %w", err) + } + } + if !requiresAuthorize { + _ = s.paymentStore.UpdatePaymentStatus(ctx, payment.ID, string(domain.PaymentStatusProcessing)) + } + + message := chargeData.userMessage() + if message == "" { + if requiresAuthorize { + message = "OTP sent to your phone. Authorize the payment to continue." + } else { + message = "USSD push sent to your phone. Approve the payment to continue." + } + } + + return &domain.InitiateChapaDirectChargeResponse{ + PaymentID: payment.ID, + SessionID: prep.TxRef, + ChapaReference: chapaRef, + RequestID: requestID, + AuthType: authType, + RequiresAuthorize: requiresAuthorize, + Message: message, + PortalHTML: chargeData.portalHTML(), + Amount: prep.Plan.Price, + Currency: prep.Plan.Currency, + ExpiresAt: prep.ExpiresAt.Format(time.RFC3339), + }, nil +} + +// AuthorizeDirectChargeSubscription completes OTP-based Chapa direct charge authorization. +func (s *Service) AuthorizeDirectChargeSubscription(ctx context.Context, userID int64, req domain.AuthorizeChapaDirectChargeRequest) (*domain.AuthorizeChapaDirectChargeResponse, error) { + if err := s.configured(); err != nil { + return nil, err + } + if strings.TrimSpace(s.cfg.CHAPA_ENCRYPTION_KEY) == "" { + return nil, ErrChapaEncryptionNotConfigured + } + + payment, err := s.lookupPayment(ctx, req.SessionID) + if err != nil { + return nil, ErrPaymentNotFound + } + if payment.UserID != userID { + return nil, errors.New("unauthorized") + } + if payment.PaymentMethod == nil || !domain.IsChapaPaymentMethod(*payment.PaymentMethod) { + return nil, ErrInvalidChapaDirectChargeMethod + } + if payment.Status == string(domain.PaymentStatusSuccess) { + return &domain.AuthorizeChapaDirectChargeResponse{ + Success: true, + Message: "Payment already completed", + PaymentID: payment.ID, + }, nil + } + + chargeType, err := chapaDirectChargeTypeFromPaymentMethod(*payment.PaymentMethod) + if err != nil { + return nil, err + } + + reference := derefString(payment.SessionID) + if reference == "" { + return nil, errors.New("missing chapa reference on payment") + } + + encrypted, err := encryptChapaDirectChargePayload(s.cfg.CHAPA_ENCRYPTION_KEY, req.RequestID, req.OTP) + if err != nil { + return nil, err + } + + body, statusCode, err := s.postMultipart(ctx, "/validate?type="+string(chargeType), map[string]string{ + "reference": reference, + "client": encrypted, + }) + if err != nil { + return nil, err + } + if statusCode != http.StatusOK { + return nil, fmt.Errorf("%w: %s", ErrChapaDirectChargeFailed, string(body)) + } + + var result domain.ChapaAuthorizeDirectChargeResponse + if err := json.Unmarshal(body, &result); err != nil { + return nil, fmt.Errorf("invalid authorize response from Chapa: %w", err) + } + if !strings.EqualFold(result.Status, "success") { + return &domain.AuthorizeChapaDirectChargeResponse{ + Success: false, + Message: result.Message, + }, nil + } + + if err := s.paymentStore.UpdatePaymentStatus(ctx, payment.ID, string(domain.PaymentStatusProcessing)); err != nil { + return nil, err + } + + verified, err := s.VerifyPayment(ctx, payment.Nonce) + if err != nil { + return &domain.AuthorizeChapaDirectChargeResponse{ + Success: true, + Message: "Authorization accepted. Payment verification is still in progress.", + PaymentID: payment.ID, + }, nil + } + + msg := "Payment authorized successfully" + if verified.Status != string(domain.PaymentStatusSuccess) { + msg = "Authorization accepted. Complete approval on your phone if prompted, then verify again." + } + + return &domain.AuthorizeChapaDirectChargeResponse{ + Success: true, + Message: msg, + PaymentID: payment.ID, + }, nil +} + +func (s *Service) GetDirectChargeMethods() []domain.ChapaDirectChargeMethod { + return []domain.ChapaDirectChargeMethod{ + {Name: string(domain.ChapaDirectChargeTelebirr), DisplayName: "Telebirr", AuthType: "ussd"}, + {Name: string(domain.ChapaDirectChargeMPesa), DisplayName: "M-Pesa", AuthType: "ussd"}, + {Name: string(domain.ChapaDirectChargeCBEBirr), DisplayName: "CBE Birr", AuthType: "otp"}, + {Name: string(domain.ChapaDirectChargeEBirr), DisplayName: "E-Birr", AuthType: "otp"}, + {Name: string(domain.ChapaDirectChargeAwashBirr), DisplayName: "Awash Birr", AuthType: "ussd"}, + {Name: string(domain.ChapaDirectChargeYaya), DisplayName: "Yaya Wallet", AuthType: "ussd"}, + {Name: string(domain.ChapaDirectChargeBOAUSSD), DisplayName: "BOA USSD", AuthType: "ussd"}, + {Name: string(domain.ChapaDirectChargeCoopayEBirr), DisplayName: "Coopay E-Birr", AuthType: "ussd"}, + {Name: string(domain.ChapaDirectChargeAmole), DisplayName: "Amole", AuthType: "otp"}, + {Name: string(domain.ChapaDirectChargeEnatBank), DisplayName: "Enat Bank", AuthType: "portal"}, + } +} + +type directChargeFields struct { + Amount string + Currency string + Mobile string + TxRef string + Email string +} + +type parsedDirectChargeData struct { + flat domain.ChapaDirectChargeData + nested domain.ChapaDirectChargeData + raw domain.ChapaDirectChargeData +} + +func (p parsedDirectChargeData) reference() string { + if ref := strings.TrimSpace(p.nested.Reference); ref != "" { + return ref + } + if p.nested.Meta != nil && strings.TrimSpace(p.nested.Meta.RefID) != "" { + return strings.TrimSpace(p.nested.Meta.RefID) + } + if ref := strings.TrimSpace(p.flat.Reference); ref != "" { + return ref + } + return "" +} + +func (p parsedDirectChargeData) requestID() string { + if p.nested.Meta != nil { + if v := strings.TrimSpace(p.nested.Meta.Data); v != "" { + return v + } + } + return "" +} + +func (p parsedDirectChargeData) authType() string { + if v := strings.TrimSpace(p.nested.AuthType); v != "" { + return v + } + return strings.TrimSpace(p.flat.AuthType) +} + +func (p parsedDirectChargeData) metaVerificationType() string { + if p.nested.Meta != nil { + return strings.TrimSpace(p.nested.Meta.VerificationType) + } + return "" +} + +func (p parsedDirectChargeData) userMessage() string { + if p.nested.Meta != nil && strings.TrimSpace(p.nested.Meta.Message) != "" { + return strings.TrimSpace(p.nested.Meta.Message) + } + return "" +} + +func (p parsedDirectChargeData) portalHTML() string { + if html := strings.TrimSpace(p.nested.PortalHTML); html != "" && strings.Contains(strings.ToLower(html), "<") { + return html + } + return "" +} + +func (s *Service) initiateDirectCharge(ctx context.Context, chargeType domain.ChapaDirectChargeType, fields directChargeFields) (parsedDirectChargeData, error) { + endpoint := "/charges?type=" + string(chargeType) + body, statusCode, err := s.postMultipart(ctx, endpoint, map[string]string{ + "amount": fields.Amount, + "currency": fields.Currency, + "mobile": fields.Mobile, + "tx_ref": fields.TxRef, + "email": fields.Email, + }) + if err != nil { + return parsedDirectChargeData{}, err + } + if statusCode != http.StatusOK { + return parsedDirectChargeData{}, fmt.Errorf("%w (status %d): %s", ErrChapaDirectChargeFailed, statusCode, string(body)) + } + + var envelope domain.ChapaDirectChargeResponse + if err := json.Unmarshal(body, &envelope); err != nil { + return parsedDirectChargeData{}, fmt.Errorf("invalid direct charge response from Chapa: %w", err) + } + if !strings.EqualFold(envelope.Status, "success") { + return parsedDirectChargeData{}, fmt.Errorf("%w: %s", ErrChapaDirectChargeFailed, envelope.Message) + } + + parsed, err := parseDirectChargeData(envelope.Data) + if err != nil { + return parsedDirectChargeData{}, err + } + return parsed, nil +} + +func parseDirectChargeData(raw json.RawMessage) (parsedDirectChargeData, error) { + if len(raw) == 0 { + return parsedDirectChargeData{}, fmt.Errorf("%w: empty data", ErrChapaDirectChargeFailed) + } + + var flat domain.ChapaDirectChargeData + if err := json.Unmarshal(raw, &flat); err != nil { + return parsedDirectChargeData{}, err + } + + var nested domain.ChapaDirectChargeData + _ = json.Unmarshal(raw, &nested) + + return parsedDirectChargeData{ + flat: flat, + nested: nested, + raw: flat, + }, nil +} + +func chapaDirectChargeTypeFromPaymentMethod(method string) (domain.ChapaDirectChargeType, error) { + const prefix = "CHAPA_DIRECT:" + upper := strings.ToUpper(strings.TrimSpace(method)) + if !strings.HasPrefix(upper, prefix) { + return "", ErrInvalidChapaDirectChargeMethod + } + return domain.ParseChapaDirectChargeType(strings.ToLower(strings.TrimPrefix(upper, prefix))) +} + +func derefString(p *string) string { + if p == nil { + return "" + } + return *p +} diff --git a/internal/services/chapa/direct_charge_test.go b/internal/services/chapa/direct_charge_test.go new file mode 100644 index 00000000..7cb0b35d --- /dev/null +++ b/internal/services/chapa/direct_charge_test.go @@ -0,0 +1,64 @@ +package chapa + +import ( + "encoding/json" + "testing" +) + +func TestParseDirectChargeData_flatReference(t *testing.T) { + raw := []byte(`{"reference":"CHcuKjgnN0Dk0","status":"pending"}`) + parsed, err := parseDirectChargeData(raw) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if got := parsed.reference(); got != "CHcuKjgnN0Dk0" { + t.Fatalf("reference=%q", got) + } +} + +func TestParseDirectChargeData_nestedMeta(t *testing.T) { + raw := []byte(`{ + "auth_type":"otp", + "meta":{ + "message":"OTP sent", + "ref_id":"CHmetaRef", + "verification_type":"otp", + "data":"request-token-123" + } + }`) + parsed, err := parseDirectChargeData(json.RawMessage(raw)) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if got := parsed.reference(); got != "CHmetaRef" { + t.Fatalf("reference=%q", got) + } + if got := parsed.requestID(); got != "request-token-123" { + t.Fatalf("requestID=%q", got) + } + if !parsed.requiresAuthorize() { + t.Fatal("expected authorize required") + } +} + +func (p parsedDirectChargeData) requiresAuthorize() bool { + authType := p.authType() + if authType == "otp" { + return true + } + return p.metaVerificationType() == "otp" +} + +func TestEncryptChapaDirectChargePayload_requiresKey(t *testing.T) { + _, err := encryptChapaDirectChargePayload("", "req", "1234") + if err == nil { + t.Fatal("expected error for missing key") + } +} + +func TestPkcs7Pad(t *testing.T) { + padded := pkcs7Pad([]byte("hello"), 8) + if len(padded)%8 != 0 { + t.Fatalf("expected multiple of block size, got %d", len(padded)) + } +} diff --git a/internal/services/chapa/encryption.go b/internal/services/chapa/encryption.go new file mode 100644 index 00000000..163b0f72 --- /dev/null +++ b/internal/services/chapa/encryption.go @@ -0,0 +1,86 @@ +package chapa + +import ( + "bytes" + "crypto/des" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "strings" +) + +var ErrChapaEncryptionNotConfigured = errors.New("chapa encryption key is not configured") + +func encryptChapaDirectChargePayload(encryptionKey, requestID, otp string) (string, error) { + key, err := decodeTripleDESKey(encryptionKey) + if err != nil { + return "", err + } + + payload, err := json.Marshal(map[string]string{ + "requestID": requestID, + "otp": otp, + }) + if err != nil { + return "", fmt.Errorf("marshal chapa encrypt payload: %w", err) + } + + encrypted, err := tripleDESECBEncrypt(key, payload) + if err != nil { + return "", err + } + return base64.StdEncoding.EncodeToString(encrypted), nil +} + +func decodeTripleDESKey(raw string) ([]byte, error) { + raw = stringsTrim(raw) + if raw == "" { + return nil, ErrChapaEncryptionNotConfigured + } + + if decoded, err := base64.StdEncoding.DecodeString(raw); err == nil && len(decoded) == 24 { + return decoded, nil + } + + key := []byte(raw) + if len(key) < 24 { + padded := make([]byte, 24) + copy(padded, key) + return padded, nil + } + if len(key) > 24 { + return key[:24], nil + } + return key, nil +} + +func tripleDESECBEncrypt(key, plaintext []byte) ([]byte, error) { + block, err := des.NewTripleDESCipher(key) + if err != nil { + return nil, fmt.Errorf("invalid chapa 3des key: %w", err) + } + + padded := pkcs7Pad(plaintext, block.BlockSize()) + out := make([]byte, len(padded)) + for i := 0; i < len(padded); i += block.BlockSize() { + block.Encrypt(out[i:i+block.BlockSize()], padded[i:i+block.BlockSize()]) + } + return out, nil +} + +func pkcs7Pad(data []byte, blockSize int) []byte { + if blockSize <= 0 { + return data + } + padLen := blockSize - (len(data) % blockSize) + if padLen == 0 { + padLen = blockSize + } + padding := bytes.Repeat([]byte{byte(padLen)}, padLen) + return append(append([]byte(nil), data...), padding...) +} + +func stringsTrim(s string) string { + return strings.TrimSpace(s) +} \ No newline at end of file diff --git a/internal/services/chapa/multipart.go b/internal/services/chapa/multipart.go new file mode 100644 index 00000000..ebcb1c95 --- /dev/null +++ b/internal/services/chapa/multipart.go @@ -0,0 +1,44 @@ +package chapa + +import ( + "bytes" + "context" + "fmt" + "io" + "mime/multipart" + "net/http" + "strings" +) + +func (s *Service) postMultipart(ctx context.Context, endpoint string, fields map[string]string) ([]byte, int, error) { + var body bytes.Buffer + writer := multipart.NewWriter(&body) + for key, value := range fields { + if err := writer.WriteField(key, value); err != nil { + return nil, 0, fmt.Errorf("write multipart field %s: %w", key, err) + } + } + if err := writer.Close(); err != nil { + return nil, 0, err + } + + url := strings.TrimSuffix(s.cfg.CHAPA_BASE_URL, "/") + endpoint + req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, &body) + if err != nil { + return nil, 0, err + } + req.Header.Set("Content-Type", writer.FormDataContentType()) + req.Header.Set("Authorization", "Bearer "+s.cfg.CHAPA_SECRET_KEY) + + resp, err := s.httpClient.Do(req) + if err != nil { + return nil, 0, fmt.Errorf("chapa multipart request failed: %w", err) + } + defer resp.Body.Close() + + respBody, err := io.ReadAll(resp.Body) + if err != nil { + return nil, resp.StatusCode, err + } + return respBody, resp.StatusCode, nil +} diff --git a/internal/services/chapa/service.go b/internal/services/chapa/service.go index a89cd196..4745a91b 100644 --- a/internal/services/chapa/service.go +++ b/internal/services/chapa/service.go @@ -20,8 +20,6 @@ import ( "Yimaru-Backend/internal/domain" "Yimaru-Backend/internal/ports" learnernotifications "Yimaru-Backend/internal/services/learnernotifications" - - "github.com/google/uuid" ) var ( @@ -74,20 +72,9 @@ func (s *Service) InitiateSubscriptionPayment(ctx context.Context, userID int64, return nil, err } - plan, err := s.subscriptionStore.GetSubscriptionPlanByID(ctx, req.PlanID) + prep, err := s.prepareSubscriptionPayment(ctx, userID, req.PlanID, req.Email) if err != nil { - return nil, fmt.Errorf("failed to get subscription plan: %w", err) - } - if !plan.IsActive { - return nil, errors.New("subscription plan is not active") - } - - hasActive, err := s.subscriptionStore.HasActiveSubscriptionByCategory(ctx, userID, plan.Category) - if err != nil { - return nil, fmt.Errorf("failed to check active subscription: %w", err) - } - if hasActive { - return nil, errors.New("user already has an active subscription for this category") + return nil, err } user, err := s.userStore.GetUserByID(ctx, userID) @@ -104,32 +91,23 @@ func (s *Service) InitiateSubscriptionPayment(ctx context.Context, userID int64, lastName = "User" } - email := strings.TrimSpace(req.Email) - if email == "" { - email = user.Email - } - if email == "" { - return nil, errors.New("email is required for payment") - } - phone := formatChapaPhone(req.Phone) if phone == "" && user.PhoneNumber != "" { phone = formatChapaPhone(user.PhoneNumber) } - txRef := uuid.NewString() expiresAt := time.Now().Add(3 * time.Hour) payment, err := s.paymentStore.CreatePayment(ctx, domain.CreatePaymentInput{ UserID: userID, PlanID: &req.PlanID, - Amount: plan.Price, - Currency: plan.Currency, + Amount: prep.Plan.Price, + Currency: prep.Plan.Currency, PaymentMethod: func() *string { v := string(domain.PaymentProviderChapa) return &v }(), - Nonce: txRef, + Nonce: prep.TxRef, ExpiresAt: &expiresAt, }) if err != nil { @@ -137,34 +115,34 @@ func (s *Service) InitiateSubscriptionPayment(ctx context.Context, userID int64, } initReq := domain.ChapaInitializeRequest{ - Amount: formatAmount(plan.Price), - Currency: normalizeCurrency(plan.Currency), - Email: email, + Amount: formatAmount(prep.Plan.Price), + Currency: normalizeCurrency(prep.Plan.Currency), + Email: prep.Email, FirstName: firstName, LastName: lastName, PhoneNumber: phone, - TxRef: txRef, + TxRef: prep.TxRef, CallbackURL: s.cfg.CHAPA_CALLBACK_URL, ReturnURL: s.cfg.CHAPA_RETURN_URL, } initReq.Customization.Title = sanitizeChapaCustomization("Yimaru LMS") - initReq.Customization.Description = chapaSubscriptionDescription(plan.Name) + initReq.Customization.Description = chapaSubscriptionDescription(prep.Plan.Name) checkoutURL, err := s.initializeTransaction(ctx, initReq) if err != nil { return nil, err } - if err := s.paymentStore.UpdatePaymentSessionID(ctx, payment.ID, txRef, checkoutURL); err != nil { + if err := s.paymentStore.UpdatePaymentSessionID(ctx, payment.ID, prep.TxRef, checkoutURL); err != nil { return nil, fmt.Errorf("failed to update payment session: %w", err) } return &domain.InitiateSubscriptionPaymentResponse{ PaymentID: payment.ID, - SessionID: txRef, + SessionID: prep.TxRef, PaymentURL: checkoutURL, - Amount: plan.Price, - Currency: plan.Currency, + Amount: prep.Plan.Price, + Currency: prep.Plan.Currency, ExpiresAt: expiresAt.Format(time.RFC3339), }, nil } diff --git a/internal/web_server/handlers/arifpay.go b/internal/web_server/handlers/arifpay.go index 48abc623..addc9f62 100644 --- a/internal/web_server/handlers/arifpay.go +++ b/internal/web_server/handlers/arifpay.go @@ -287,6 +287,9 @@ func (h *Handler) verifyPaymentByProvider(ctx context.Context, ref string) (*dom } if payment.PaymentMethod != nil { + if domain.IsChapaPaymentMethod(*payment.PaymentMethod) { + return h.chapaSvc.VerifyPayment(ctx, ref) + } if provider, err := domain.ParsePaymentProvider(*payment.PaymentMethod); err == nil { switch provider { case domain.PaymentProviderChapa: diff --git a/internal/web_server/handlers/chapa_direct.go b/internal/web_server/handlers/chapa_direct.go new file mode 100644 index 00000000..eddecb57 --- /dev/null +++ b/internal/web_server/handlers/chapa_direct.go @@ -0,0 +1,161 @@ +package handlers + +import ( + "Yimaru-Backend/internal/domain" + "Yimaru-Backend/internal/services/chapa" + "errors" + "fmt" + + "github.com/gofiber/fiber/v2" +) + +type initiateChapaDirectPaymentReq struct { + PlanID int64 `json:"plan_id" validate:"required"` + Phone string `json:"phone" validate:"required"` + Email string `json:"email" validate:"required,email"` + PaymentMethod string `json:"payment_method" validate:"required"` +} + +type authorizeChapaDirectPaymentReq struct { + SessionID string `json:"session_id" validate:"required"` + RequestID string `json:"request_id" validate:"required"` + OTP string `json:"otp" validate:"required"` +} + +// InitiateChapaDirectPayment godoc +// @Summary Initiate Chapa direct charge subscription payment +// @Description Starts a Chapa Direct Charge (USSD push or OTP) for a subscription plan without hosted checkout redirect. +// @Tags payments +// @Accept json +// @Produce json +// @Param body body initiateChapaDirectPaymentReq true "Chapa direct charge request" +// @Success 200 {object} domain.Response +// @Failure 400 {object} domain.ErrorResponse +// @Failure 500 {object} domain.ErrorResponse +// @Router /api/v1/payments/chapa/direct [post] +func (h *Handler) InitiateChapaDirectPayment(c *fiber.Ctx) error { + userID, ok := c.Locals("user_id").(int64) + if !ok { + return c.Status(fiber.StatusUnauthorized).JSON(domain.ErrorResponse{Message: "Unauthorized"}) + } + + var req initiateChapaDirectPaymentReq + if err := c.BodyParser(&req); err != nil { + return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ + Message: "Invalid request body", + Error: err.Error(), + }) + } + + result, err := h.chapaSvc.InitiateDirectChargeSubscription(c.Context(), userID, domain.InitiateChapaDirectChargeRequest{ + PlanID: req.PlanID, + Phone: req.Phone, + Email: req.Email, + PaymentMethod: req.PaymentMethod, + }) + if err != nil { + return c.Status(chapaDirectPaymentStatus(err)).JSON(domain.ErrorResponse{ + Message: "Failed to initiate Chapa direct payment", + Error: err.Error(), + }) + } + + paymentID := result.PaymentID + h.recordActivity(c, domain.ActionPaymentInitiated, domain.ResourcePayment, &paymentID, fmt.Sprintf("Initiated Chapa direct payment ID: %d", paymentID), nil) + + return c.JSON(domain.Response{ + Message: "Chapa direct payment initiated successfully", + Data: result, + }) +} + +// AuthorizeChapaDirectPayment godoc +// @Summary Authorize Chapa direct charge with OTP +// @Description Completes OTP authorization for Chapa direct charge methods that require it. +// @Tags payments +// @Accept json +// @Produce json +// @Param body body authorizeChapaDirectPaymentReq true "Chapa direct charge authorization request" +// @Success 200 {object} domain.Response +// @Failure 400 {object} domain.ErrorResponse +// @Failure 404 {object} domain.ErrorResponse +// @Router /api/v1/payments/chapa/direct/authorize [post] +func (h *Handler) AuthorizeChapaDirectPayment(c *fiber.Ctx) error { + userID, ok := c.Locals("user_id").(int64) + if !ok { + return c.Status(fiber.StatusUnauthorized).JSON(domain.ErrorResponse{Message: "Unauthorized"}) + } + + var req authorizeChapaDirectPaymentReq + if err := c.BodyParser(&req); err != nil { + return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ + Message: "Invalid request body", + Error: err.Error(), + }) + } + + result, err := h.chapaSvc.AuthorizeDirectChargeSubscription(c.Context(), userID, domain.AuthorizeChapaDirectChargeRequest{ + SessionID: req.SessionID, + RequestID: req.RequestID, + OTP: req.OTP, + }) + if err != nil { + status := fiber.StatusInternalServerError + if errors.Is(err, chapa.ErrPaymentNotFound) { + status = fiber.StatusNotFound + } + if err.Error() == "unauthorized" { + status = fiber.StatusForbidden + } + return c.Status(status).JSON(domain.ErrorResponse{ + Message: "Failed to authorize Chapa direct payment", + Error: err.Error(), + }) + } + + if !result.Success { + return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ + Message: result.Message, + }) + } + + var paymentID *int64 + if result.PaymentID > 0 { + paymentID = &result.PaymentID + } + h.recordActivity(c, domain.ActionPaymentVerified, domain.ResourcePayment, paymentID, "Chapa direct payment authorized", nil) + + return c.JSON(domain.Response{ + Message: result.Message, + Data: result, + }) +} + +// GetChapaDirectPaymentMethods godoc +// @Summary Get Chapa direct charge payment methods +// @Description Returns wallet methods supported by Chapa Direct Charge API (USSD push and OTP flows). +// @Tags payments +// @Produce json +// @Success 200 {object} domain.Response +// @Router /api/v1/payments/chapa/direct/methods [get] +func (h *Handler) GetChapaDirectPaymentMethods(c *fiber.Ctx) error { + return c.JSON(domain.Response{ + Message: "Chapa direct payment methods retrieved successfully", + Data: h.chapaSvc.GetDirectChargeMethods(), + }) +} + +func chapaDirectPaymentStatus(err error) int { + switch { + case errors.Is(err, chapa.ErrChapaNotConfigured): + return fiber.StatusServiceUnavailable + case errors.Is(err, chapa.ErrInvalidChapaDirectChargeMethod): + return fiber.StatusBadRequest + case err.Error() == "user already has an active subscription": + return fiber.StatusConflict + case err.Error() == "subscription plan is not active", err.Error() == "phone is required for direct charge": + return fiber.StatusBadRequest + default: + return fiber.StatusInternalServerError + } +} diff --git a/internal/web_server/routes.go b/internal/web_server/routes.go index 76d0cb87..b93af986 100644 --- a/internal/web_server/routes.go +++ b/internal/web_server/routes.go @@ -308,7 +308,12 @@ func (a *App) initAppRoutes() { groupV1.Get("/payments/chapa/callback", h.HandleChapaCallback) a.fiber.Get("/payment/success", h.HandleChapaSuccessPage) - // Direct Payments + // Chapa Direct Charge (USSD / OTP — separate from hosted checkout and ArifPay direct) + groupV1.Post("/payments/chapa/direct", a.authMiddleware, a.RequirePermission("payments.direct_initiate"), h.InitiateChapaDirectPayment) + groupV1.Post("/payments/chapa/direct/authorize", a.authMiddleware, a.RequirePermission("payments.direct_verify_otp"), h.AuthorizeChapaDirectPayment) + groupV1.Get("/payments/chapa/direct/methods", h.GetChapaDirectPaymentMethods) + + // Direct Payments (ArifPay) groupV1.Post("/payments/direct", a.authMiddleware, a.RequirePermission("payments.direct_initiate"), h.InitiateDirectPayment) groupV1.Post("/payments/direct/verify-otp", a.authMiddleware, a.RequirePermission("payments.direct_verify_otp"), h.VerifyDirectPaymentOTP) groupV1.Get("/payments/direct/methods", h.GetDirectPaymentMethods)