Add web checkout link API for iOS subscription paywall.
Send checkout URLs by email or SMS via POST /subscriptions/request-checkout-link, with LEARNER_WEB_CHECKOUT_BASE_URL config, RBAC permission, rate limiting, and client integration docs. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
b7ed649874
commit
2791894e14
576
docs/web-checkout-client-integration.md
Normal file
576
docs/web-checkout-client-integration.md
Normal file
|
|
@ -0,0 +1,576 @@
|
||||||
|
# Web Checkout — Client Integration Guide
|
||||||
|
|
||||||
|
Minimal spec for a **standalone web checkout** used by iOS users (and anyone who pays outside the mobile app). The page sells subscriptions via **Chapa hosted checkout** and activates the same `user_subscriptions` rows the mobile apps use.
|
||||||
|
|
||||||
|
> **Scope:** Hosted Chapa checkout only (`POST /api/v1/subscriptions/checkout`). Do **not** use Chapa Direct Charge (`/payments/chapa/direct`) on web unless you build a custom in-page wallet flow — hosted checkout is simpler and sufficient.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Table of contents
|
||||||
|
|
||||||
|
1. [Goals](#goals)
|
||||||
|
2. [iOS paywall: email/SMS checkout link](#ios-paywall-emailsms-checkout-link)
|
||||||
|
3. [Pages & user flow](#pages--user-flow)
|
||||||
|
4. [Environment](#environment)
|
||||||
|
5. [API base & auth](#api-base--auth)
|
||||||
|
6. [Screen specs](#screen-specs)
|
||||||
|
7. [API reference](#api-reference)
|
||||||
|
8. [State machine](#state-machine)
|
||||||
|
9. [Success & return URLs](#success--return-urls)
|
||||||
|
10. [Error handling](#error-handling)
|
||||||
|
11. [Security notes](#security-notes)
|
||||||
|
12. [Optional enhancements](#optional-enhancements)
|
||||||
|
13. [Integration checklist](#integration-checklist)
|
||||||
|
14. [Quick reference](#quick-reference)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Goals
|
||||||
|
|
||||||
|
| Goal | Detail |
|
||||||
|
|------|--------|
|
||||||
|
| iOS-friendly acquisition | Subscriptions bought on web; iOS app is player-only |
|
||||||
|
| Reuse existing backend | No new payment APIs required |
|
||||||
|
| Same entitlements | After payment, `GET /subscriptions/me` unlocks content in iOS/Android |
|
||||||
|
| Minimal surface | 4 routes: plans → login → checkout → success |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## iOS paywall: email/SMS checkout link
|
||||||
|
|
||||||
|
When the iOS app shows **Subscription required** (locked content), it should **not** open the web checkout in-app. Instead, call the backend to **email or SMS the checkout link** to the learner.
|
||||||
|
|
||||||
|
### Mobile flow
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
sequenceDiagram
|
||||||
|
participant iOS as iOS app
|
||||||
|
participant API as Yimaru API
|
||||||
|
participant User as Email / SMS
|
||||||
|
participant Web as Web checkout app
|
||||||
|
|
||||||
|
iOS->>API: Content blocked (no subscription)
|
||||||
|
iOS->>iOS: Show "Subscription required" + optional "Send link"
|
||||||
|
iOS->>API: POST /subscriptions/request-checkout-link
|
||||||
|
API->>User: Checkout URL (email or SMS)
|
||||||
|
User->>Web: Opens link in browser
|
||||||
|
Web->>API: POST /subscriptions/checkout → Chapa
|
||||||
|
User->>iOS: Opens app, signs in
|
||||||
|
iOS->>API: GET /subscriptions/me
|
||||||
|
```
|
||||||
|
|
||||||
|
### API
|
||||||
|
|
||||||
|
```http
|
||||||
|
POST /api/v1/subscriptions/request-checkout-link
|
||||||
|
Authorization: Bearer <learner_token>
|
||||||
|
Content-Type: application/json
|
||||||
|
|
||||||
|
{
|
||||||
|
"plan_id": 1
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Or filter by category when plan id is unknown:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "category": "LEARN_ENGLISH" }
|
||||||
|
```
|
||||||
|
|
||||||
|
Both fields are optional; omit both for a generic `/subscribe` link.
|
||||||
|
|
||||||
|
**Response:**
|
||||||
|
|
||||||
|
| `message` (by channel) | |
|
||||||
|
|------------------------|---|
|
||||||
|
| Email | `Please check your email for the address` |
|
||||||
|
| SMS | `Please check your SMS for the address` |
|
||||||
|
|
||||||
|
**Response `data`:**
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"channel": "sms",
|
||||||
|
"destination_hint": "***5678"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
| Field | Meaning |
|
||||||
|
|-------|---------|
|
||||||
|
| `channel` | `email` or `sms` (registration contact) |
|
||||||
|
| `destination_hint` | Masked address; full link is only in the message |
|
||||||
|
|
||||||
|
### Delivery channel rules
|
||||||
|
|
||||||
|
1. Verified phone → **SMS**
|
||||||
|
2. Else verified email → **email**
|
||||||
|
3. Else phone only on file → **SMS**
|
||||||
|
4. Else email only on file → **email**
|
||||||
|
5. Both on file, neither verified → **SMS** if phone present, else email
|
||||||
|
|
||||||
|
### Rate limit
|
||||||
|
|
||||||
|
One link per **15 minutes** per user (`429` if called too soon).
|
||||||
|
|
||||||
|
### Backend env
|
||||||
|
|
||||||
|
| Variable | Example |
|
||||||
|
|----------|---------|
|
||||||
|
| `LEARNER_WEB_CHECKOUT_BASE_URL` | `https://subscribe.yimaruacademy.com` |
|
||||||
|
|
||||||
|
Links are built as:
|
||||||
|
|
||||||
|
- `{base}/subscribe/checkout?plan_id={id}` when `plan_id` is sent
|
||||||
|
- `{base}/subscribe?category=IELTS` when `category` is sent
|
||||||
|
- `{base}/subscribe` otherwise
|
||||||
|
|
||||||
|
### iOS UI guidance
|
||||||
|
|
||||||
|
- Paywall: **“Subscription required”**
|
||||||
|
- Primary action: **“Email/SMS me a link”** → calls this API once
|
||||||
|
- Success in app: show the API `message` (e.g. **“Please check your SMS for the address”**)
|
||||||
|
- Do **not** display the checkout URL in the app UI
|
||||||
|
- After user pays on web, **Refresh** / reopen app → `GET /subscriptions/me`
|
||||||
|
|
||||||
|
### Errors
|
||||||
|
|
||||||
|
| HTTP | Meaning |
|
||||||
|
|------|---------|
|
||||||
|
| `409` | Already subscribed for that plan category |
|
||||||
|
| `429` | Link sent within the last 15 minutes |
|
||||||
|
| `503` | `LEARNER_WEB_CHECKOUT_BASE_URL` not configured |
|
||||||
|
| `400` | No email/phone on account |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Pages & user flow
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
A["/subscribe"] --> B{Logged in?}
|
||||||
|
B -->|No| C["/subscribe/login"]
|
||||||
|
C --> D["POST /auth/customer-login"]
|
||||||
|
D --> A
|
||||||
|
B -->|Yes| E["Pick plan"]
|
||||||
|
E --> F["/subscribe/checkout?plan_id="]
|
||||||
|
F --> G["POST /subscriptions/checkout"]
|
||||||
|
G --> H["Redirect to Chapa payment_url"]
|
||||||
|
H --> I["Chapa payment"]
|
||||||
|
I --> J["Backend callback + success page"]
|
||||||
|
J --> K["/subscribe/success?session_id="]
|
||||||
|
K --> L["GET /payments/verify/:session_id"]
|
||||||
|
L --> M["GET /subscriptions/me"]
|
||||||
|
M --> N["Open mobile app CTA"]
|
||||||
|
```
|
||||||
|
|
||||||
|
**Happy path (returning user):**
|
||||||
|
|
||||||
|
1. Land on plan list → pick plan
|
||||||
|
2. Login if needed
|
||||||
|
3. Confirm phone + email → **Pay with Chapa**
|
||||||
|
4. Complete payment on Chapa
|
||||||
|
5. Success page confirms subscription → prompt to open iOS app
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Environment
|
||||||
|
|
||||||
|
| Variable | Example | Purpose |
|
||||||
|
|----------|---------|---------|
|
||||||
|
| `VITE_API_BASE_URL` | `https://api.yimaru.com` | Yimaru API |
|
||||||
|
| `LEARNER_WEB_CHECKOUT_BASE_URL` (backend) | `https://subscribe.yimaruacademy.com` | Base URL embedded in email/SMS links |
|
||||||
|
| `VITE_APP_STORE_URL` | `https://apps.apple.com/...` | Optional iOS download link on success |
|
||||||
|
| `VITE_PLAY_STORE_URL` | `https://play.google.com/...` | Optional Android link |
|
||||||
|
|
||||||
|
Production API base from existing docs: `https://api.yimaru.com/api/v1`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## API base & auth
|
||||||
|
|
||||||
|
All authenticated calls:
|
||||||
|
|
||||||
|
```http
|
||||||
|
Authorization: Bearer <access_token>
|
||||||
|
Content-Type: application/json
|
||||||
|
```
|
||||||
|
|
||||||
|
Store tokens in `sessionStorage` (or httpOnly cookie if you add a BFF later):
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
type AuthSession = {
|
||||||
|
access_token: string;
|
||||||
|
refresh_token: string;
|
||||||
|
user_id: number;
|
||||||
|
role: string;
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
Refresh when access token expires:
|
||||||
|
|
||||||
|
```http
|
||||||
|
POST /api/v1/auth/refresh
|
||||||
|
{ "refresh_token": "<refresh_token>" }
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Screen specs
|
||||||
|
|
||||||
|
### 1. `/subscribe` — Plan list
|
||||||
|
|
||||||
|
**Purpose:** Show purchasable plans (public; no auth required to view).
|
||||||
|
|
||||||
|
**API:**
|
||||||
|
|
||||||
|
```http
|
||||||
|
GET /api/v1/subscription-plans?active_only=true
|
||||||
|
GET /api/v1/subscription-plans?active_only=true&category=LEARN_ENGLISH
|
||||||
|
```
|
||||||
|
|
||||||
|
**Query params:**
|
||||||
|
|
||||||
|
| Param | Values | Default |
|
||||||
|
|-------|--------|---------|
|
||||||
|
| `active_only` | `true` / `false` | `true` |
|
||||||
|
| `category` | `LEARN_ENGLISH`, `IELTS`, `DUOLINGO` | all |
|
||||||
|
|
||||||
|
**Plan card fields** (from `data[]`):
|
||||||
|
|
||||||
|
| Field | UI use |
|
||||||
|
|-------|--------|
|
||||||
|
| `id` | Pass to checkout |
|
||||||
|
| `name` | Title |
|
||||||
|
| `description` | Subtitle |
|
||||||
|
| `category` | Tab/filter |
|
||||||
|
| `price`, `currency` | Price display |
|
||||||
|
| `duration_value`, `duration_unit` | Billing period (hide if `is_lifetime`) |
|
||||||
|
| `is_lifetime` | Show “One-time purchase” |
|
||||||
|
| `is_active` | Only listed when `active_only=true` |
|
||||||
|
|
||||||
|
**Actions:**
|
||||||
|
|
||||||
|
- **Subscribe** → if no session, `/subscribe/login?redirect=/subscribe/checkout?plan_id={id}`; else `/subscribe/checkout?plan_id={id}`
|
||||||
|
- Optional: **Already subscribed?** → login link
|
||||||
|
|
||||||
|
**Do not** embed Chapa or payment widgets on this page.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 2. `/subscribe/login` — Login / register
|
||||||
|
|
||||||
|
**Purpose:** Authenticate before checkout.
|
||||||
|
|
||||||
|
#### Login
|
||||||
|
|
||||||
|
```http
|
||||||
|
POST /api/v1/auth/customer-login
|
||||||
|
```
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"email": "learner@example.com",
|
||||||
|
"password": "your-password"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Or phone:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"phone_number": "0912345678",
|
||||||
|
"password": "your-password"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
OTP login (if your app supports it):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"email": "learner@example.com",
|
||||||
|
"otp_code": "123456"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Response `data`:**
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"access_token": "...",
|
||||||
|
"refresh_token": "...",
|
||||||
|
"role": "STUDENT",
|
||||||
|
"user_id": 42
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Register (minimal)
|
||||||
|
|
||||||
|
1. Optional OTP: `POST /api/v1/user/sendRegisterCode` with `{ "email" }` or `{ "phone_number" }`
|
||||||
|
2. Register:
|
||||||
|
|
||||||
|
```http
|
||||||
|
POST /api/v1/user/register
|
||||||
|
```
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"email": "learner@example.com",
|
||||||
|
"phone_number": "0912345678",
|
||||||
|
"password": "your-password",
|
||||||
|
"role": "STUDENT",
|
||||||
|
"otp_medium": "EMAIL"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Redirect to login (register does not return tokens).
|
||||||
|
|
||||||
|
**After login:** redirect to `redirect` query param or `/subscribe`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 3. `/subscribe/checkout` — Confirm & pay
|
||||||
|
|
||||||
|
**Purpose:** Collect billing contact info and start Chapa hosted checkout.
|
||||||
|
|
||||||
|
**Query:** `plan_id` (required)
|
||||||
|
|
||||||
|
**Preload:**
|
||||||
|
|
||||||
|
```http
|
||||||
|
GET /api/v1/subscription-plans/{plan_id}
|
||||||
|
GET /api/v1/subscriptions/me # warn if already active in same category
|
||||||
|
```
|
||||||
|
|
||||||
|
**Form fields:**
|
||||||
|
|
||||||
|
| Field | Source | Required |
|
||||||
|
|-------|--------|----------|
|
||||||
|
| Plan summary | plan API | read-only |
|
||||||
|
| Phone | user profile or input | yes |
|
||||||
|
| Email | user profile or input | yes |
|
||||||
|
|
||||||
|
**Pay button** → single API call:
|
||||||
|
|
||||||
|
```http
|
||||||
|
POST /api/v1/subscriptions/checkout
|
||||||
|
Authorization: Bearer <token>
|
||||||
|
```
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"plan_id": 1,
|
||||||
|
"phone": "0912345678",
|
||||||
|
"email": "learner@example.com",
|
||||||
|
"provider": "CHAPA"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Equivalent alias:** `POST /api/v1/payments/subscribe` (same handler logic).
|
||||||
|
|
||||||
|
**Success response `data`:**
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"payment_id": 100,
|
||||||
|
"session_id": "yimaru-tx-abc123",
|
||||||
|
"payment_url": "https://checkout.chapa.co/...",
|
||||||
|
"amount": 499.0,
|
||||||
|
"currency": "ETB",
|
||||||
|
"expires_at": "2026-08-24T12:00:00Z"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Client action:** persist `session_id` (e.g. `sessionStorage.checkout_session_id`), then:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
window.location.href = data.payment_url;
|
||||||
|
```
|
||||||
|
|
||||||
|
Do **not** open Chapa in an iframe; full redirect only.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 4. `/subscribe/success` — Confirmation
|
||||||
|
|
||||||
|
**Purpose:** Confirm payment and tell user to open the mobile app.
|
||||||
|
|
||||||
|
**Entry points:**
|
||||||
|
|
||||||
|
- Your page after user returns from Chapa (configure marketing site URL in success copy), **or**
|
||||||
|
- Link from backend HTML success page (`GET /api/v1/payments/chapa/success?tx_ref=...`)
|
||||||
|
|
||||||
|
**Verify payment:**
|
||||||
|
|
||||||
|
```http
|
||||||
|
GET /api/v1/payments/verify/{session_id}
|
||||||
|
Authorization: Bearer <token>
|
||||||
|
```
|
||||||
|
|
||||||
|
Use `session_id` from checkout response (stored before redirect) or `tx_ref` from Chapa redirect query.
|
||||||
|
|
||||||
|
**Response `data.status` values:**
|
||||||
|
|
||||||
|
| Status | UI |
|
||||||
|
|--------|-----|
|
||||||
|
| `SUCCESS` | ✅ Subscription active |
|
||||||
|
| `PENDING` / `PROCESSING` | ⏳ Poll again (see below) |
|
||||||
|
| `FAILED` / `CANCELLED` / `EXPIRED` | ❌ Retry checkout |
|
||||||
|
|
||||||
|
**Confirm entitlement:**
|
||||||
|
|
||||||
|
```http
|
||||||
|
GET /api/v1/subscriptions/me
|
||||||
|
```
|
||||||
|
|
||||||
|
Expect an `ACTIVE` subscription with matching `category`.
|
||||||
|
|
||||||
|
**Success UI copy (suggested):**
|
||||||
|
|
||||||
|
> Your subscription is active.
|
||||||
|
> Open **Yimaru Academy** on your iPhone and sign in with this account.
|
||||||
|
|
||||||
|
Optional buttons:
|
||||||
|
|
||||||
|
- **Open app** — custom URL scheme / Universal Link (`yimaru://` or `https://app.yimaru.com/open`) if configured
|
||||||
|
- **Download on App Store** — marketing link only; not a payment link
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## API reference
|
||||||
|
|
||||||
|
| Step | Method | Path | Auth |
|
||||||
|
|------|--------|------|------|
|
||||||
|
| List plans | `GET` | `/subscription-plans` | No |
|
||||||
|
| Get plan | `GET` | `/subscription-plans/:id` | No |
|
||||||
|
| Login | `POST` | `/auth/customer-login` | No |
|
||||||
|
| Register | `POST` | `/user/register` | No |
|
||||||
|
| Send register OTP | `POST` | `/user/sendRegisterCode` | No |
|
||||||
|
| Refresh token | `POST` | `/auth/refresh` | No |
|
||||||
|
| Request checkout link (iOS paywall) | `POST` | `/subscriptions/request-checkout-link` | Yes |
|
||||||
|
| My subscriptions | `GET` | `/subscriptions/me` | Yes |
|
||||||
|
| Start checkout | `POST` | `/subscriptions/checkout` | Yes |
|
||||||
|
| Verify payment | `GET` | `/payments/verify/:session_id` | Yes |
|
||||||
|
| Chapa methods (optional) | `GET` | `/payments/methods` | No |
|
||||||
|
|
||||||
|
**Provider value:** `"CHAPA"` (also accepts `"ARIFPAY"` but use Chapa for this spec).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## State machine
|
||||||
|
|
||||||
|
```
|
||||||
|
IDLE → CHECKOUT_INITIATED → REDIRECTED_TO_CHAPA → VERIFYING → ACTIVE | FAILED
|
||||||
|
```
|
||||||
|
|
||||||
|
| State | Trigger | Next |
|
||||||
|
|-------|---------|------|
|
||||||
|
| `CHECKOUT_INITIATED` | `POST /subscriptions/checkout` OK | Redirect to `payment_url` |
|
||||||
|
| `REDIRECTED_TO_CHAPA` | User completes or cancels on Chapa | Land on success/cancel page |
|
||||||
|
| `VERIFYING` | `GET /payments/verify/:session_id` | Poll if `PENDING` |
|
||||||
|
| `ACTIVE` | `status === SUCCESS` && `/subscriptions/me` has ACTIVE | Show success |
|
||||||
|
| `FAILED` | terminal payment status | Offer retry → checkout |
|
||||||
|
|
||||||
|
**Polling (when `PENDING` / `PROCESSING`):**
|
||||||
|
|
||||||
|
- Interval: 3s → 5s → 8s (max ~60s)
|
||||||
|
- Same verify endpoint
|
||||||
|
- Backend also processes `GET /payments/chapa/callback` and webhooks asynchronously
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Success & return URLs
|
||||||
|
|
||||||
|
Chapa redirect targets are configured **server-side** when the payment session is created (Chapa `return_url` / `callback_url` → API routes):
|
||||||
|
|
||||||
|
| Backend route | Role |
|
||||||
|
|---------------|------|
|
||||||
|
| `GET /api/v1/payments/chapa/callback` | Server verifies payment (no UI) |
|
||||||
|
| `GET /api/v1/payments/chapa/success` | HTML success page (optional fallback) |
|
||||||
|
| `GET /payment/success` | Alias for Chapa success page |
|
||||||
|
|
||||||
|
Your marketing site can host `/subscribe/success` for branded UX; pass through `session_id` or read `tx_ref` from query and call verify API.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Error handling
|
||||||
|
|
||||||
|
| HTTP | Meaning | UI |
|
||||||
|
|------|---------|-----|
|
||||||
|
| `401` | Token expired / missing | Redirect to login |
|
||||||
|
| `409` | User already has active subscription in that category | Show “Already subscribed” + link to app |
|
||||||
|
| `400` | Invalid plan, inactive plan, validation | Show `error` message |
|
||||||
|
| `503` | Chapa not configured | “Payments temporarily unavailable” |
|
||||||
|
|
||||||
|
**Checkout 409 example** — user already subscribed to Learn English; offer extend via support or pick another category (IELTS / Duolingo).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Security notes
|
||||||
|
|
||||||
|
- Never expose Chapa secret keys in the browser; only use learner JWT + public API.
|
||||||
|
- Store tokens in `sessionStorage`, not localStorage, if possible; clear on logout.
|
||||||
|
- Use HTTPS only in production.
|
||||||
|
- Do not pass access tokens in URL query strings.
|
||||||
|
- The iOS app must **not** link to this checkout URL (App Store compliance).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Optional enhancements
|
||||||
|
|
||||||
|
| Feature | Effort | Notes |
|
||||||
|
|---------|--------|-------|
|
||||||
|
| Pre-fill email/phone from `GET /user/profile` | Low | Better UX on checkout form |
|
||||||
|
| Category deep links | Low | `/subscribe?category=IELTS` |
|
||||||
|
| Cancel page | Low | `/subscribe/cancelled` when user backs out of Chapa |
|
||||||
|
| Universal Link back to iOS app | Medium | Apple associated domains |
|
||||||
|
| BFF with httpOnly cookies | Medium | Hides tokens from JS |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Integration checklist
|
||||||
|
|
||||||
|
- [ ] Plan list loads from `GET /subscription-plans`
|
||||||
|
- [ ] Login/register stores `access_token` + `refresh_token`
|
||||||
|
- [ ] Checkout calls `POST /subscriptions/checkout` with `provider: "CHAPA"`
|
||||||
|
- [ ] `session_id` saved before redirect to `payment_url`
|
||||||
|
- [ ] Success page calls `GET /payments/verify/:session_id`
|
||||||
|
- [ ] Poll while `PENDING`; confirm with `GET /subscriptions/me`
|
||||||
|
- [ ] iOS app has **no** payment UI; only entitlement check
|
||||||
|
- [ ] Error states: 401 → login, 409 → already subscribed
|
||||||
|
- [ ] Production `VITE_API_BASE_URL` points to live API
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Quick reference
|
||||||
|
|
||||||
|
**Start checkout:**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -s -X POST "$API/api/v1/subscriptions/checkout" \
|
||||||
|
-H "Authorization: Bearer $TOKEN" \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{
|
||||||
|
"plan_id": 1,
|
||||||
|
"phone": "0912345678",
|
||||||
|
"email": "learner@example.com",
|
||||||
|
"provider": "CHAPA"
|
||||||
|
}'
|
||||||
|
```
|
||||||
|
|
||||||
|
**Verify after return:**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -s "$API/api/v1/payments/verify/$SESSION_ID" \
|
||||||
|
-H "Authorization: Bearer $TOKEN"
|
||||||
|
```
|
||||||
|
|
||||||
|
**Confirm access:**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -s "$API/api/v1/subscriptions/me" \
|
||||||
|
-H "Authorization: Bearer $TOKEN"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*Aligns with Yimaru API `production` branch — Chapa hosted checkout via `SubscribeWithPayment` / `InitiateSubscriptionPayment`.*
|
||||||
|
|
@ -141,6 +141,7 @@ type Config struct {
|
||||||
TeamPasswordResetBaseURL string
|
TeamPasswordResetBaseURL string
|
||||||
TeamInviteExpiry time.Duration
|
TeamInviteExpiry time.Duration
|
||||||
LearnerAppBaseURL string
|
LearnerAppBaseURL string
|
||||||
|
LearnerWebCheckoutBaseURL string
|
||||||
PasswordResetBaseURL string
|
PasswordResetBaseURL string
|
||||||
RedisAddr string
|
RedisAddr string
|
||||||
KafkaBrokers []string
|
KafkaBrokers []string
|
||||||
|
|
@ -499,6 +500,7 @@ func (c *Config) loadEnv() error {
|
||||||
c.TeamInviteExpiry = time.Duration(inviteExpiryHours) * time.Hour
|
c.TeamInviteExpiry = time.Duration(inviteExpiryHours) * time.Hour
|
||||||
|
|
||||||
c.LearnerAppBaseURL = strings.TrimRight(strings.TrimSpace(os.Getenv("LEARNER_APP_BASE_URL")), "/")
|
c.LearnerAppBaseURL = strings.TrimRight(strings.TrimSpace(os.Getenv("LEARNER_APP_BASE_URL")), "/")
|
||||||
|
c.LearnerWebCheckoutBaseURL = strings.TrimRight(strings.TrimSpace(os.Getenv("LEARNER_WEB_CHECKOUT_BASE_URL")), "/")
|
||||||
c.PasswordResetBaseURL = strings.TrimSpace(os.Getenv("PASSWORD_RESET_BASE_URL"))
|
c.PasswordResetBaseURL = strings.TrimSpace(os.Getenv("PASSWORD_RESET_BASE_URL"))
|
||||||
|
|
||||||
c.FCMServiceAccountKey = strings.TrimSpace(os.Getenv("FCM_SERVICE_ACCOUNT_KEY"))
|
c.FCMServiceAccountKey = strings.TrimSpace(os.Getenv("FCM_SERVICE_ACCOUNT_KEY"))
|
||||||
|
|
|
||||||
|
|
@ -108,6 +108,7 @@ const (
|
||||||
ActionSubscriptionCreated ActivityAction = "SUBSCRIPTION_CREATED"
|
ActionSubscriptionCreated ActivityAction = "SUBSCRIPTION_CREATED"
|
||||||
ActionSubscriptionCancelled ActivityAction = "SUBSCRIPTION_CANCELLED"
|
ActionSubscriptionCancelled ActivityAction = "SUBSCRIPTION_CANCELLED"
|
||||||
ActionSubscriptionExtended ActivityAction = "SUBSCRIPTION_EXTENDED"
|
ActionSubscriptionExtended ActivityAction = "SUBSCRIPTION_EXTENDED"
|
||||||
|
ActionSubscriptionCheckoutLinkSent ActivityAction = "SUBSCRIPTION_CHECKOUT_LINK_SENT"
|
||||||
ActionSubscriptionAutoRenewUpdated ActivityAction = "SUBSCRIPTION_AUTO_RENEW_UPDATED"
|
ActionSubscriptionAutoRenewUpdated ActivityAction = "SUBSCRIPTION_AUTO_RENEW_UPDATED"
|
||||||
ActionPaymentInitiated ActivityAction = "PAYMENT_INITIATED"
|
ActionPaymentInitiated ActivityAction = "PAYMENT_INITIATED"
|
||||||
ActionPaymentVerified ActivityAction = "PAYMENT_VERIFIED"
|
ActionPaymentVerified ActivityAction = "PAYMENT_VERIFIED"
|
||||||
|
|
|
||||||
88
internal/domain/subscription_checkout_link.go
Normal file
88
internal/domain/subscription_checkout_link.go
Normal file
|
|
@ -0,0 +1,88 @@
|
||||||
|
package domain
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net/mail"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
var ErrNoContactForCheckoutLink = errors.New("no email or phone number on file to send checkout link")
|
||||||
|
|
||||||
|
type CheckoutLinkDeliveryChannel string
|
||||||
|
|
||||||
|
const (
|
||||||
|
CheckoutLinkDeliveryEmail CheckoutLinkDeliveryChannel = "email"
|
||||||
|
CheckoutLinkDeliverySMS CheckoutLinkDeliveryChannel = "sms"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ResolveCheckoutLinkDeliveryChannel picks email vs SMS from the learner's registration contact.
|
||||||
|
// Verified phone/email is preferred; otherwise falls back to the single contact on file.
|
||||||
|
func ResolveCheckoutLinkDeliveryChannel(user User) (CheckoutLinkDeliveryChannel, string, error) {
|
||||||
|
phone := strings.TrimSpace(user.PhoneNumber)
|
||||||
|
email := strings.TrimSpace(user.Email)
|
||||||
|
|
||||||
|
if user.PhoneVerified && phone != "" {
|
||||||
|
return CheckoutLinkDeliverySMS, phone, nil
|
||||||
|
}
|
||||||
|
if user.EmailVerified && email != "" {
|
||||||
|
return CheckoutLinkDeliveryEmail, email, nil
|
||||||
|
}
|
||||||
|
if phone != "" && email == "" {
|
||||||
|
return CheckoutLinkDeliverySMS, phone, nil
|
||||||
|
}
|
||||||
|
if email != "" && phone == "" {
|
||||||
|
return CheckoutLinkDeliveryEmail, email, nil
|
||||||
|
}
|
||||||
|
if phone != "" {
|
||||||
|
return CheckoutLinkDeliverySMS, phone, nil
|
||||||
|
}
|
||||||
|
if email != "" {
|
||||||
|
if _, err := mail.ParseAddress(email); err != nil {
|
||||||
|
return "", "", fmt.Errorf("invalid email on file: %w", err)
|
||||||
|
}
|
||||||
|
return CheckoutLinkDeliveryEmail, email, nil
|
||||||
|
}
|
||||||
|
return "", "", ErrNoContactForCheckoutLink
|
||||||
|
}
|
||||||
|
|
||||||
|
// BuildWebCheckoutURL builds a deep link into the standalone web checkout app.
|
||||||
|
func BuildWebCheckoutURL(baseURL string, planID *int64, category *string) string {
|
||||||
|
base := strings.TrimRight(strings.TrimSpace(baseURL), "/")
|
||||||
|
if base == "" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
if planID != nil && *planID > 0 {
|
||||||
|
return fmt.Sprintf("%s/subscribe/checkout?plan_id=%d", base, *planID)
|
||||||
|
}
|
||||||
|
if category != nil {
|
||||||
|
cat := strings.TrimSpace(*category)
|
||||||
|
if cat != "" {
|
||||||
|
return fmt.Sprintf("%s/subscribe?category=%s", base, url.QueryEscape(strings.ToUpper(cat)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return base + "/subscribe"
|
||||||
|
}
|
||||||
|
|
||||||
|
// MaskCheckoutLinkDestination returns a safe hint for API responses (e.g. ***5678, j***@example.com).
|
||||||
|
func MaskCheckoutLinkDestination(channel CheckoutLinkDeliveryChannel, destination string) string {
|
||||||
|
dest := strings.TrimSpace(destination)
|
||||||
|
if dest == "" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
switch channel {
|
||||||
|
case CheckoutLinkDeliverySMS:
|
||||||
|
if len(dest) <= 4 {
|
||||||
|
return "***" + dest
|
||||||
|
}
|
||||||
|
return "***" + dest[len(dest)-4:]
|
||||||
|
default:
|
||||||
|
parts := strings.Split(dest, "@")
|
||||||
|
if len(parts) != 2 || parts[0] == "" {
|
||||||
|
return "***"
|
||||||
|
}
|
||||||
|
prefix := parts[0][:1]
|
||||||
|
return prefix + "***@" + parts[1]
|
||||||
|
}
|
||||||
|
}
|
||||||
67
internal/domain/subscription_checkout_link_test.go
Normal file
67
internal/domain/subscription_checkout_link_test.go
Normal file
|
|
@ -0,0 +1,67 @@
|
||||||
|
package domain
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestResolveCheckoutLinkDeliveryChannel(t *testing.T) {
|
||||||
|
t.Run("verified phone first", func(t *testing.T) {
|
||||||
|
ch, dest, err := ResolveCheckoutLinkDeliveryChannel(User{
|
||||||
|
PhoneNumber: "0912345678",
|
||||||
|
PhoneVerified: true,
|
||||||
|
Email: "a@b.com",
|
||||||
|
EmailVerified: true,
|
||||||
|
})
|
||||||
|
if err != nil || ch != CheckoutLinkDeliverySMS || dest != "0912345678" {
|
||||||
|
t.Fatalf("got %q %q err=%v", ch, dest, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("verified email when phone not verified", func(t *testing.T) {
|
||||||
|
ch, dest, err := ResolveCheckoutLinkDeliveryChannel(User{
|
||||||
|
Email: "learner@example.com",
|
||||||
|
EmailVerified: true,
|
||||||
|
})
|
||||||
|
if err != nil || ch != CheckoutLinkDeliveryEmail || dest != "learner@example.com" {
|
||||||
|
t.Fatalf("got %q %q err=%v", ch, dest, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("phone only on file", func(t *testing.T) {
|
||||||
|
ch, dest, err := ResolveCheckoutLinkDeliveryChannel(User{PhoneNumber: "0911111111"})
|
||||||
|
if err != nil || ch != CheckoutLinkDeliverySMS {
|
||||||
|
t.Fatalf("got %q err=%v", ch, err)
|
||||||
|
}
|
||||||
|
if dest != "0911111111" {
|
||||||
|
t.Fatal(dest)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("no contact", func(t *testing.T) {
|
||||||
|
_, _, err := ResolveCheckoutLinkDeliveryChannel(User{})
|
||||||
|
if err != ErrNoContactForCheckoutLink {
|
||||||
|
t.Fatalf("expected ErrNoContactForCheckoutLink, got %v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildWebCheckoutURL(t *testing.T) {
|
||||||
|
planID := int64(5)
|
||||||
|
cat := "IELTS"
|
||||||
|
if u := BuildWebCheckoutURL("https://subscribe.example.com", &planID, nil); u != "https://subscribe.example.com/subscribe/checkout?plan_id=5" {
|
||||||
|
t.Fatal(u)
|
||||||
|
}
|
||||||
|
if u := BuildWebCheckoutURL("https://subscribe.example.com/", nil, &cat); u != "https://subscribe.example.com/subscribe?category=IELTS" {
|
||||||
|
t.Fatal(u)
|
||||||
|
}
|
||||||
|
if u := BuildWebCheckoutURL("https://subscribe.example.com", nil, nil); u != "https://subscribe.example.com/subscribe" {
|
||||||
|
t.Fatal(u)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMaskCheckoutLinkDestination(t *testing.T) {
|
||||||
|
if got := MaskCheckoutLinkDestination(CheckoutLinkDeliverySMS, "0912345678"); got != "***5678" {
|
||||||
|
t.Fatal(got)
|
||||||
|
}
|
||||||
|
if got := MaskCheckoutLinkDestination(CheckoutLinkDeliveryEmail, "john@example.com"); got != "j***@example.com" {
|
||||||
|
t.Fatal(got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -162,6 +162,7 @@ var AllPermissions = []domain.PermissionSeed{
|
||||||
// Subscriptions
|
// Subscriptions
|
||||||
{Key: "subscriptions.create", Name: "Create Subscription", Description: "Create subscription (admin)", GroupName: "Subscriptions"},
|
{Key: "subscriptions.create", Name: "Create Subscription", Description: "Create subscription (admin)", GroupName: "Subscriptions"},
|
||||||
{Key: "subscriptions.checkout", Name: "Checkout Subscription", Description: "Initiate subscription payment", GroupName: "Subscriptions"},
|
{Key: "subscriptions.checkout", Name: "Checkout Subscription", Description: "Initiate subscription payment", GroupName: "Subscriptions"},
|
||||||
|
{Key: "subscriptions.request_checkout_link", Name: "Request Checkout Link", Description: "Send web checkout link by email or SMS", GroupName: "Subscriptions"},
|
||||||
{Key: "subscriptions.get_mine", Name: "Get My Subscription", Description: "Get own subscription", GroupName: "Subscriptions"},
|
{Key: "subscriptions.get_mine", Name: "Get My Subscription", Description: "Get own subscription", GroupName: "Subscriptions"},
|
||||||
{Key: "subscriptions.get_by_user", Name: "Get User Subscriptions (Admin)", Description: "Get full subscription details for a user", GroupName: "Subscriptions"},
|
{Key: "subscriptions.get_by_user", Name: "Get User Subscriptions (Admin)", Description: "Get full subscription details for a user", GroupName: "Subscriptions"},
|
||||||
{Key: "subscriptions.export", Name: "Export Subscriptions", Description: "Export user subscriptions as CSV (admin)", GroupName: "Subscriptions"},
|
{Key: "subscriptions.export", Name: "Export Subscriptions", Description: "Export user subscriptions as CSV (admin)", GroupName: "Subscriptions"},
|
||||||
|
|
@ -379,7 +380,7 @@ var defaultStudentLearnerPermissions = []string{
|
||||||
"question_set_personas.list",
|
"question_set_personas.list",
|
||||||
|
|
||||||
// Subscriptions & Payments (own)
|
// Subscriptions & Payments (own)
|
||||||
"subscriptions.checkout", "subscriptions.get_mine", "subscriptions.history",
|
"subscriptions.checkout", "subscriptions.request_checkout_link", "subscriptions.get_mine", "subscriptions.history",
|
||||||
"subscriptions.status", "subscriptions.cancel", "subscriptions.set_auto_renew",
|
"subscriptions.status", "subscriptions.cancel", "subscriptions.set_auto_renew",
|
||||||
"payments.initiate", "payments.verify", "payments.list_mine", "payments.get", "payments.cancel",
|
"payments.initiate", "payments.verify", "payments.list_mine", "payments.get", "payments.cancel",
|
||||||
"payments.direct_initiate", "payments.direct_verify_otp",
|
"payments.direct_initiate", "payments.direct_verify_otp",
|
||||||
|
|
@ -457,7 +458,7 @@ var DefaultRolePermissions = map[string][]string{
|
||||||
|
|
||||||
// Subscriptions & Payments (full access)
|
// Subscriptions & Payments (full access)
|
||||||
"subscription_plans.create", "subscription_plans.update", "subscription_plans.delete",
|
"subscription_plans.create", "subscription_plans.update", "subscription_plans.delete",
|
||||||
"subscriptions.create", "subscriptions.checkout", "subscriptions.get_mine", "subscriptions.get_by_user", "subscriptions.export", "subscriptions.history",
|
"subscriptions.create", "subscriptions.checkout", "subscriptions.request_checkout_link", "subscriptions.get_mine", "subscriptions.get_by_user", "subscriptions.export", "subscriptions.history",
|
||||||
"subscriptions.status", "subscriptions.cancel", "subscriptions.admin_cancel", "subscriptions.admin_extend", "subscriptions.set_auto_renew",
|
"subscriptions.status", "subscriptions.cancel", "subscriptions.admin_cancel", "subscriptions.admin_extend", "subscriptions.set_auto_renew",
|
||||||
"payments.initiate", "payments.verify", "payments.list_mine", "payments.get", "payments.cancel",
|
"payments.initiate", "payments.verify", "payments.list_mine", "payments.get", "payments.cancel",
|
||||||
"payments.direct_initiate", "payments.direct_verify_otp", "payments.list_all", "payments.export",
|
"payments.direct_initiate", "payments.direct_verify_otp", "payments.list_all", "payments.export",
|
||||||
|
|
@ -568,7 +569,7 @@ var DefaultRolePermissions = map[string][]string{
|
||||||
"faqs.create", "faqs.list", "faqs.get", "faqs.update", "faqs.delete",
|
"faqs.create", "faqs.list", "faqs.get", "faqs.update", "faqs.delete",
|
||||||
|
|
||||||
// Subscriptions & Payments (own)
|
// Subscriptions & Payments (own)
|
||||||
"subscriptions.checkout", "subscriptions.get_mine", "subscriptions.history",
|
"subscriptions.checkout", "subscriptions.request_checkout_link", "subscriptions.get_mine", "subscriptions.history",
|
||||||
"subscriptions.status", "subscriptions.cancel", "subscriptions.set_auto_renew",
|
"subscriptions.status", "subscriptions.cancel", "subscriptions.set_auto_renew",
|
||||||
"payments.initiate", "payments.verify", "payments.list_mine", "payments.get", "payments.cancel",
|
"payments.initiate", "payments.verify", "payments.list_mine", "payments.get", "payments.cancel",
|
||||||
"payments.direct_initiate", "payments.direct_verify_otp",
|
"payments.direct_initiate", "payments.direct_verify_otp",
|
||||||
|
|
|
||||||
222
internal/web_server/handlers/subscription_checkout_link.go
Normal file
222
internal/web_server/handlers/subscription_checkout_link.go
Normal file
|
|
@ -0,0 +1,222 @@
|
||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"Yimaru-Backend/internal/domain"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v2"
|
||||||
|
)
|
||||||
|
|
||||||
|
const checkoutLinkRateLimitWindow = 15 * time.Minute
|
||||||
|
|
||||||
|
type requestCheckoutLinkReq struct {
|
||||||
|
PlanID *int64 `json:"plan_id"`
|
||||||
|
Category *string `json:"category"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type requestCheckoutLinkRes struct {
|
||||||
|
Channel string `json:"channel"`
|
||||||
|
DestinationHint string `json:"destination_hint"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// RequestSubscriptionCheckoutLink godoc
|
||||||
|
// @Summary Send web checkout link to learner
|
||||||
|
// @Description Sends the standalone web checkout URL to the learner by email or SMS (registration channel). Intended when mobile clients show a subscription-required state.
|
||||||
|
// @Tags subscriptions
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Param body body requestCheckoutLinkReq false "Optional plan or category for deep link"
|
||||||
|
// @Success 200 {object} domain.Response
|
||||||
|
// @Failure 400 {object} domain.ErrorResponse
|
||||||
|
// @Failure 409 {object} domain.ErrorResponse
|
||||||
|
// @Failure 429 {object} domain.ErrorResponse
|
||||||
|
// @Failure 503 {object} domain.ErrorResponse
|
||||||
|
// @Router /api/v1/subscriptions/request-checkout-link [post]
|
||||||
|
func (h *Handler) RequestSubscriptionCheckoutLink(c *fiber.Ctx) error {
|
||||||
|
userID, ok := c.Locals("user_id").(int64)
|
||||||
|
if !ok {
|
||||||
|
return c.Status(fiber.StatusUnauthorized).JSON(domain.ErrorResponse{
|
||||||
|
Message: "Unauthorized",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
checkoutBase := strings.TrimSpace(h.Cfg.LearnerWebCheckoutBaseURL)
|
||||||
|
if checkoutBase == "" {
|
||||||
|
return c.Status(fiber.StatusServiceUnavailable).JSON(domain.ErrorResponse{
|
||||||
|
Message: "Web checkout is not configured",
|
||||||
|
Error: "LEARNER_WEB_CHECKOUT_BASE_URL is not set",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := h.enforceCheckoutLinkRateLimit(c, userID); err != nil {
|
||||||
|
return c.Status(fiber.StatusTooManyRequests).JSON(domain.ErrorResponse{
|
||||||
|
Message: "Checkout link was sent recently. Please check your messages or try again later.",
|
||||||
|
Error: err.Error(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
var req requestCheckoutLinkReq
|
||||||
|
if len(c.Body()) > 0 {
|
||||||
|
if err := c.BodyParser(&req); err != nil {
|
||||||
|
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||||||
|
Message: "Invalid request body",
|
||||||
|
Error: err.Error(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var planCategory string
|
||||||
|
if req.PlanID != nil && *req.PlanID > 0 {
|
||||||
|
plan, err := h.subscriptionsSvc.GetPlanByID(c.Context(), *req.PlanID)
|
||||||
|
if err != nil {
|
||||||
|
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||||||
|
Message: "Invalid subscription plan",
|
||||||
|
Error: err.Error(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if !plan.IsActive {
|
||||||
|
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||||||
|
Message: "Subscription plan is not available",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
planCategory = plan.Category
|
||||||
|
} else if req.Category != nil {
|
||||||
|
cat := strings.ToUpper(strings.TrimSpace(*req.Category))
|
||||||
|
if cat != "" && !domain.IsValidSubscriptionCategory(cat) {
|
||||||
|
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||||||
|
Message: "Invalid category",
|
||||||
|
Error: "category must be one of: LEARN_ENGLISH, IELTS, DUOLINGO",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
planCategory = cat
|
||||||
|
}
|
||||||
|
|
||||||
|
if planCategory != "" {
|
||||||
|
active, err := h.subscriptionsSvc.HasActiveSubscriptionByCategory(
|
||||||
|
c.Context(),
|
||||||
|
userID,
|
||||||
|
domain.SubscriptionCategory(planCategory),
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
||||||
|
Message: "Failed to check subscription status",
|
||||||
|
Error: err.Error(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if active {
|
||||||
|
return c.Status(fiber.StatusConflict).JSON(domain.ErrorResponse{
|
||||||
|
Message: "You already have an active subscription for this content",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
user, err := h.userSvc.GetUserByID(c.Context(), userID)
|
||||||
|
if err != nil {
|
||||||
|
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
||||||
|
Message: "Failed to load user profile",
|
||||||
|
Error: err.Error(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
channel, destination, err := domain.ResolveCheckoutLinkDeliveryChannel(user)
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, domain.ErrNoContactForCheckoutLink) {
|
||||||
|
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||||||
|
Message: "No email or phone number on your account to send a checkout link",
|
||||||
|
Error: err.Error(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{
|
||||||
|
Message: "Cannot send checkout link",
|
||||||
|
Error: err.Error(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
checkoutURL := domain.BuildWebCheckoutURL(checkoutBase, req.PlanID, req.Category)
|
||||||
|
if checkoutURL == "" {
|
||||||
|
return c.Status(fiber.StatusServiceUnavailable).JSON(domain.ErrorResponse{
|
||||||
|
Message: "Web checkout is not configured",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := h.deliverCheckoutLink(c, channel, destination, checkoutURL); err != nil {
|
||||||
|
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
||||||
|
Message: "Failed to send checkout link",
|
||||||
|
Error: err.Error(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
meta, _ := json.Marshal(map[string]string{
|
||||||
|
"channel": string(channel),
|
||||||
|
"checkout_url": checkoutURL,
|
||||||
|
})
|
||||||
|
h.recordActivity(c, domain.ActionSubscriptionCheckoutLinkSent, domain.ResourceSubscription, req.PlanID, "Sent web checkout link to learner", meta)
|
||||||
|
|
||||||
|
return c.JSON(domain.Response{
|
||||||
|
Message: checkoutLinkSentMessage(channel),
|
||||||
|
Data: requestCheckoutLinkRes{
|
||||||
|
Channel: string(channel),
|
||||||
|
DestinationHint: domain.MaskCheckoutLinkDestination(channel, destination),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkoutLinkSentMessage(channel domain.CheckoutLinkDeliveryChannel) string {
|
||||||
|
switch channel {
|
||||||
|
case domain.CheckoutLinkDeliveryEmail:
|
||||||
|
return "Please check your email for the address"
|
||||||
|
case domain.CheckoutLinkDeliverySMS:
|
||||||
|
return "Please check your SMS for the address"
|
||||||
|
default:
|
||||||
|
return "Please check your email/SMS for the address"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) enforceCheckoutLinkRateLimit(c *fiber.Ctx, userID int64) error {
|
||||||
|
since := time.Now().Add(-checkoutLinkRateLimitWindow)
|
||||||
|
action := string(domain.ActionSubscriptionCheckoutLinkSent)
|
||||||
|
filter := domain.ActivityLogFilter{
|
||||||
|
ActorID: &userID,
|
||||||
|
Action: &action,
|
||||||
|
After: &since,
|
||||||
|
Limit: 1,
|
||||||
|
Offset: 0,
|
||||||
|
}
|
||||||
|
logs, _, err := h.activityLogSvc.List(c.Context(), filter)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if len(logs) > 0 {
|
||||||
|
return fmt.Errorf("rate limit: one checkout link per %s", checkoutLinkRateLimitWindow)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) deliverCheckoutLink(c *fiber.Ctx, channel domain.CheckoutLinkDeliveryChannel, destination, checkoutURL string) error {
|
||||||
|
subject := "Complete your Yimaru Academy subscription"
|
||||||
|
text := fmt.Sprintf(
|
||||||
|
"Complete your Yimaru Academy subscription here:\n\n%s\n\nAfter payment, open the mobile app and sign in with this account.",
|
||||||
|
checkoutURL,
|
||||||
|
)
|
||||||
|
html := fmt.Sprintf(
|
||||||
|
`<p>Complete your <strong>Yimaru Academy</strong> subscription using the link below:</p><p><a href="%s">Subscribe now</a></p><p>After payment, open the mobile app and sign in with this account.</p>`,
|
||||||
|
checkoutURL,
|
||||||
|
)
|
||||||
|
sms := fmt.Sprintf("Complete your Yimaru Academy subscription: %s", checkoutURL)
|
||||||
|
|
||||||
|
ctx := c.Context()
|
||||||
|
messenger := h.notificationSvc.MessengerSvc()
|
||||||
|
switch channel {
|
||||||
|
case domain.CheckoutLinkDeliveryEmail:
|
||||||
|
return messenger.SendEmail(ctx, destination, text, html, subject)
|
||||||
|
case domain.CheckoutLinkDeliverySMS:
|
||||||
|
return messenger.SendSMS(ctx, destination, sms)
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("unsupported delivery channel %q", channel)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -295,6 +295,7 @@ func (a *App) initAppRoutes() {
|
||||||
// User Subscriptions
|
// User Subscriptions
|
||||||
groupV1.Post("/subscriptions", a.authMiddleware, a.RequirePermission("subscriptions.create"), h.Subscribe)
|
groupV1.Post("/subscriptions", a.authMiddleware, a.RequirePermission("subscriptions.create"), h.Subscribe)
|
||||||
groupV1.Post("/subscriptions/checkout", a.authMiddleware, a.RequirePermission("subscriptions.checkout"), h.SubscribeWithPayment)
|
groupV1.Post("/subscriptions/checkout", a.authMiddleware, a.RequirePermission("subscriptions.checkout"), h.SubscribeWithPayment)
|
||||||
|
groupV1.Post("/subscriptions/request-checkout-link", a.authMiddleware, a.RequirePermission("subscriptions.request_checkout_link"), h.RequestSubscriptionCheckoutLink)
|
||||||
groupV1.Get("/subscriptions/me", a.authMiddleware, a.RequirePermission("subscriptions.get_mine"), h.GetMySubscription)
|
groupV1.Get("/subscriptions/me", a.authMiddleware, a.RequirePermission("subscriptions.get_mine"), h.GetMySubscription)
|
||||||
groupV1.Get("/subscriptions/history", a.authMiddleware, a.RequirePermission("subscriptions.history"), h.GetMySubscriptionHistory)
|
groupV1.Get("/subscriptions/history", a.authMiddleware, a.RequirePermission("subscriptions.history"), h.GetMySubscriptionHistory)
|
||||||
groupV1.Get("/subscriptions/status", a.authMiddleware, a.RequirePermission("subscriptions.status"), h.CheckSubscriptionStatus)
|
groupV1.Get("/subscriptions/status", a.authMiddleware, a.RequirePermission("subscriptions.status"), h.CheckSubscriptionStatus)
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue
Block a user