Skip to content

API Reference

One HTTP API: the Go/Fiber backend, all routes under the base path /api/v1 (aim-backend/internal/handler/routes.go).

API Base URL Auth Source
Backend API https://api.aimstoreorg.com/api/v1 custom JWT or Firebase ID token; some routes public aim-backend/

The website's Express payment server (aim-store-website/server/index.js) additionally exposes gateway endpoints under https://aimstoreorg.com/api/* (CCAvenue/PhonePe initiate/response/webhook) — those are gateway plumbing, not part of the /api/v1 surface.

Conventions

  • Auth: protected routes go through a dual-auth middleware (internal/middleware/firebase_auth.go) that accepts either x-sdk-access-token: <custom JWT> (issued by the OTP and admin-login flows) or Authorization: Bearer <firebase_id_token>. Rows below say public, token, or admin.
  • Admin: admin routes additionally require the JWT claim role == "admin" (set from users.is_admin); anything else is 403.
  • Errors: non-2xx responses carry {"error": "message"}. Some rate-limited endpoints add a code field (e.g. OTP_RATE_LIMITED).
  • Responses are plain JSON maps built per handler — there is no global envelope. Read the handler file in aim-backend/internal/handler/ for the exact shape of a given endpoint.
  • /metrics (Prometheus) and /health exist at the app root; /metrics is blocked publicly at Caddy.

Health & meta

Method Path Auth Summary
GET /health public Liveness probe → {status:"ok"}. (App root, not under /api/v1.)
GET /app/version public App-version gate for the mobile client → {version, apk_url, force_update, …}.

Auth

Method Path Auth Summary
POST /auth/register public Create account with {phone, password, full_name}; creates the wallet → 201 {custom_token}. 409 duplicate phone. Optional referral_code attributes the signup to a referrer (invalid codes are silently ignored — never a registration failure).
POST /auth/login public Phone + password login → {custom_token} (Firebase custom token).
POST /auth/admin/login public New. Password login for the admin portal: {phone, password} → {access_token, user} where user.is_admin is true. Uniform 401 on any failure; 429 after 10 attempts per phone+IP per 15 min.
POST /auth/support/login public Password login for the support portal (ADR 0018): {phone, password} → {access_token, user}; admits is_support or is_admin accounts, and the token carries role support (or admin). user has id, firebase_uid, phone, email, display_name, avatar_url, is_admin, is_support — no wallet fields. Uniform 401 on any failure; same attempt cap as the admin login.
POST /auth/reset-password public Reset password (OTP-verified).
POST /auth/otp/send public Send a login OTP via SMS. No server-side send limit (the SMS provider caps volume); verifying is capped at 5 wrong attempts per code (429 OTP_ATTEMPTS_EXCEEDED).
POST /auth/otp/verify public Verify OTP; auto-creates user + wallet on first signup (gated by purpose) → tokens + user (incl. email_verified). Optional referral_code + referral_source (install_referrer | manual) attribute a new user's signup; absent those, an IP match against recent /r/:code clicks is tried. Invalid codes never fail signup.
POST /auth/refresh public Refresh the custom JWT.
POST /auth/logout token Revoke the caller's active tokens server-side.
GET /me token Caller profile (incl. email_verified, true iff the current email was OTP-verified).
PATCH /me token Update own profile fields. Changing email to a different value clears its verified status.

Email verification

Authenticated OTP flow that proves ownership of the caller's email address. Gated on SMTP configuration (SMTP_*) — unconfigured, send-otp returns 503 {"error":"email_disabled"}.

Method Path Auth Summary
POST /me/email/send-otp token Send a 6-digit OTP to {email} (10-min TTL). 409 if the email belongs to a different user; 60s resend cooldown, max 5 sends/hour per user and 20/hour per IP.
POST /me/email/verify-otp token Verify {otp} (max 5 attempts, then the OTP is burned); on success sets the email + verified timestamp → {email, email_verified: true}.

Referrals

Every user can lazily mint a referral code and share https://aimstoreorg.com/r/<CODE>. Attribution happens at signup (see /auth/otp/verify and /auth/register above) — explicit code first, IP match against recent clicks as fallback.

Method Path Auth Summary
GET /r/:code public Referral share-link redirect: records the click (code, client IP, user-agent) and 302s to the Play Store with the code encoded in the install-referrer query. Unknown/malformed codes still redirect (no click recorded). 20/hour per IP. (App root on aimstoreorg.com — routed by Caddy to the API — not under /api/v1.)
GET /referrals/my-code token Caller's referral code, lazily generated on first call → {referral_code, share_url}.
GET /referrals/check public Most recent referral click from the caller's IP within the attribution window (default 48h) → {referral_code} (or null). 30/hour per IP.

Account deletion

Google Play requires a deletion route that works without installing or signing into the app, so the web/ flow is unauthenticated — each step is gated on an OTP sent to the registered mobile.

Method Path Auth Summary
POST /account/deletion/web/send-otp public Start web deletion: send OTP to the registered phone.
POST /account/deletion/web/verify public Verify the web-deletion OTP.
POST /account/deletion/web/request public File the deletion request (OTP-proven).
GET /account/deletion/eligibility token Can this account be deleted (open orders/balances)?
POST /account/deletion/send-otp token Send in-app deletion OTP.
POST /account/deletion/verify-otp token Verify the deletion OTP.
POST /account/deletion/request token Request deletion for the caller's own account.
GET /account/deletion/status token Deletion request status.
POST /account/deletion/cancel token Cancel a pending deletion.

Catalogue (public storefront)

Method Path Auth Summary
GET /products public Product catalogue.
GET /products/:id public One product.
GET /categories public Category list.

Catalogue images uploaded through the admin portal are served (outside /api/v1) at GET /media/:key — public and unauthenticated, because these are the product photos every storefront visitor already sees. The key is the content hash minted at upload, so the bytes under it never change and the response is Cache-Control: public, max-age=31536000, immutable.

Each product carries both a single cover image and its full gallery (ADR 0013):

{
  "id": "…", "name": "Circle (Ai-ENC) TWS Earbuds",
  "image_url": "https://cdn…/01.jpg",
  "images": [
    { "id": "…", "image_url": "https://cdn…/01.jpg", "alt_text": "tws earphones", "sort_order": 0 },
    { "id": "…", "image_url": "https://cdn…/02.jpg", "alt_text": "tws earphones", "sort_order": 1 }
  ]
}

images is ordered by sort_order, always present ([] when the product has no images, never null), and images[0].image_url always equals image_url. A client that only wants one image can keep reading image_url alone.

Wallet

Method Path Auth Summary
GET /wallet token Balance (shopping credits, reward points, e-vouchers).
GET /wallet/transactions token Transaction history.
POST /wallet/topup-initiate token Start a top-up: mints a one-time token → hosted-page URL. 503 until TOPUP_PAGE_BASE_URL is configured.
GET /wallet/topup-status/:token token Poll a top-up; verifies directly with PhonePe and credits if the callback hasn't landed yet.
POST /wallet/topup-credit public (HMAC) Gateway-confirmed credit callback from the website payment server; mandatory HMAC over STORE_WEBHOOK_SECRET (503 if unconfigured).
POST /wallet/settle-pending token Compatibility no-op (pending buckets retired with the gaming currencies) → {wallet, settled: 0}.
POST /wallet/daily-spin token Free daily Spin & Win → credits shopping credits; prize amount is a server-side constant.

No direct top-up route

POST /wallet/topup is intentionally not routed — it credited shopping credits with no payment. Money enters only through topup-initiate → hosted page → verified topup-credit / topup-status. Do not re-add it (see the comment in routes.go).

Orders & payment gateways

Method Path Auth Summary
GET /payment-gateways token Active gateways the client may offer.
POST /orders/quote token Server-authoritative price quote for a cart.
POST /orders token Place an order paid from the shopping-credits wallet.
GET /orders token List the caller's orders.
GET /orders/:id token One order.
POST /orders/:id/cancel token Cancel an order (refunds the wallet).

Support tickets

The customer support desk (ADR 0016). Every support route returns errors as {"error": "…", "code": "UPPER_SNAKE"} (plus field for VALIDATION_FAILED). Lists are {"data": [...], "count": n}. Timestamps are UTC YYYY-MM-DDTHH:MM:SSZ, or null, and money is integer *_paise. A ticket that is not the caller's answers 404 TICKET_NOT_FOUND. No support route waits on SMTP or fails because email is unavailable: emails are queued and sent later by the support worker.

Method Path Auth Summary
GET /support/help public Help Centre: active topics (two levels) with their FAQs, plus the support contact block → {data: {topics, contact}}. Cache-Control: public, max-age=60. A topic whose feature is switched off is omitted (KARAT 24 unless explicitly enabled).
POST /tickets token Open a ticket: {description, topic_key?, category?, subject?, sub_category?, chat_path?, order_id?, client_request_id?, channel?} → 201 {data: CustomerTicket}. Needs topic_key or category; channel is app or web. With topic_key, the category, priority and grievance flag come from the topic; a topic with visible children needs a child (400 TOPIC_NOT_FOUND). order_id must be the caller's (400 ORDER_NOT_FOUND). A repeated client_request_id returns the original as 200 {data, duplicate: true}. 429 TOO_MANY_OPEN_TICKETS above the active-ticket limit. 10/hour.
GET /tickets token Own tickets, most recently updated first, max 100; optional ?status= active, resolved, closed or all → {data, count, unread_count}.
GET /tickets/:id token {data: {ticket, replies, timeline}}. Marks the ticket as seen (clears has_unread).
POST /tickets/:id/reply token {message} → 201 {data: reply, ticket}. A reply to a ticket waiting on the customer moves it back to open; a reply to a resolved ticket inside the reopen window reopens it. 409 TICKET_CLOSED / REOPEN_WINDOW_EXPIRED. 60/hour.
POST /tickets/:id/confirm-resolution token "This is fixed": resolved → closed. Repeating it is a no-op.
POST /tickets/:id/reopen token {reason} (5–2000 chars). Resolved, or closed other than by an agent, within the reopen window of the last resolution → open. 10/hour.
POST /tickets/:id/rating token {rating: 1–5, comment?}, once per ticket, on a resolved or closed ticket. 409 ALREADY_RATED / NOT_RATEABLE. 10/hour.
POST /tickets/:id/escalate token {reason}: escalate to the Grievance Officer. Sets the statutory deadline (the earlier of 30 days and one month), priority urgent, and sends the acknowledgement. Allowed on an active or resolved ticket, or one closed in the last 30 days. 409 ALREADY_ESCALATED. 5/hour.

Topic shape in /support/help (children carry the same fields, including faqs):

{ "key": "orders_delivery", "name": "…", "description": "…",
  "icon": "cube-outline", "icon_web": "Package", "form_hint": "…",
  "order_prompt": "required | optional | none", "sort_order": 10,
  "is_grievance": false,
  "faqs": [ { "id": "…", "question": "…", "answer": "…",
              "link_label": "…", "link_path": "/orders" } ],
  "children": [ … ] }

contact is {support_email, support_phone, support_hours, response_time, grievance_ack_within, grievance_resolve_within}.

CustomerTicket keeps the original ticket fields (id, ticket_number, user_id, category, sub_category, subject, description, status, priority, chat_path, reply_count, created_at, updated_at) and adds topic_key, topic_name, order_id, order_number, channel, resolution_summary, resolution_label, resolved_at, closed_at, closed_reason, reopen_count, is_grievance, grievance_due_at, revised_due_at, delay_reason, csat_rating, csat_comment, has_unread, last_agent_reply_at, customer_attention_at, reopen_deadline, and email_updates (verified | unverified | none, whether this customer also gets updates by email). The server computes can_reply, can_confirm, can_reopen, can_rate and can_escalate on every payload, and clients offer an action only when its flag is true.

  • Statuses: open, in_progress, awaiting_customer (waiting on the customer), resolved, closed. Priorities: low, medium, high, urgent.
  • Replies: {id, ticket_id, user_id, is_admin, message, created_at, author_name, user_name}. On an agent reply, user_id is "" and the author is the configured support display name, never the agent's own name.
  • timeline: customer-visible events only (created, status changes, replies, resolution, reopen, close, auto-close or auto-resolve, grievance escalation, delay notice, rating). from_value and to_value are filled only for a status change (status keys) and a delay notice (the date), and are null otherwise. Internal notes and triage events never appear.

Admin (/api/v1/admin/*)

All routes below require a token whose JWT claim role == "admin" (internal/middleware/firebase_auth.go, AdminOnly). The admin portal obtains such a token from POST /auth/admin/login.

Catalogue & payment gateways

Method Path Summary
GET /admin/products Full catalogue (incl. inactive).
POST /admin/products Create a product.
PUT/DELETE /admin/products/:id Edit/delete a product.
GET/PUT /admin/products/:id/cost Read/set the admin-only unit cost.
GET /admin/categories Category list.
GET/POST /admin/payment-gateways List/create gateways.
PUT/DELETE /admin/payment-gateways/:id Edit/delete a gateway.

Catalogue image upload

POST /api/v1/admin/uploads/image stores an image and returns the URL to save on a product or category:

{ "filename": "circle-black.jpg", "data": "data:image/jpeg;base64,/9j/4AAQ…" }

data may be bare base64 or a full data: URL (what FileReader.readAsDataURL produces). Base64 rather than multipart because the admin browser reaches the API through the portal's Next.js proxy, which reads the body as text.

{ "data": { "url": "https://api.aimstoreorg.com/media/<sha256>.jpg",
            "content_type": "image/jpeg", "bytes": 148213 } }

The stored name is the content hash, so re-uploading identical bytes returns the same URL instead of duplicating the file. The extension and content_type come from sniffing the bytes — filename and any type declared in a data: URL are ignored. PNG, JPEG, GIF and WebP are accepted; SVG is refused (it is XML that can carry script, and it would execute on the API origin). Limits: 413 IMAGE_TOO_LARGE over 5 MB, 400 UNSUPPORTED_IMAGE_TYPE otherwise. A server with no media directory configured answers 503 uploads_disabled, and the admin falls back to pasting a URL.

Product create/update accept an images array of {image_url, alt_text} in display order. The server trims and de-duplicates it, renumbers sort_order densely from 0, caps it at 12 rows, and forces image_url to the first entry — whatever the request sent for image_url is ignored when images is supplied. Omitting images leaves an existing gallery untouched (the pre-gallery client path); sending [] clears it.

Users, dashboard, orders

Method Path Summary
GET /admin/dashboard Headline platform metrics.
GET /admin/transactions All wallet transactions.
GET /admin/users User list/search (each row carries is_admin and is_support).
GET /admin/users/:uid One user.
PUT /admin/users/:uid Edit a user (incl. is_admin and the optional is_support — absent = unchanged). Granting or revoking either needs a super admin (403 SUPER_ADMIN_REQUIRED).Changing the phone of an admin, Super Admin, support agent or accounting-role holder is refused for every caller (403 PRIVILEGED_PHONE_CHANGE); an ordinary account's phone stays editable and its sessions end with the change.
POST /admin/users/:uid/phone-recovery Super Admin only: ask to move a privileged login to a new number ({new_phone, reason}); the two-person recovery (ADR 0025, migration 105).
GET /admin/users/:uid/phone-recovery The open recovery request, numbers masked.
POST /admin/users/:uid/phone-recovery/:id/approve A different verified Super Admin approves; the phone moves, the old binding and sessions end.
POST /admin/users/:uid/phone-recovery/:id/cancel Cancel an open request (requester, another Super Admin, or the account itself).
DELETE /admin/users/:uid Delete a user.
GET /admin/users/:uid/ledger · /orders · /tickets Per-user drill-downs.
GET /admin/webhook/logs Payment-webhook log.
GET /admin/orders All store orders.
POST /admin/orders/:id/status Update an order's status.
POST /admin/orders/:id/refund Refund an order to the wallet.
GET /admin/refunds Refund list.
GET /admin/reconciliation Payments/orders reconciliation view.

Tickets

Same error, list and timestamp conventions as Support tickets. AdminTicket is CustomerTicket without the can_* flags, reopen_deadline and email_updates, plus customer contact (user_name, user_email, user_phone, customer_email_verified, contact_email), assignment (assigned_to, assignee_name, created_by_admin, resolved_by, resolved_by_name), resolution_code, SLA timing (first_response_due_at, resolution_due_at, first_response_at, last_customer_reply_at, awaiting_since, grievance_at, csat_at), sla_state (ok | due_soon | breached | paused | met | missed), needs_reply, and overdue_without_notice (past the resolution target with no current revised date).

Method Path Summary
GET /admin/tickets Queue. Filters: status (one status, active or all), priority, topic (includes its children), assignee (me | unassigned | uuid), sla (breached | due_soon | paused | grievance_overdue: a grievance past its statutory grievance_due_at, a clock that never pauses; with status=active this is the dashboard's grievance_breached count), grievance=true, needs_reply=true, overdue_without_notice=true, recent=true (tickets created in the rolling last 7 × 24 hours ending now — created_at only, any status; the same window as the dashboard's counts.recent_created), channel, q, sort (updated_desc | created_desc | created_asc | due_asc), page, pageSize (1–200, default 50) → {data, count, total, page, pageSize}. Without page or pageSize it returns up to 100 rows, as before.
POST /admin/tickets Create on a customer's behalf: {customer_user_id?, customer_phone?, topic_key?, category?, subject, description, priority?, order_id?, channel, contact_email?, notify_customer?, client_request_id?} → 201 {data}. Identify the customer by customer_user_id or customer_phone; channel is phone, email or admin; contact_email is where this customer's emails go for this ticket. 404 CUSTOMER_NOT_FOUND; the order must belong to that customer (400 ORDER_NOT_FOUND).
GET /admin/tickets/:id {data: {ticket, replies, events, emails, order, customer, agent_display_name}}. replies includes internal notes (is_internal: true). order carries the per-rail refund figures (refund_credits_paise, refund_pending_paise, refund_original_settled_paise, …).
PATCH /admin/tickets/:id Any subset of {priority, topic_key, assigned_to, order_id, subject, revised_due_at, delay_reason, is_grievance}; an absent key is left alone. assigned_to takes "me", a user id or null; order_id an order id or null; is_grievance only true → {data, changed, changed_fields}. A future revised_due_at needs delay_reason and sends the customer a delay notice. 400 ASSIGNEE_NOT_ADMIN / ORDER_NOT_FOUND; 409 TICKET_CLOSED.
PUT /admin/tickets/:id/status {status} → {message, data, changed}. Allowed moves: open ↔ in_progress, awaiting_customer → open/in_progress, resolved → closed, and resolved/closed → open (reopen). A move to resolved, or to closed from an active status, is 409 RESOLUTION_REQUIRED (use /resolve); a move to awaiting_customer is 409 MESSAGE_REQUIRED (reply with set_status).
POST /admin/tickets/:id/reply {message, is_internal?, notify_customer?, set_status?} → 201 {data, ticket}; set_status is in_progress or awaiting_customer. An internal note is never shown or emailed to the customer, and combining it with set_status or notify_customer is 400 VALIDATION_FAILED. A message still containing a {{placeholder}} is 400 UNFILLED_PLACEHOLDER. 409 TICKET_CLOSED.
POST /admin/tickets/:id/resolve {resolution_code, resolution_summary, internal_note?, notify_customer?, close_now?} → {data}. 400 ORDER_REQUIRED when the code needs a linked order, 400 REFUND_STATE_MISMATCH when it names a refund the linked order does not have. Retrying with the identical code and summary is a no-op; anything else on a resolved ticket is 409 ILLEGAL_TICKET_TRANSITION.

Support desk

Configuration and reporting for the support desk. DELETE routes also require a super admin.

Method Path Summary
GET /admin/support/dashboard ?days= 7, 30 (default) or 90, counted in IST days → {data: {generated_at, window_days, counts, averages, daily, by_topic, by_priority, agents, email, attention}}. counts.grievance_breached is active grievances past their statutory grievance_due_at; a grievance that only missed its internal SLA target is in counts.breached instead. counts.urgent_active / counts.high_active count tickets of that priority that are open, in progress or awaiting the customer (the rows of status=active&priority=urgent|high); counts.recent_created counts tickets created in the rolling last 7 × 24 hours, whatever their status (the rows of recent=true).
GET /admin/support/agents Assignable agents (admins and support agents) with their active load.
GET /admin/support/customers ?q= (3+ chars) customer lookup for create-on-behalf; at most 10 results.
GET/POST /admin/support/topics List (with FAQ and ticket counts) / create. 409 TOPIC_EXISTS, 400 INVALID_PARENT / INVALID_ICON.
PUT/DELETE /admin/support/topics/:key Edit / delete. 409 TOPIC_IN_USE.
GET/POST /admin/support/faqs List (?topic_key=) / create.
PUT/DELETE /admin/support/faqs/:id Edit / delete.
GET/POST /admin/support/templates List (?kind= reply, resolution or email; the response adds the placeholders catalogue) / create. Email templates: 400 UNKNOWN_PLACEHOLDER / UNSAFE_SUBJECT_PLACEHOLDER.
PUT/DELETE /admin/support/templates/:id Edit / delete. A system template keeps its key and kind and cannot be deleted (409 TEMPLATE_SYSTEM).
GET/POST /admin/support/resolution-codes List / create.
PUT /admin/support/resolution-codes/:code Edit. Codes are deactivated, never deleted.
GET /admin/support/settings {data, count, mailer_enabled, staff_inbox_default, is_super_admin}.
PUT /admin/support/settings/:key {value} → {data, changed}. 400 VALUE_OUT_OF_RANGE, 404 SETTING_NOT_FOUND. staff_notification_email, support_email and support_phone need a super admin (403 SUPER_ADMIN_REQUIRED).
GET /admin/support/emails Email log (the outbox), paged. Filters: status, ticket_id, template_key, q, page, pageSize.
POST /admin/support/emails/:id/retry Re-queue a failed or dead email → {data}; any other status is 409 EMAIL_NOT_RETRYABLE.

Support portal (/api/v1/support-desk/*)

The support portal's API (ADR 0018). Every route requires a token whose role claim is support or admin and a fresh database check that the caller still has users.is_support or users.is_admin (SupportStaffOnly); the portal obtains the token from POST /auth/support/login. Each route runs the same handler — same body, response and errors — as its /admin twin above, so only the paths are listed. Nothing here writes configuration or moves money.

Method Path Same as
GET/POST /support-desk/tickets /admin/tickets (queue / create on a customer's behalf)
POST /support-desk/tickets/export Desk only — Excel / PDF export of the queue; see below
GET/PATCH /support-desk/tickets/:id /admin/tickets/:id
PUT /support-desk/tickets/:id/status /admin/tickets/:id/status
POST /support-desk/tickets/:id/reply /admin/tickets/:id/reply
POST /support-desk/tickets/:id/resolve /admin/tickets/:id/resolve
GET /support-desk/dashboard /admin/support/dashboard
GET /support-desk/agents /admin/support/agents — admins and support agents
GET /support-desk/customers /admin/support/customers
GET /support-desk/customers/:uid/orders /admin/users/:uid/orders (the ticket order picker)
GET /support-desk/topics GET /admin/support/topics (read-only)
GET /support-desk/templates GET /admin/support/templates (read-only)
GET /support-desk/resolution-codes GET /admin/support/resolution-codes (read-only)
GET /support-desk/settings GET /admin/support/settings (read-only)

Tickets export (POST /support-desk/tickets/export)

{"format": "xlsx"|"pdf", "mode": "filtered"|"selected", "filters": {…}, "ticket_ids": [uuid, …]} → the file itself (Content-Disposition: attachment, Cache-Control: no-store; X-Export-Count and X-Export-Skipped carry the row count and how many selected ids were no longer available). Nothing is stored or exposed at a URL.

  • filtered exports every ticket matching filters (the queue's filter names: status, priority, topic, assignee, sla, grievance, needs_reply, overdue_without_notice, recent, channel, q, sort) across all pages — it runs the queue's own WHERE builder without paging. selected exports exactly ticket_ids (1–500 UUIDs, filters ignored). An id that does not exist is silently left out, so ids cannot be probed.
  • Content is a fixed summary: ticket number, subject, topic, status, priority, assigned agent, customer name, created / last updated / resolved (IST), SLA status, next SLA deadline, breach flag (Excel adds first-response and resolution targets and the grievance flag and deadline). Never the conversation, internal notes, descriptions, or customer phone or email. Absent values read N/A. Every cell is inert text (formula-leading characters are neutralised).
  • More than 5,000 matching tickets is 413 EXPORT_TOO_LARGE; a bad format, mode, filter or id is 400 VALIDATION_FAILED naming the field. Each export writes a SUPPORT_TICKETS_EXPORTED audit row (mode, format, counts — no search text).

Ticket assignment (assigned_to) accepts an admin or a support agent; anyone else is 400 ASSIGNEE_NOT_ADMIN (the code name predates the Support role).