# NEXUS — Stripe payment integration (frontend guide)

Yeh document backend ke **payment / subscription** flow ko explain karta hai taake frontend team ko pata ho ke **kaun si API**, **kya body/headers**, aur **Stripe par kaun sa key / process** use karna hai.

---

## Short summary (Urdu)

- **Secret key** sirf backend par rehti hai — frontend ko **kabhi bhi** Stripe Secret Key nahi chahiye.
- Frontend ko sirf **Publishable key** chahiye (`VITE_STRIPE_PUBLISH_KEY`) taake **card Stripe Elements** se collect ho aur **`paymentMethod.id`** ban sake.
- Pehle user **`POST /users/register-user`** se register hota hai; response mein **`user` (id)**, **`customer_id`** (Stripe Customer) milta hai.
- Phir Stripe se **`createPaymentMethod`** karke **`POST /users/register-route`** par **`user_id`**, **`customerId`**, **`paymentMethodId`** bhejna hota hai — isi ke andar backend subscription banata hai (`paymentFunction`).
- Logged-in Super admin ke liye billing info **`/payments/*`** GET routes se aati hai (JWT required).

---

## 1. Environment variables (frontend)

| Variable | Kahan use | Kaun dega |
|----------|-----------|-----------|
| `VITE_STRIPE_PUBLISH_KEY` | `@stripe/stripe-js` / `loadStripe(...)` — Elements wrap | Stripe Dashboard → Developers → API keys → **Publishable key** |

Backend alag se `STRIPE_SECRET_KEY` use karta hai — **yeh env frontend mein add mat karo.**

---

## 2. Stripe — frontend par process (high level)

1. **`<Elements provider={stripePromise}>`** — app mein publishable key se `loadStripe` (already `App.jsx` pattern).
2. **Card elements** — `CardNumberElement`, `CardExpiryElement`, `CardCvcElement` (ya `PaymentElement` agar migrate karo).
3. Submit par:
   ```js
   const { error, paymentMethod } = await stripe.createPaymentMethod({
     type: "card",
     card: cardNumberElement, // ya relevant element
   });
   ```
4. Agar `error` na ho to `paymentMethod.id` backend ko bhejo — **card number / CVC kabhi apne server par mat bhejo**, sirf yeh `pm_...` id.

Backend is `paymentMethodId` ko Stripe customer par attach karta hai, default payment method set karta hai, phir **`stripe.subscriptions.create`** chalata hai (secret key se).

---

## 3. Base URL

Sab routes API root ke neeche hain, jaise:

- `{API_BASE}/users/...`
- `{API_BASE}/subscription-plans/...`
- `{API_BASE}/payments/...`

`{API_BASE}` wohi hai jo app mein `BASE_URL` hai (e.g. `https://api.example.com/api`).

---

## 4. Registration + first payment flow (public — token optional)

### Step A — User create + Stripe Customer

**`POST /users/register-user`**

| Body field | Type | Required | Note |
|------------|------|----------|------|
| `name` | string | ✓ | |
| `email` | string | ✓ | |
| `company_name` | string | ✓ | |
| `company_address` | string | ✓ | |
| `contact_no` | string/number | ✓ | |
| `password` | string | ✓ | |
| `isPlan` | boolean | ✓ Registration with plan | e.g. `true` |
| `plan` | MongoDB ObjectId | ✓ | Selected plan `_id` |
| `industry` | string[] | Optional | Industry names array |

**Successful response (relevant fields):**

```json
{
  "success": true,
  "message": "User registered successfully",
  "user": "<user_id>",
  "customer_id": "cus_xxxxxxxx",
  "email": "user@example.com"
}
```

Frontend ko **`user`**, **`customer_id`** save karna hai — agle step ke liye.

### Step B — Card + subscription charge + OTP email

**`POST /users/register-route`**

| Body field | Type | Required | Note |
|------------|------|----------|------|
| `user_id` | string | ✓ | Step A se `user` |
| `customerId` | string | ✓ | Step A se `customer_id` (`cus_...`) |
| `paymentMethodId` | string | ✓ | Stripe `createPaymentMethod` se `pm_...` |

**Success (example):**

```json
{
  "success": true,
  "message": "Subscription created successfully.",
  "email": "user@example.com",
  "expanded_message": "Please check your email for OTP"
}
```

**Failure:** HTTP 400/`success: false` — `message` mein Stripe ya validation error text ho sakta hai.

**Backend behavior (for context):**

- Payment method customer par attach + default set.
- User document par plan dates / `price_id` (plan se) set.
- **`paymentFunction`** Stripe subscription create karti hai; agar invoice ka `payment_intent` immediately `succeeded` na ho to failure return.

---

## 5. Logged-in Super admin — payments / billing APIs

In sab par **`Authorization: Bearer <JWT>`** chahiye. Role: **`Super admin`** (middleware `authorizeUserType`).

### Current plan (Stripe product)

**`GET /payments/customer-plan`**

- Body: none.
- User JWT se `subscription_id` resolve hota hai.
- Response: `success`, `plan_id` (product metadata), `product`, etc.

### Invoices list (Stripe)

**`GET /payments/customer-invoice-list`**

- Returns Stripe `invoices.list` style payload for logged-in user’s `customer_id`.

### Customer portal / invoices (alternate)

**`GET /payments/customer-portal`**

- Abhi implementation Stripe **Customer Billing Portal session** ki jagah **invoices list** return karti hai — frontend isi ko “portal data” jaisa treat kare agar API aise hi use ho rahi ho.

---

## 6. Plan cancel / upgrade (authenticated Super admin)

Base: **`/subscription-plans`**

### Cancel subscription

**`PATCH /subscription-plans/cancel/plan`**

- Body: (empty ya minimal — user server se `req.user` se aata hai).
- Backend: Stripe subscription cancel + user fields update.

### Upgrade plan

**`PATCH /subscription-plans/upgrade/plan`**

| Body field | Type | Required |
|------------|------|----------|
| `plan` | MongoDB ObjectId | ✓ Naya plan `_id` |

**Important (integration note):** `paymentFunction` user ke saved **`price_id`** se Stripe subscription banati hai. Upgrade flow mein ensure karein ke **user document par naye plan ka `price_id`** pehle set ho — warna charge purane price par ho sakta hai. Agar yeh mismatch dikhe to backend team se align karna hoga.

---

## 7. Webhooks (informational)

Backend mein **`Webhook.js`** Stripe events handle karta hai (e.g. `invoice.payment_succeeded`, `invoice.payment_failed`). Frontend ko webhook URL call nahi karna — yeh Stripe server-to-server backend par aata hai.

---

## 8. Quick checklist (frontend)

- [ ] `.env` mein `VITE_STRIPE_PUBLISH_KEY` set
- [ ] App root par `Elements` + `loadStripe`
- [ ] Register: `register-user` → phir `createPaymentMethod` → `register-route`
- [ ] Kabhi raw card data backend ko na bhejein — sirf `paymentMethodId`
- [ ] Super admin screens: `GET /payments/*` ke saath valid JWT

---

## 9. Related backend files

| Piece | File |
|--------|------|
| Subscription create / cancel helpers | `backend/controllers/Payment.js` |
| Register + card attach + `paymentFunction` call | `backend/controllers/Users.js` (`registerUser`, `cardNoRoute`) |
| Plan upgrade/cancel routes | `backend/routes/SubscriptionPlan.js` |
| Payment read-only routes | `backend/routes/Payment.js` |

---

*Last updated for NEXUS codebase structure (subscription + Stripe Customer + PaymentMethod flow).*
