# CRECER × Razorpay — Payment Integration

Complete, production-level Razorpay integration for the CRECER clothing storefront.

---

## Architecture

```
Browser (Frontend)
│
│  1. User clicks "Pay Now"
│  2. JS calls our backend — NOT Razorpay directly
│
▼
Backend (Express / Node.js)          Razorpay Servers
│                                    │
│── POST /create-order ─────────────▶│  Creates order
│◀─ returns { order_id, amount } ────│
│
│  3. Frontend receives order_id
│  4. Razorpay checkout.js opens modal
│
▼ (user completes payment in modal)
│
│  5. Razorpay calls handler() with:
│     razorpay_order_id
│     razorpay_payment_id
│     razorpay_signature
│
│── POST /verify-payment ──────────▶ Backend
│   (HMAC-SHA256 signature check)
│◀─ { success: true } ────────────── Backend
│
│  6. Only NOW show success to user
│  7. Fulfil order (DB update, email, etc.)
```

### Why this order matters

| Risk | How we prevent it |
|------|-------------------|
| Price tampering | Order is created server-side with the real amount |
| Fake payment signals | Signature is re-derived with the secret key on the server |
| Timing attacks | `crypto.timingSafeEqual` used for comparison |
| Key leakage | `KEY_SECRET` lives only in `.env`, never in frontend code |

---

## Current File Structure

```
.
├── index.html
├── shop.html
├── product.html
├── cart.html
├── checkout.html
├── style.css
├── app.js
├── payment.js
├── server.js
├── package.json
├── .env.example
├── .gitignore
└── DEPLOYMENT_REPORT.md
```

---

## Quick Start

### 1. Get Razorpay keys

1. Sign up at [dashboard.razorpay.com](https://dashboard.razorpay.com)
2. Go to **Settings → API Keys → Generate Test Key**
3. Copy the **Key ID** and **Key Secret**

### 2. Configure the backend

```bash
cp .env.example .env
```

Open `.env` and fill in:

```env
RAZORPAY_KEY_ID=rzp_test_YOUR_KEY_ID
RAZORPAY_KEY_SECRET=your_secret_here
PORT=5000
FRONTEND_URL=http://localhost:5000
```

### 3. Install and run the backend

```bash
npm install
npm start
```

You should see:
```
🚀  CRECER payment server running on http://localhost:5000
   Razorpay key: rzp_test_XXXX...
   CORS origin:  http://localhost:5000
```

### 4. Open the storefront

The Express app serves the storefront and API together at `http://localhost:5000`.

### 5. Open checkout

Navigate to `http://localhost:5000/checkout.html`

Use Razorpay's test card details:
- **Card:** 4111 1111 1111 1111
- **Expiry:** Any future date
- **CVV:** Any 3 digits
- **OTP:** 1234 (for simulated 3DS)

---

## API Reference

### `POST /create-order`

**Request body:**
```json
{
  "amount": 49900,      // in paise (₹499 = 49900)
  "currency": "INR"     // optional, default INR
}
```

**Response:**
```json
{
  "success": true,
  "order_id": "order_XXXXXXXXXXXXXXXX",
  "amount": 49900,
  "currency": "INR",
  "key": "rzp_test_..."
}
```

---

### `POST /verify-payment`

**Request body:**
```json
{
  "razorpay_order_id": "order_XXX",
  "razorpay_payment_id": "pay_XXX",
  "razorpay_signature": "abc123..."
}
```

**Response (success):**
```json
{
  "success": true,
  "message": "Payment verified successfully.",
  "payment_id": "pay_XXX",
  "order_id": "order_XXX"
}
```

**Response (failure):**
```json
{
  "success": false,
  "message": "Payment verification failed. Invalid signature."
}
```

---

## Integrating into Existing CRECER Pages

The `payment.js` module is self-contained. To add payment to your existing cart page:

1. Add to any page that needs payment:

```html
<!-- In <head> or end of <body> -->
<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
<script src="payment.js"></script>
```

3. Call `initiatePayment()` from your Pay button:

```javascript
document.getElementById('payBtn').addEventListener('click', async () => {
  await initiatePayment(
    {
      amount: 49900,          // paise
      name: 'Customer Name',
      email: 'email@example.com',
      contact: '9876543210',
    },
    (result) => {
      // Payment verified ✅
      console.log('Order paid:', result.payment_id);
    },
    (err) => {
      // Payment failed/cancelled ❌
      console.warn('Payment issue:', err.message);
    }
  );
});
```

---

## Going Live

1. Replace test keys with **live keys** from Razorpay dashboard
2. Set `FRONTEND_URL` to your production domain in `.env`
3. Implement database writes in `server.js` inside `/verify-payment` success block
4. Add email confirmation (Nodemailer / SendGrid)
5. Move to HTTPS (required for live payments)
6. Set `rzp_live_` key in `.env` — the frontend receives it from the server, nothing else changes

---

## Security Checklist

- [x] Orders created server-side (amount not trusted from browser)
- [x] Signature verified with HMAC-SHA256 on every payment
- [x] `crypto.timingSafeEqual` prevents timing attacks
- [x] `KEY_SECRET` never sent to or stored on the frontend
- [x] CORS locked to frontend origin
- [x] Input validation on amount before order creation
- [x] Payment failures logged for support
- [ ] Add rate limiting (`express-rate-limit`) in production
- [ ] Add idempotency keys for retried order creation
- [ ] Store `order_id` → `payment_id` mapping in your database
