# Online payments — runbook for support and operations

How HostelCare collects money through Razorpay, and what to do when
something looks wrong. Written for the support team; the code lives under
`src/modules/payments/`.

## How money moves

1. A student presses **Pay**, or the office sends a link, or a reminder
   carries one. HostelCare writes a `PaymentRequest` row, then asks Razorpay
   for a **Payment Link** for exactly the balance (plus the gateway charge
   when the student bears it). The link expires after `PAYMENT_LINK_TTL_MINUTES`.
2. The student pays on Razorpay's hosted page. Razorpay sends a **webhook** to
   `POST /api/webhooks/razorpay`. That webhook is the only thing that records
   a payment: it is signed, claimed once by event id, processed under a row
   lock, and the amount must equal the link's. The invoice moves to Partial
   or Completed and the student is emailed the receipt.
3. **Route** moves the base amount to the hostel's linked account. The
   platform keeps the fee portion to pay Razorpay. Settlement to the hostel's
   bank is Razorpay's standard T+2 working days.
4. Every 10 minutes a **reconciliation job** asks Razorpay about links that
   are still pending (older than 5 minutes) or expired in the last 48 hours,
   and books any paid link whose webhook never arrived. Every night it
   compares the day's gateway payments with the books and lists mismatches
   on the Online collections dashboard.
5. **Virtual accounts** (Smart Collect): a student can be given an account
   number and UPI id of their own. A transfer to it arrives as a
   `virtual_account.credited` webhook and is applied to their oldest open
   invoice with the UTR as reference; any excess becomes a settled "advance"
   invoice the office adjusts later.

## Going live — checklist

- Razorpay: KYC-approved **live** account with Route and Smart Collect
  enabled. Env on the server: `RAZORPAY_KEY_ID`, `RAZORPAY_KEY_SECRET`,
  `RAZORPAY_WEBHOOK_SECRET`, `PUBLIC_WEB_URL=https://<web app>`.
- Razorpay dashboard → Webhooks: URL `https://<api>/api/webhooks/razorpay`,
  secret = `RAZORPAY_WEBHOOK_SECRET`, events: `payment_link.paid`,
  `payment.captured`, `order.paid`, `payment.failed`, `payment_link.expired`,
  `payment_link.cancelled`, `refund.created`, `refund.processed`,
  `refund.failed`, `virtual_account.credited`, `account.*`, `product.route.*`.
- Confirm the linked-account category values (`RAZORPAY_BUSINESS_CATEGORY`,
  `RAZORPAY_BUSINESS_SUBCATEGORY`) against Razorpay's list in test mode.
- Email (Mailgun SMTP): `EMAIL_PROVIDER=smtp`, `SMTP_HOST=smtp.mailgun.org`
  (`smtp.eu.mailgun.org` for an EU domain), `SMTP_PORT=587`,
  `SMTP_SECURE=false`, `SMTP_USER`/`SMTP_PASS` from Mailgun → Sending →
  Domain settings → SMTP credentials, `EMAIL_FROM` on that verified domain,
  optionally `EMAIL_REPLY_TO`. The server logs `email ready` at boot once the
  login works; `npm run check:email -- you@domain` sends one real test mail.
  Settings → Reminders & emails then shows **Sent**, not **Dry run**. Every
  mail the product sends — sign-in codes, receipts, invoices, reminders,
  notices, settlements, guardian invites, late returns, enquiries — uses this
  one relay.
- WhatsApp: `WHATSAPP_PROVIDER=meta`, `WHATSAPP_API_TOKEN`,
  `WHATSAPP_PHONE_NUMBER_ID`, and the approved template names in
  `WHATSAPP_TEMPLATE_REMINDER` / `WHATSAPP_TEMPLATE_PAYMENT_LINK` (texts below).
- Per hostel, in Settings → Online payments: connect the bank account, wait
  for **Active**, choose the fee bearer, switch collection on. Optionally
  switch on bank-transfer accounts.
- Collect a real ₹1 by link and by virtual-account transfer; check both on
  the Online collections dashboard and on the student's history.

## WhatsApp utility templates (submit to Meta, category *Utility*)

**hostelcare_fee_reminder** — body:
```
Hi {{1}}, your hostel fee of {{2}} ({{3}}) is due {{4}}. Pay securely here: {{5}}
If you have already paid, please ignore this message.
```
Parameters: name, amount, invoice/period, when, pay link (or "the HostelCare app").

**hostelcare_payment_link** — body:
```
Hi {{1}}, you can pay {{2}} for {{3}} by UPI, card or net banking here: {{4}}
The link is valid for a short time; open HostelCare for a fresh one if it has expired.
```
Parameters: name, amount, invoice/period, pay link.

Payment received / failed go by email with the receipt attached; WhatsApp
copies can be added as a third template once the two above are approved.

## Something looks wrong

### "I paid but it still shows pending"
1. Open Rent & Invoices → Online collections → **Run now**. This asks
   Razorpay about every open link and books anything paid. Nine times out of
   ten this is a missed webhook and it resolves here.
2. If not: find the payment in the Razorpay dashboard. If its notes carry a
   `paymentRequestId`, the nightly compare will list it under *Reconciliation*
   with a note explaining the state. A payment with no HostelCare notes was
   not made through a HostelCare link — record it by hand with
   **Record payment** and the Razorpay id as the reference.
3. Never record an online payment by hand if the link is still open; cancel
   the link first (Pay link → Cancel) so a late webhook cannot book it twice.
   The webhook refuses a second booking of the same gateway payment anyway.

### "I was charged twice"
Two Razorpay payments can exist only if the student paid two different
links. HostelCare books each gateway payment once (unique gateway id), and a
link always asks for the current balance, so the second one would have
settled a different invoice or landed as an *advance*. Check the student's
history; refund the duplicate from the Payments dialog → **Refund**.

### Refunds
Payments → **Refund** asks Razorpay (and reverses the Route transfer). The
row shows *refund requested* until Razorpay's `refund.processed` webhook
arrives; then the payment is marked failed with the reason, the invoice
reopens, and the student is emailed. A `refund.failed` leaves the payment
cleared and marks the attempt failed: the money stayed with the hostel, try
again or settle it offline. Refunds reach the student in 5–7 working days.

### A webhook outage
Nothing is lost. Razorpay retries non-2xx responses for 24 hours, and the
reconciliation job books anything paid within 10 minutes of the API being
back (links) or by the next night (everything else). Check the server log
for `[reconcile]` lines.

### Rotating keys or the webhook secret
1. Create the new key pair in Razorpay. Set the new `RAZORPAY_KEY_ID` /
   `RAZORPAY_KEY_SECRET` and restart the API. Links already issued keep
   working — they are Razorpay's, not the key's.
2. For the webhook secret: add a second webhook endpoint in Razorpay with
   the new secret pointing at the same URL, set `RAZORPAY_WEBHOOK_SECRET` to
   the new value, restart, then delete the old endpoint. Any event that
   arrived signed with the old secret during the switch is answered 400 and
   retried by Razorpay; the reconciliation job covers the rest.

### Capacity
`npm run load:webhook` fires 50 signed events a second for 10 seconds at a
throwaway instance and checks every event is answered and every link is
booked exactly once. Run it after any change to the webhook path.

## Things the office can switch off
Settings → Online payments. Switching collection off stops new links and
the Pay button at once; open links still accept a payment until they
expire, and the webhook still books it. Virtual accounts can be closed per
student from the student's page.
