Welcome to Great Loan
Loans up to ₹2,50,000 with easy monthly EMI. Tap Apply for a Loan to get started.
Get a loan in minutes
Apply with just your NID card — amounts from ₹20,000 to ₹2,50,000, repaid over 6 to 36 months.
Welcome!
We are ready to help with your financial needs
Get a loan in minutes
Apply with just your NID card
Loans up to ₹2,50,000
Easy monthly EMI
Repay over 6 to 36 months
Profile
Your account, loan card, balance and all services.
All Services
Everything about your loan, in one place.
EMI Calculator
Choose an amount and tenure to see the monthly EMI, total interest and total payable.
| Loan Amount | 12 months / monthly | 24 months / monthly |
|---|
EMIs for 6, 18, 30 and 36 months are calculated at the same rate as the 12 / 24 month table above.
Apply for a Loan
Fill in the form with your ID card. Approval comes from the admin panel and the Telegram bot.
Your Plan Summary
Updates as you change the amount and tenure.
My Loans / Loan Status
Your applications, repayment schedule and statement — all in one page.
Repayment Schedule
Generated for disbursed loans.
Statement
All activity on your loans.
Inbox
Loan status updates, notifications and messages about your applications.
Welcome to Great Loan
Log in with your phone number to manage your loans.
Admin Panel
Users, loan applications, approvals, settings and the Telegram bot.
Admin Login
Sign in with an account that has the admin role on the server. Complete the “I am not a robot” check to continue.
Applications by Status
Live from the applications list.
Recent Applications
The latest five submissions.
Loan Applications
Verify the ID card and approve, cancel, disburse or close each application.
Registered Users
Accounts created from the register page, along with applicants.
| User | Phone | Applications | Joined | Actions |
|---|
Telegram Bot — Live Preview
This is exactly what the admin receives on Telegram for every new application. The Approve / Cancel buttons below work just like the bot's inline buttons.
Bot Settings
Create a bot with @BotFather, enter the token and the chat / group ID. The portal works normally even if Telegram is not configured.
How the approval flow works
Application submitted. The portal sends the applicant's full name, age, WhatsApp number, occupation, amount, tenure, purpose, detailed Reason / Details, ID card type and EMI to your Telegram chat.
Admin taps a button. The message has two inline buttons — Approve and Cancel.
The webhook updates the record. Telegram calls your webhook; the application status changes and the bot sends a confirmation message.
Site Settings
Everything on this site comes from these settings — nothing is fixed in the code. Edit any value, press Save Settings, and the change applies across the whole portal at once: header, home page, promo banner, EMI calculator, apply form, footer, inbox and admin. On the deployed site the same values are saved as one JSON row in the database settings table and served by GET /api/settings (see Backend & API).
Deploy on Cloudflare Pages
Project name great-loan — the site runs at great-loan.pages.dev. The portal is a static site, plus one Pages Function for the Telegram webhook.
Upload the site. Create a Pages project named great-loan and upload index.html together with manifest.webmanifest, sw.js, icon-192.png, icon-512.png and icon-maskable-512.png — all as separate files in the project root (or push them all to a Git repo). No build command is needed. The manifest, service worker and icons must be real files at the root: without them Chrome shows “This app cannot be installed”, and a service worker in a subfolder can never control the home page.
Add the webhook function. Create the file functions/api/telegram/webhook.js in the project with the code below.
Set the secrets. In Pages → Settings → Environment variables, add TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID. Connect the function to the database / KV where application statuses are stored.
Register the webhook. Open once in your browser: https://api.telegram.org/bot<TOKEN>/setWebhook?url=https://great-loan.pages.dev/api/telegram/webhook
// functions/api/telegram/webhook.js — Cloudflare Pages Function
// Secrets (Pages → Settings → Environment variables):
// TELEGRAM_BOT_TOKEN, TELEGRAM_CHAT_ID
// Replace updateApplicationStatus() with your DB / KV write.
async function tg(env, method, payload) {
return fetch(`https://api.telegram.org/bot${env.TELEGRAM_BOT_TOKEN}/${method}`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(payload)
});
}
// Call this from your application-submit endpoint:
export async function notifyNewApplication(env, app) {
const text =
`New Loan Application ${app.id}\n` +
`Name: ${app.name} (age ${app.age})\nPhone / WhatsApp: ${app.whatsapp}\n` +
`Occupation: ${app.occupation}\n` +
`Amount: ₹${app.amount} · Tenure: ${app.tenure} months\n` +
`Purpose: ${app.purpose} · EMI: ₹${app.emi}/month\n` +
`Reason / Details: ${app.loanReason || app.reasonDetails || ''}\n` +
`ID Card: ${app.idType} (front + back photos submitted)`;
await tg(env, 'sendMessage', {
chat_id: env.TELEGRAM_CHAT_ID,
text,
reply_markup: { inline_keyboard: [[
{ text: '✓ Approve', callback_data: `approve:${app.id}` },
{ text: '✕ Cancel', callback_data: `cancel:${app.id}` }
]]}
});
}
export async function onRequestPost({ request, env }) {
const update = await request.json();
const cb = update.callback_query;
if (!cb) return new Response('ok');
if (String(cb.message.chat.id) !== String(env.TELEGRAM_CHAT_ID))
return new Response('forbidden', { status: 403 });
const [action, appId] = cb.data.split(':');
const status = action === 'approve' ? 'Approved' : 'Cancelled';
await updateApplicationStatus(env, appId, status); // ← your DB/KV
await tg(env, 'answerCallbackQuery', {
callback_query_id: cb.id, text: `${appId} marked ${status}`
});
await tg(env, 'editMessageText', {
chat_id: cb.message.chat.id, message_id: cb.message.message_id,
text: cb.message.text + `\n\nStatus: ${status}`
});
return new Response('ok');
}
Backend Architecture — Cloudflare Pages
Deploy guide — the live backend is not active in this static preview. The portal's screens are built against the API contract below and post every action to these endpoints; until the Pages Functions are deployed, no server answers and the same flows run in the browser session instead. Once the functions below are deployed next to this page, the same screens run on the live backend: server-side authentication with httpOnly session cookies, user / admin roles, and a D1 database for users, applications, status history, EMI schedules and payments. ID card photos go to an R2 bucket.
| Endpoint | Method | Access | What it does |
|---|---|---|---|
/api/auth/register | POST | Public | Create account — PBKDF2 password hash, session cookie issued |
/api/auth/login | POST | Public | Verify password, create a server session (7 days) |
/api/auth/logout | POST | User | Delete the session row and clear the cookie |
/api/auth/me | GET | User | Current user and role from the session cookie |
/api/loans | POST / GET | User | Submit an application (EMI + schedule generated server-side) / list my loans |
/api/admin/stats | GET | Admin | Totals by status and user count |
/api/admin/applications | GET | Admin | Search and filter all applications |
/api/admin/status | POST | Admin | Approve / Cancel / Disburse / Repaid + status history entry |
/api/admin/payment | POST | Admin | Record an EMI payment and mark the schedule row paid |
/api/admin/users | GET | Admin | All registered users with roles |
/api/settings | GET | Public | All site settings from the settings table — the page applies them on load, nothing is hardcoded |
/api/admin/settings | POST | Admin | Save site settings (name, tagline, theme color, texts, amounts, tenures, EMI table, contacts, notifications) |
/api/telegram/webhook | POST | Telegram | Approve / Cancel callbacks update D1 and confirm in chat |
/api/admin/login | POST | Public → Admin | Admin sign-in for /admin — verifies the Cloudflare Turnstile token with the secret key first, then the password, then issues an admin session |
1 · Database Schema (D1)
Users, sessions, applications, status history, EMI schedule and payments.
-- schema.sql — run once on your D1 database:
-- wrangler d1 execute great-loan-db --remote --file=schema.sql
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL, phone TEXT UNIQUE NOT NULL,
pass_hash TEXT NOT NULL, salt TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'user', -- 'user' | 'admin'
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS sessions (
token TEXT PRIMARY KEY, user_id INTEGER NOT NULL,
expires_at INTEGER NOT NULL -- epoch ms, 7 days
);
CREATE TABLE IF NOT EXISTS applications (
id TEXT PRIMARY KEY, user_id INTEGER,
name TEXT, age INTEGER, whatsapp TEXT, occupation TEXT,
amount INTEGER, tenure INTEGER, purpose TEXT,
loan_reason TEXT DEFAULT '', -- applicant's detailed Reason / Details
id_type TEXT, id_front_key TEXT, id_back_key TEXT, -- R2 object keys
emi INTEGER, status TEXT DEFAULT 'Pending',
reason TEXT DEFAULT '', paid_emis INTEGER DEFAULT 0,
created_at TEXT, disbursed_on TEXT
);
CREATE TABLE IF NOT EXISTS status_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
app_id TEXT, status TEXT, note TEXT, at TEXT
);
CREATE TABLE IF NOT EXISTS emi_schedule (
id INTEGER PRIMARY KEY AUTOINCREMENT,
app_id TEXT, n INTEGER, due_date TEXT,
emi INTEGER, principal INTEGER, interest INTEGER,
balance INTEGER, paid INTEGER DEFAULT 0
);
CREATE TABLE IF NOT EXISTS payments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
app_id TEXT, n INTEGER, amount INTEGER, method TEXT, at TEXT
);
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY, value TEXT NOT NULL -- one JSON row, key = 'site'
);
-- The admin panel's Site Settings page reads / writes that JSON row:
-- SELECT value FROM settings WHERE key = 'site';
-- INSERT INTO settings (key, value) VALUES ('site', '{...}')
-- ON CONFLICT(key) DO UPDATE SET value = excluded.value;
-- Make your own account an admin after registering:
-- UPDATE users SET role = 'admin' WHERE phone = 'YOUR_PHONE';
2 · Project Config
Bindings for the D1 database and the R2 file bucket.
# wrangler.toml — place next to index.html, with a functions/ folder beside it name = "great-loan" pages_build_output_dir = "." compatibility_date = "2024-11-01" [[d1_databases]] binding = "DB" database_name = "great-loan-db" database_id = "<your-d1-database-id>" [[r2_buckets]] binding = "FILES" bucket_name = "great-loan-files" # Sessions live in D1 (sessions table). A KV namespace can replace them # later for faster reads; the API contract stays the same.
3 · Deploy Steps
Create the database. Cloudflare dashboard → Storage & Databases → D1 → Create great-loan-db, then run schema.sql in its console (or with Wrangler).
Create the file bucket. R2 → Create bucket great-loan-files for ID card photos.
Add the functions. Put this page and a functions/ folder (files below) in the Pages project great-loan, with the wrangler.toml bindings — or add the same D1 / R2 bindings in Pages → Settings → Functions.
Set the secrets. Pages → Settings → Environment variables: TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID.
Make yourself admin. Register normally, then run in the D1 console: UPDATE users SET role = 'admin' WHERE phone = 'your phone';
Register the Telegram webhook. Open once: https://api.telegram.org/bot<TOKEN>/setWebhook?url=https://great-loan.pages.dev/api/telegram/webhook
4 · Shared Helpers — functions/api/_shared.js
JSON responses, PBKDF2 password hashing, session cookies, role guards.
// functions/api/_shared.js — helpers shared by every Pages Function
// Bindings (Pages project -> Settings -> Functions, or wrangler.toml):
// DB -> D1 database (users, sessions, applications, ...)
// FILES -> R2 bucket for ID card photos
export function json(data, status = 200, extra = {}) {
return new Response(JSON.stringify(data), {
status, headers: { 'content-type': 'application/json', ...extra }
});
}
async function pbkdf2(password, salt) {
const enc = new TextEncoder();
const key = await crypto.subtle.importKey('raw', enc.encode(password), 'PBKDF2', false, ['deriveBits']);
const bits = await crypto.subtle.deriveBits(
{ name: 'PBKDF2', salt: enc.encode(salt), iterations: 100000, hash: 'SHA-256' }, key, 256);
return [...new Uint8Array(bits)].map(b => b.toString(16).padStart(2, '0')).join('');
}
export async function hashPassword(password) {
const salt = crypto.randomUUID();
return { salt, hash: await pbkdf2(password, salt) };
}
export async function checkPassword(password, salt, expected) {
return (await pbkdf2(password, salt)) === expected;
}
export function sessionCookie(token) {
return 'gl_session=' + token + '; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=' + (7 * 24 * 3600);
}
export async function createSession(env, userId) {
const token = crypto.randomUUID() + crypto.randomUUID();
await env.DB.prepare('INSERT INTO sessions (token, user_id, expires_at) VALUES (?, ?, ?)')
.bind(token, userId, Date.now() + 7 * 24 * 3600 * 1000).run();
return token;
}
export async function currentUser(request, env) {
const m = (request.headers.get('cookie') || '').match(/gl_session=([^;]+)/);
if (!m) return null;
return env.DB.prepare(
'SELECT u.id, u.name, u.phone, u.role FROM sessions s JOIN users u ON u.id = s.user_id ' +
'WHERE s.token = ? AND s.expires_at > ?').bind(m[1], Date.now()).first();
}
export async function requireUser(request, env) {
const user = await currentUser(request, env);
if (!user) throw json({ error: 'Login required' }, 401);
return user;
}
export async function requireAdmin(request, env) {
const user = await requireUser(request, env);
if (user.role !== 'admin') throw json({ error: 'Admin only' }, 403);
return user;
}
5 · Auth API — functions/api/auth/[[route]].js
Register, login, logout and /me — server-side sessions, roles user / admin.
// functions/api/auth/[[route]].js — one catch-all file for /api/auth/*
// POST /api/auth/register POST /api/auth/login
// POST /api/auth/logout GET /api/auth/me
import { json, hashPassword, checkPassword, createSession, sessionCookie, currentUser } from '../_shared.js';
export async function onRequest({ request, env, params }) {
const route = (params.route || []).join('/');
try {
if (route === 'register' && request.method === 'POST') {
const { name, phone, password } = await request.json();
if (!name || !phone || !password || password.length < 6)
return json({ error: 'Name, phone and a 6+ character password are required' }, 400);
const exists = await env.DB.prepare('SELECT id FROM users WHERE phone = ?').bind(phone).first();
if (exists) return json({ error: 'Phone already registered' }, 409);
const { salt, hash } = await hashPassword(password);
const r = await env.DB.prepare(
'INSERT INTO users (name, phone, pass_hash, salt, role, created_at) VALUES (?, ?, ?, ?, ?, ?)')
.bind(name, phone, hash, salt, 'user', new Date().toISOString()).run();
const token = await createSession(env, r.meta.last_row_id);
return json({ id: r.meta.last_row_id, name, phone, role: 'user' }, 201,
{ 'set-cookie': sessionCookie(token) });
}
if (route === 'login' && request.method === 'POST') {
const { phone, password } = await request.json();
const u = await env.DB.prepare('SELECT * FROM users WHERE phone = ?').bind(phone).first();
if (!u || !(await checkPassword(password, u.salt, u.pass_hash)))
return json({ error: 'Wrong phone or password' }, 401);
const token = await createSession(env, u.id);
return json({ id: u.id, name: u.name, phone: u.phone, role: u.role }, 200,
{ 'set-cookie': sessionCookie(token) });
}
if (route === 'logout' && request.method === 'POST') {
const m = (request.headers.get('cookie') || '').match(/gl_session=([^;]+)/);
if (m) await env.DB.prepare('DELETE FROM sessions WHERE token = ?').bind(m[1]).run();
return json({ ok: true }, 200,
{ 'set-cookie': 'gl_session=; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=0' });
}
if (route === 'me' && request.method === 'GET') {
const user = await currentUser(request, env);
return user ? json(user) : json({ error: 'Not logged in' }, 401);
}
return json({ error: 'Not found' }, 404);
} catch (e) {
return e instanceof Response ? e : json({ error: 'Server error' }, 500);
}
}
6 · Loans API — functions/api/loans.js
Creates the application from multipart/form-data, validates every field and BOTH ID photos (400 if anything is missing), generates the full EMI schedule in D1, stores the photos (R2 when bound, otherwise Telegram file_ids) and forwards the full form + both photos to Telegram.
// POST /api/loans — submit a loan application (login required).
// The Apply form posts multipart/form-data with ALL fields plus BOTH ID
// photos (id_front, id_back). Both photos are mandatory: the UI blocks a
// submit without them AND this endpoint rejects it with 400. A JSON body
// without photos is also rejected — photos can only arrive as files.
// Flow: validate everything -> save to D1 (applications + status_history +
// emi_schedule) -> store photos in R2 when the FILES binding exists ->
// send the full form + BOTH photos to the admin on Telegram (sendPhoto x2
// with captions + a text message with Approve / Cancel buttons). If any
// Telegram delivery fails, the D1 rows (and R2 objects) are rolled back and
// the request fails with 502 — the form is never sent without its photos.
// GET /api/loans — my applications (login required).
import { json, requireUser, tgCall, tgSendPhoto, largestPhotoFileId, adminChatId } from './_shared.js';
const EMI_TABLE = {
20000: { 12: 1850, 24: 1020 }, 50000: { 12: 4620, 24: 2540 },
100000: { 12: 9240, 24: 5080 }, 200000: { 12: 18480, 24: 10160 },
250000: { 12: 23100, 24: 12700 },
};
const RATE = 0.0164;
const MAX_PHOTO_BYTES = 5 * 1024 * 1024; // 5 MB per photo
const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
function emiFor(amount, months) {
if (EMI_TABLE[amount] && EMI_TABLE[amount][months]) return EMI_TABLE[amount][months];
return Math.round((amount * RATE / (1 - Math.pow(1 + RATE, -months))) / 10) * 10;
}
function badPhoto(file, label) {
if (!file || typeof file !== 'object' || typeof file.size !== 'number' || file.size === 0)
return label + ' photo is required — please upload the ID card photo.';
if (file.size > MAX_PHOTO_BYTES)
return label + ' photo is too large (max 5 MB). Please upload a smaller photo.';
const type = (file.type || '').toLowerCase();
if (!ALLOWED_TYPES.includes(type) && !type.startsWith('image/'))
return label + ' photo must be a JPG or PNG image.';
return null;
}
function extOf(file) {
const name = (file.name || '').toLowerCase();
const dot = name.lastIndexOf('.');
if (dot > -1 && name.length - dot <= 5) return name.slice(dot + 1);
const t = (file.type || '').toLowerCase();
if (t === 'image/png') return 'png';
if (t === 'image/webp') return 'webp';
if (t === 'image/gif') return 'gif';
return 'jpg';
}
export async function onRequestPost({ request, env }) {
let id = null;
let r2Keys = [];
try {
const user = await requireUser(request, env);
const ct = (request.headers.get('content-type') || '').toLowerCase();
// ---- Parse body: multipart/form-data is the only way photos arrive.
let f = null;
if (ct.includes('multipart/form-data')) {
f = await request.formData();
} else {
// JSON (or anything else) can never carry the photos.
return json({ error: 'ID photos are required — please upload the front and back photos of your ID card.' }, 400);
}
const s = (k) => String(f.get(k) || '').trim();
const name = s('name') || user.name || '';
const age = parseInt(s('age'), 10);
const whatsapp = s('whatsapp') || s('phone') || user.phone || '';
const occupation = s('occupation');
const amount = parseInt(s('amount'), 10);
const tenure = parseInt(s('tenure'), 10);
const purpose = s('purpose');
const loanReason = s('loanReason') || s('reasonDetails') || s('reason') || '';
const idType = s('idType') || s('id_type') || '';
const front = f.get('id_front');
const back = f.get('id_back');
// ---- Validate EVERYTHING (the UI validates too; the server is the gate).
if (!name || name.length < 2) return json({ error: 'Please enter your full name.' }, 400);
if (!age || age < 18 || age > 80) return json({ error: 'Age must be between 18 and 80.' }, 400);
if (whatsapp.replace(/\D/g, '').length < 10) return json({ error: 'Please enter a valid WhatsApp number.' }, 400);
if (!occupation) return json({ error: 'Please select your occupation.' }, 400);
if (!EMI_TABLE[amount]) return json({ error: 'Please select a valid loan amount.' }, 400);
if (![6, 12, 18, 24, 30, 36].includes(tenure)) return json({ error: 'Please select a valid loan tenure.' }, 400);
if (!purpose) return json({ error: 'Please select the loan purpose.' }, 400);
if (loanReason.length < 10) return json({ error: 'Please write in detail why you need this loan (Reason / Details, at least a short sentence).' }, 400);
if (!idType) return json({ error: 'Please select your ID card type.' }, 400);
const frontErr = badPhoto(front, 'Front');
if (frontErr) return json({ error: frontErr }, 400);
const backErr = badPhoto(back, 'Back');
if (backErr) return json({ error: backErr }, 400);
const chatId = adminChatId(env);
if (!env.TELEGRAM_BOT_TOKEN || !chatId)
return json({ error: 'The loan desk is not connected to Telegram yet — please try again later.' }, 502);
const emi = emiFor(amount, tenure);
id = 'LP-' + new Date().getFullYear() + '-' + crypto.randomUUID().slice(0, 8).toUpperCase();
const now = new Date();
// ---- Save to D1 first (photos are added right after Telegram confirms).
await env.DB.prepare(
'INSERT INTO applications (id, user_id, name, phone, age, whatsapp, occupation, amount, tenure, purpose, loan_reason, id_type, id_front_key, id_back_key, emi, status, created_at) ' +
'VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,\'Pending\',?)')
.bind(id, user.id, name, user.phone || whatsapp, age, whatsapp, occupation, amount, tenure,
purpose, loanReason, idType, '', '', emi, now.toISOString()).run();
await env.DB.prepare('INSERT INTO status_history (app_id, status, note, at) VALUES (?,?,?,?)')
.bind(id, 'Pending', 'Application submitted', now.toISOString()).run();
const stmts = [];
let balance = amount;
for (let i = 1; i <= tenure; i++) {
const interest = Math.round(balance * RATE);
let principal = emi - interest;
if (i === tenure) principal = balance;
balance = Math.max(0, balance - principal);
const due = new Date(now);
due.setMonth(due.getMonth() + i);
stmts.push(env.DB.prepare(
'INSERT INTO emi_schedule (app_id, n, due_date, emi, principal, interest, balance) VALUES (?,?,?,?,?,?,?)')
.bind(id, i, due.toISOString().slice(0, 10), i === tenure ? principal + interest : emi, principal, interest, balance));
}
await env.DB.batch(stmts);
// ---- Durable photo storage: R2 when the FILES binding exists.
let frontKey = '';
let backKey = '';
if (env.FILES) {
try {
frontKey = 'applications/' + id + '/front.' + extOf(front);
backKey = 'applications/' + id + '/back.' + extOf(back);
await env.FILES.put(frontKey, await front.arrayBuffer(), { httpMetadata: { contentType: front.type || 'image/jpeg' } });
r2Keys.push(frontKey);
await env.FILES.put(backKey, await back.arrayBuffer(), { httpMetadata: { contentType: back.type || 'image/jpeg' } });
r2Keys.push(backKey);
} catch (e) {
frontKey = '';
backKey = '';
}
}
// ---- Telegram: full form + BOTH photos, together or not at all.
const keyboard = { inline_keyboard: [[
{ text: '✅ Approve', callback_data: 'approve:' + id },
{ text: '❌ Cancel', callback_data: 'cancel:' + id },
]] };
const fullText =
'🆕 New Loan Application ' + id + '\n' +
'Name: ' + name + ' (age ' + age + ')\n' +
'WhatsApp: ' + whatsapp + '\n' +
'Occupation: ' + occupation + '\n' +
'Amount: ₹' + amount + ' · Tenure: ' + tenure + ' months · EMI: ₹' + emi + '/month\n' +
'Purpose: ' + purpose + '\n' +
'Reason / Details: ' + loanReason + '\n' +
'ID Card: ' + idType + ' (front + back photos attached)';
const captionFront = fullText.slice(0, 1000);
const captionBack = 'ID Card — Back photo\n' + id + ' · ' + name + '\n' + idType;
const sentFront = await tgSendPhoto(env, chatId, front, captionFront, keyboard);
if (!sentFront.ok) throw new Error('Telegram front photo failed: ' + sentFront.error);
const sentBack = await tgSendPhoto(env, chatId, back, captionBack, keyboard);
if (!sentBack.ok) throw new Error('Telegram back photo failed: ' + sentBack.error);
const sentText = await tgCall(env, 'sendMessage', {
chat_id: chatId, text: fullText, reply_markup: keyboard,
});
if (!sentText.ok) throw new Error('Telegram message failed: ' + sentText.error);
const frontFileId = largestPhotoFileId(sentFront.result);
const backFileId = largestPhotoFileId(sentBack.result);
if (!frontKey) frontKey = frontFileId ? 'tg:' + frontFileId : '';
if (!backKey) backKey = backFileId ? 'tg:' + backFileId : '';
await env.DB.prepare(
'UPDATE applications SET id_front_key = ?, id_back_key = ?, tg_front_file_id = ?, tg_back_file_id = ?, ' +
'tg_front_msg_id = ?, tg_back_msg_id = ?, tg_msg_id = ? WHERE id = ?')
.bind(frontKey, backKey, frontFileId, backFileId,
sentFront.result.message_id || null, sentBack.result.message_id || null,
sentText.result.message_id || null, id).run();
return json({ id, emi, status: 'Pending', photosDelivered: true }, 201);
} catch (e) {
// Roll back: never leave an application whose photos never reached Telegram.
if (id) {
try {
if (env.FILES) {
for (const k of r2Keys) { try { await env.FILES.delete(k); } catch (_) {} }
}
await env.DB.batch([
env.DB.prepare('DELETE FROM emi_schedule WHERE app_id = ?').bind(id),
env.DB.prepare('DELETE FROM status_history WHERE app_id = ?').bind(id),
env.DB.prepare('DELETE FROM applications WHERE id = ?').bind(id),
]);
} catch (_) {}
}
if (e instanceof Response) return e;
const msg = String((e && e.message) || 'Server error');
if (msg.startsWith('Telegram')) return json({ error: 'Could not deliver your application with photos to the admin on Telegram (' + msg + '). Please try again.' }, 502);
return json({ error: 'Server error' }, 500);
}
}
export async function onRequestGet({ request, env }) {
try {
const user = await requireUser(request, env);
const apps = await env.DB.prepare(
'SELECT * FROM applications WHERE user_id = ? ORDER BY created_at DESC').bind(user.id).all();
return json({ applications: apps.results });
} catch (e) {
return e instanceof Response ? e : json({ error: 'Server error' }, 500);
}
}
7 · Admin API — functions/api/admin/[[route]].js
Stats, application search, status changes with history, EMI payments, user list.
// functions/api/admin/[[route]].js — every route requires role = 'admin'
// GET /api/admin/stats
// GET /api/admin/applications?status=Pending&q=rahim
// POST /api/admin/status { id, status, reason }
// POST /api/admin/payment { appId, n, amount, method }
// GET /api/admin/users
import { json, requireAdmin } from '../_shared.js';
export async function onRequest({ request, env, params }) {
try {
await requireAdmin(request, env);
const route = (params.route || []).join('/');
const url = new URL(request.url);
if (route === 'stats' && request.method === 'GET') {
const rows = await env.DB.prepare(
'SELECT status, COUNT(*) c, COALESCE(SUM(amount),0) amt FROM applications GROUP BY status').all();
const users = await env.DB.prepare('SELECT COUNT(*) c FROM users').first();
return json({ users: users.c, byStatus: rows.results });
}
if (route === 'applications' && request.method === 'GET') {
const st = url.searchParams.get('status') || '';
const q = '%' + (url.searchParams.get('q') || '') + '%';
const rows = await env.DB.prepare(
"SELECT * FROM applications WHERE (? = '' OR status = ?) AND (name LIKE ? OR whatsapp LIKE ? OR id LIKE ?) ORDER BY created_at DESC")
.bind(st, st, q, q, q).all();
return json({ applications: rows.results });
}
if (route === 'status' && request.method === 'POST') {
const { id, status, reason } = await request.json();
if (!['Approved', 'Cancelled', 'Disbursed', 'Repaid'].includes(status))
return json({ error: 'Bad status' }, 400);
await env.DB.prepare('UPDATE applications SET status = ?, reason = ? WHERE id = ?')
.bind(status, reason || '', id).run();
await env.DB.prepare('INSERT INTO status_history (app_id, status, note, at) VALUES (?,?,?,?)')
.bind(id, status, 'Changed from admin panel', new Date().toISOString()).run();
return json({ id, status });
}
if (route === 'payment' && request.method === 'POST') {
const { appId, n, amount, method } = await request.json();
await env.DB.prepare('INSERT INTO payments (app_id, n, amount, method, at) VALUES (?,?,?,?,?)')
.bind(appId, n, amount, method || 'manual', new Date().toISOString()).run();
await env.DB.prepare('UPDATE emi_schedule SET paid = 1 WHERE app_id = ? AND n = ?').bind(appId, n).run();
await env.DB.prepare('UPDATE applications SET paid_emis = paid_emis + 1 WHERE id = ?').bind(appId).run();
return json({ ok: true });
}
if (route === 'users' && request.method === 'GET') {
const rows = await env.DB.prepare(
'SELECT id, name, phone, role, created_at FROM users ORDER BY created_at DESC').all();
return json({ users: rows.results });
}
return json({ error: 'Not found' }, 404);
} catch (e) { return e instanceof Response ? e : json({ error: 'Server error' }, 500); }
}
8 · Telegram Webhook — functions/api/telegram/webhook.js
Approve / Cancel taps in Telegram update the application row in D1, write a status-history entry and confirm back in the chat.
// functions/api/telegram/webhook.js — D1 version
// Secrets: TELEGRAM_BOT_TOKEN, TELEGRAM_CHAT_ID - Binding: DB (D1)
async function tg(env, method, payload) {
return fetch('https://api.telegram.org/bot' + env.TELEGRAM_BOT_TOKEN + '/' + method, {
method: 'POST', headers: { 'content-type': 'application/json' },
body: JSON.stringify(payload) });
}
export async function onRequestPost({ request, env }) {
const update = await request.json();
const cb = update.callback_query;
if (!cb) return new Response('ok');
if (String(cb.message.chat.id) !== String(env.TELEGRAM_CHAT_ID))
return new Response('forbidden', { status: 403 });
const parts = cb.data.split(':');
const status = parts[0] === 'approve' ? 'Approved' : 'Cancelled';
const appId = parts[1];
await env.DB.prepare('UPDATE applications SET status = ? WHERE id = ?').bind(status, appId).run();
await env.DB.prepare('INSERT INTO status_history (app_id, status, note, at) VALUES (?,?,?,?)')
.bind(appId, status, 'Changed from Telegram bot', new Date().toISOString()).run();
await tg(env, 'answerCallbackQuery', { callback_query_id: cb.id, text: appId + ' marked ' + status });
await tg(env, 'editMessageText', { chat_id: cb.message.chat.id, message_id: cb.message.message_id,
text: cb.message.text + '\n\nStatus: ' + status });
return new Response('ok');
}
9 · Site Settings API — functions/api/settings.js + functions/api/admin/settings.js
The Site Settings page in the admin panel saves one JSON object; the public endpoint serves it back so every visitor's page renders from the database, not from hardcoded values.
// functions/api/settings.js — GET /api/settings (public, read-only)
// Returns the JSON the admin saved from Admin → Site Settings.
export async function onRequestGet({ env }) {
const row = await env.DB.prepare("SELECT value FROM settings WHERE key = 'site'").first();
return new Response(row ? row.value : '{}', {
headers: { 'content-type': 'application/json', 'cache-control': 'no-store' }
});
}
// functions/api/admin/settings.js — POST /api/admin/settings (admin only)
import { json, requireAdmin } from '../_shared.js';
export async function onRequestPost({ request, env }) {
try {
await requireAdmin(request, env);
const settings = await request.json();
await env.DB.prepare(
"INSERT INTO settings (key, value) VALUES ('site', ?) " +
'ON CONFLICT(key) DO UPDATE SET value = excluded.value')
.bind(JSON.stringify(settings)).run();
return json({ ok: true });
} catch (e) { return e instanceof Response ? e : json({ error: 'Server error' }, 500); }
}
10 · Admin Login + Turnstile — functions/api/admin/login.js
Powers the /admin login page. The browser widget (site key set in Site Settings) returns a token; this function verifies it server-side with the secret key before checking the password — no token, no login. Secrets (Pages → Settings → Environment variables): TURNSTILE_SECRET_KEY. Never put the secret in the page.
// functions/api/admin/login.js — POST /api/admin/login
// Body: { username, password, turnstileToken }
// Order matters: 1) Turnstile siteverify, 2) password, 3) role = 'admin'.
import { json, checkPassword, createSession, sessionCookie } from '../_shared.js';
async function verifyTurnstile(env, token, ip) {
if (!token) return false;
const form = new URLSearchParams();
form.set('secret', env.TURNSTILE_SECRET_KEY); // server secret only
form.set('response', token);
if (ip) form.set('remoteip', ip);
const r = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', {
method: 'POST', body: form
});
const data = await r.json();
return data.success === true;
}
export async function onRequestPost({ request, env }) {
try {
const { username, password, turnstileToken } = await request.json();
const ip = request.headers.get('CF-Connecting-IP') || '';
if (!(await verifyTurnstile(env, turnstileToken, ip)))
return json({ error: 'Turnstile check failed — please tick I am not a robot and try again' }, 403);
const u = await env.DB.prepare('SELECT * FROM users WHERE name = ? OR phone = ?').bind(username, username).first();
if (!u || !(await checkPassword(password, u.salt, u.pass_hash)))
return json({ error: 'Wrong username or password' }, 401);
if (u.role !== 'admin')
return json({ error: 'This account does not have the admin role' }, 403);
const token = await createSession(env, u.id);
return json({ id: u.id, name: u.name, phone: u.phone, role: u.role }, 200,
{ 'set-cookie': sessionCookie(token) });
} catch (e) { return e instanceof Response ? e : json({ error: 'Server error' }, 500); }
}