External Providers / Comms & Telephony

Communications, Telephony & AI

Every SMS/email/WhatsApp delivery provider, telephony and AI-voice integration, chatbot, marketing/affiliate vendor, and the AWS infrastructure underneath them — with real endpoint URLs, internal triggers, and credential resolution, grep-verified against los-backend.

Ground truth as of 2026-10-01 — research pass D of 4, grep-verified endpoint URLs and file paths
Corrections to earlier assumptions 1. WhatsApp delivery. AiSensy is the only registered WhatsApp delivery provider in the generic communication layer (src/core/communication/communication.module.ts wires exactly one WhatsAppProvider: AisensyProvider). Gupshup's registered provider is SMS-only — it has no WhatsApp code path at all — and there is no "Meta WhatsApp Cloud" provider in the generic WhatsAppService fallback chain. Meta's Cloud API (graph.facebook.com) is used in this codebase, but only inside the separate, bespoke WhatsApp Flows feature (src/external/flows), which bypasses WhatsAppService/AisensyProvider entirely.

2. "WhatsApp CRM" staff inbox. The staff WhatsApp-inbox feature described in some earlier docs does not exist in this codebase's src/ — only unused Prisma schema (whatsapp_crm_enabled on Brand, plus whatsapp_conversations/whatsapp_messages/whatsapp_sender_accounts/whatsapp_templates models) with zero references anywhere in TypeScript source. src/app/partner/crm-chatbot — the directory an earlier brief pointed at — is a completely unrelated AI-assistant proxy, not a WhatsApp feature; the name match is coincidental.

3. Web chatbot model. The web chatbot widget (src/external/chatbot) uses plain OpenAI — new OpenAI({ apiKey: process.env.OPENAI_API_KEY }), default model gpt-4o-mini, resolving to api.openai.com — not Azure OpenAI, despite a stale doc comment above callOpenAI() claiming otherwise.

01 OTP Verification — Internal Layer

Not an external vendor — these services persist OTP state and rate-limit, then hand off the actual send to the SMS/email providers documented below.

OtpVerificationService / OtpAttemptLimiter

OtpVerificationService (src/shared/otpVerification/otp-verification.service.ts) is a thin Prisma wrapper around UserOtpVerification: createOtp() inserts a row (userId, otpCode, type, expiresAt), verifyOtp() checks code/expiry/isUsed and flips isEmailVerified/isPhoneVerified on the user, and checkOtpLimit() enforces a 30-second cooldown plus a 5-per-10-minutes cap purely via DB queries (no Redis).

OtpAttemptLimiter (otp-attempt-limiter.service.ts) is a separate, Redis-backed failed-verification lockout (not send-rate limiting): 5 failed attempts within a 15-minute window locks the (scope, subject) pair for 15 minutes (otp:fail:* / otp:lock:* Redis keys). It degrades gracefully — logs and allows — if Redis is unavailable.

Handoff to delivery: OtpVerificationService itself never calls a provider — it only persists state. The actual send happens in the caller, e.g. src/features/auth/services/web.auth.service.ts: sendPhone() generates the OTP, calls otpVerificationService.createOtp(...), then this.smsService.sendSms({ text, to, otp, brandId }); sendEmail() renders an EJS template and calls this.emailService.sendEmail({ to, subject, html }) — deliberately without a brandId, so brand-admin CC/BCC rows never see a credential-bearing OTP email.

UAT/test bypass: if brand.isUATServices or the phone is the fixed +918888899999 test number, the OTP is fixed at "123456" and no SMS is actually sent (just logged). No WhatsApp OTP path exists in this generic flow — OTP delivery is SMS or email only here.

ComplaintOtpService (grievance / whistleblower forms)

Files: src/shared/complaintOtp/complaint-otp.service.ts, complaint-otp.constants.ts, complaint-otp.module.ts. Same generate/verify/rate-limit pattern as above but keyed by (module, referenceId) against the ComplaintOtpVerification table — shared by every public complaint-style form rather than FK'd to one parent. Uses OtpAttemptLimiter for post-verification lockout and its own DB-count-based assertSendRateAllowed() (COMPLAINT_OTP_MAX_SENDS_PER_WINDOW per COMPLAINT_OTP_SEND_WINDOW_SECONDS) for send throttling.

Handoff to delivery: callers are src/features/whistleblower/whistleblower.service.ts and src/features/grievance/grievance.service.ts. Both send the OTP email via a dedicated SMTP mailbox (src/shared/smtpMailer), explicitly bypassing the general EmailService/provider chain documented below — intentional, so these public-form emails don't flow through the brand-recipient-CC logic or vendor APIs used for transactional mail.

ServiceBacking storeRate limitingDelivery path
OtpVerificationServiceUserOtpVerification (Postgres)DB-based: 30s cooldown, 5 / 10 minSmsService / EmailService fallback chains
OtpAttemptLimiterRedis5 failed attempts / 15 min → 15 min lockn/a (verification lockout only)
ComplaintOtpServiceComplaintOtpVerification (Postgres)DB-based, configurable window/capDedicated SMTP mailbox (smtpMailer) — bypasses EmailService

02 SMS Delivery Providers

All live under src/core/communication/providers/sms/, implement SmsProvider.sendSms(message): Promise<boolean>, and are orchestrated by SmsService.

Msg91 SMS

Primary/default transactional SMS (OTP, template-based) provider for most brands.

  • POST {MSG91_URL}/api/v5/flow — sends a templated SMS (template_id, recipients[] with per-template variable mapping, short_url: "0")
Modulesrc/core/communication/providers/sms/msg91.provider.ts TriggerCalled by SmsService.sendSms() (src/core/communication/services/sms.service.ts), invoked wherever OTP/transactional SMS is needed (e.g. WebAuthService.sendPhone()). AuthResolved per-brand via BrandProviderKeyReader.resolve(brandId, "SMS", "MSG91", [...]): MSG91_TEMPLATE_ID, MSG91_AUTH_KEY, MSG91_URL (header authkey). WebhookNone.
Notes: Has a hardcoded TEMPLATE_VARIABLE_MAP keyed by literal Mongo-style template IDs ("68272f93d6fc0543812ce422", "699daaa025d6de279a07e2f2") mapping to different variable shapes (var1/var2/mobiles vs mobiles/numeric); unknown template IDs fall back to a generic {mobiles, var1, var2, numeric} payload with a console warning.
Gupshup SMS

Alternate transactional SMS provider; sends a hardcoded OTP message text (not template-based like the others). SMS only — see correction #1 above; no WhatsApp code path exists here.

  • POST {GUPSHUP_URL} — form-urlencoded, method=sendMessage; plain SMS send via Gupshup's legacy SMS gateway API (auth_scheme=PLAIN, format=JSON, v=1.1)
Modulesrc/core/communication/providers/sms/gupshup.provider.ts TriggerSmsService.sendSms() fallback chain. Authprocess.env.GUPSHUP_USER_ID, GUPSHUP_PASSWORD, GUPSHUP_URL; message body also references BRAND_NAME/BRAND_EMAIL env vars — not brand-scoped via BrandProviderKeyReader, unlike the others. WebhookNone.
Notes: Message text is hardcoded to reference "jhatpatcash" regardless of actual brand — looks like leftover single-tenant code. Strips a leading +91 before sending.
NimbusIT SMS

Transactional SMS provider with per-brand hardcoded message templates — an if/else if chain keyed on the resolved NIMBUSIT_BRAND config value (18+ brand names: Paisapop, MinutesLoan, ZeptoFinance, Salary4Sure, FastRupees, FastSalary, SalaryBolt, jhatpatcash→"Crednidhi", Subhlakshmi, ToofanLoan, SwiftPaisa, Expressoloan, EazyPaisa, MySalaryLoan, RupeeRaftaar, UrjaPe, DezireLoan, LoanInSeconds, Thecredbuddy, InstantFundz, DhanPocket, DhaniLoans, Credmyloan, Credbulls).

  • GET http://nimbusit.net/api/pushsms?user=...&authkey=...&sender=...&mobile=...&text=...&entityid=...&templateid=...&rpt=1 — fires via plain fetch(), not the injected HttpService
Modulesrc/core/communication/providers/sms/nimbusit-sms.provider.ts TriggerSmsService.sendSms() fallback chain. AuthPer-brand via BrandProviderKeyReader.resolve(brandId, "SMS", "NIMBUSIT", [...]): NIMBUSIT_USER, NIMBUSIT_AUTH_KEY, NIMBUSIT_SENDER, NIMBUSIT_ENTITY_ID, NIMBUSIT_TEMPLATE_ID, NIMBUSIT_BRAND, NIMBUSIT_EMAIL. WebhookNone.
Notes: No brand/NIMBUSIT_BRAND match in the if-chain → logs an error and returns false (no send). Uses plain http:// (not https) for the Nimbusit API. The URL-building is unusually duplicated per brand instead of parameterized.
SMSGatewayHub SMS

Alternate/template-based transactional SMS provider. (Filename itself has a typo: smsgatewayhub.provicer.ts.)

  • POST https://www.smsgatewayhub.com/api/mt/SendSMS?APIKey=...&senderid=...&channel=...&DCS=...&flashsms=...&number=...&text=...&route=...
Modulesrc/core/communication/providers/sms/smsgatewayhub.provicer.ts TriggerSmsService.sendSms() fallback chain. AuthPer-brand via BrandProviderKeyReader.resolve(brandId, "SMS", "SMSGATEWAYHUB", [...]): SMS_GETEWAY_HUB_API_KEY, SMS_GETEWAY_HUB_SENDER_ID, SMS_GETEWAY_HUB_CHANNEL (default "2"), SMS_GETEWAY_HUB_DCS (default "0"), SMS_GETEWAY_HUB_FLASHSMS (default "0"), SMS_GETEWAY_HUB_ROUTE (default "1"), SMS_GETEWAY_HUB_TEMPLATE (text template with a literal {{OTP}} placeholder substituted with message.text). WebhookNone.
Notes: Success is ErrorCode === "000" && ErrorMessage === "Success". The env var name typo (GETEWAY not GATEWAY) is baked into production config — must be preserved exactly when setting env vars.
TrustSignal (SMS) SMS

Alternate transactional SMS provider; defaults to a hardcoded "SpeedoLoan" OTP message if no TRUSTSIGNAL_MESSAGE_TEMPLATE is configured.

  • GET {TRUSTSIGNAL_URL}?sender_id=...&to=...&route=transactional&message=...&api_key=...&template_id=... — default base https://sms.trustsignal.io/v1/sms
Modulesrc/core/communication/providers/sms/trustsignal.provider.ts TriggerSmsService.sendSms() fallback chain. AuthPlain process.env: TRUSTSIGNAL_API_KEY, TRUSTSIGNAL_SENDER_ID, TRUSTSIGNAL_TEMPLATE_ID, TRUSTSIGNAL_URL (optional override), TRUSTSIGNAL_MESSAGE_TEMPLATE (optional, {#var#} OTP placeholder). Not brand-scoped via BrandProviderKeyReader, unlike its email counterpart. WebhookNone.
Notes: Success check is lenient — any 200 response, or status === "success", or type === "success" counts as success.

03 Email Delivery Providers

All live under src/core/communication/providers/email/, implement EmailProvider.sendEmail(message): Promise<boolean>, orchestrated by EmailService.

Brevo Email

Primary/default transactional email provider (first in the fallback chain alongside brand overrides).

  • POST https://api.brevo.com/v3/smtp/email — full email send (to/cc/bcc, html/text, attachments as base64)
Modulesrc/core/communication/providers/email/brevo-email.provider.ts TriggerEmailService.sendEmail() fallback chain. AuthPer-brand via BrandProviderKeyReader.resolve(brandId, "EMAIL", "BREVO", ["BREVO_API_KEY"]), header api-key. Constructor also throws at boot if process.env.BREVO_API_KEY (the deployment default) is entirely unset. WebhookNone found in this module.
Notes: Attachments sent as {name, content (base64), mime_type}. Sender name/address come from EmailConfigService (EMAIL_FROM_NAME/EMAIL_FROM_ADDRESS), shared by all 4 email providers.
Resend Email

Alternate transactional email provider, uses the official resend npm SDK rather than raw HTTP.

  • SDK this.resend.emails.send(...) — wraps Resend's https://api.resend.com/emails internally; no literal URL in this file since the SDK handles it
Modulesrc/core/communication/providers/email/resend-email.provider.ts TriggerEmailService.sendEmail() fallback chain. Authprocess.env.RESEND_API_KEY (constructor throws if unset) — not brand-scoped via BrandProviderKeyReader, unlike Brevo. WebhookNone in this module.
Notes: Attachments passed as Buffer/base64-decoded content directly to the SDK.
Amazon SES Email · AWS

Alternate transactional email provider using AWS SES directly via aws-sdk.

  • SDK ses.sendEmail(...) — plain messages, via the AWS SDK's SES client (no literal HTTPS URL)
  • SDK ses.sendRawEmail(...) — hand-built MIME multipart/mixed message, used when attachments are present
Modulesrc/core/communication/providers/email/ses-email.provider.ts TriggerEmailService.sendEmail() fallback chain. Authprocess.env.SES_AWS_REGION (falls back to AWS_REGION), SES_AWS_ACCESS_KEY_ID/SES_AWS_SECRET_ACCESS_KEY (fall back to generic AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY, or IAM role if both unset). Constructor throws if no region resolvable. WebhookNone in this module.
Notes: Only provider that hand-builds a raw RFC 2045 MIME message (boundary markers, base64-wrapped attachments) — needed because SES's structured API doesn't support attachments directly. BCC is deliberately omitted from the MIME header but included in Destinations so SES still delivers it without exposing it on the visible header.
TrustSignal (Email) Email

Alternate/template-based transactional email provider — a separate TrustSignal product/endpoint from its SMS sibling above.

  • POST {TRUSTSIGNAL_EMAIL_URL}?api_key=... — default https://eapi.trustsignal.io/v1/otp-email; body {to, from, template_id, subject, evariables}
Modulesrc/core/communication/providers/email/trustsignal-email.provider.ts TriggerEmailService.sendEmail() fallback chain. Authprocess.env.TRUSTSIGNAL_EMAIL_API_KEY, TRUSTSIGNAL_EMAIL_TEMPLATE_ID, TRUSTSIGNAL_EMAIL_URL (optional override). Not brand-scoped. WebhookNone.
Notes: Template-driven ("otp-email" in the URL path) — only sends to/subject/template_id/evariables (JSON-stringified message.variables), does not accept arbitrary HTML like the other three.

04 WhatsApp Delivery

The generic WhatsAppService abstraction has exactly one registered provider.

AiSensy WhatsApp

The sole registered direct WhatsApp message delivery provider for the generic WhatsAppService abstraction (template-based campaign sends, e.g. reminders).

  • POST {AISENSY_BASE_URL}/campaign/t1/api/v2 — body {apiKey, campaignName, destination, userName, templateParams, media, source}
Modulesrc/core/communication/providers/whatsapp/aisensey.provider.ts (filename aisensey, class AisensyProvider) TriggerWhatsAppService.sendWhatsAppMessage() (src/core/communication/services/whatsapp.service.ts); found as the sole provider used by src/core/workers/reminder-worker.service.ts for WhatsApp reminder delivery. Authprocess.env.AISENSY_API_KEY, AISENSY_BASE_URL. Constructor validates AISENSY_BASE_URL is https:// and its hostname is in an allowlist (backend.aisensy.com, api.aisensy.com) — throws otherwise. WebhookNone in this module.
Notes: Phone formatting auto-prepends 91 for bare 10-digit numbers. If AISENSY_API_KEY/AISENSY_BASE_URL are unset, isConfigured=false and the provider is excluded from WHATSAPP_PROVIDERS at module wiring time (communication.module.ts — if (aisensy?.name) providers.push(aisensy)).

05 Provider Selection & Fallback

communication.module.ts, sms.service.ts, email.service.ts, whatsapp.service.ts, email-config.service.ts — identical selection shape across all three channels.

process.env.SMS_PROVIDER / EMAIL_PROVIDER / WHATSAPP_PROVIDER (case-insensitive) — if set and matching a known key, only that provider is used, with no fallback. Otherwise, all providers run in a hardcoded priority order and the first one whose send*() call returns true wins:

ChannelPriority order
SMSmsg91 → smsgatewayhub → nimbusit → gupshup → trustsignal
Emailbrevo → ses → resend → trustsignal
WhatsAppaisensy only (if configured)

SmsService/WhatsAppService are simple loops; EmailService additionally merges brand-configured admin CC/BCC/PRIMARY recipients (brand_email_recipients table, matched by brand_id + email_type, or NULL = "all types") before sending, and validates all addresses — dropping invalid CC/BCC without failing the send, but hard-failing on an invalid primary to.

A message without brandId skips the brand-recipient merge entirely — this is how OTP/credential-bearing emails deliberately avoid being CC'd/BCC'd to brand admin mailboxes (see the comment in WebAuthService.sendEmail()). CC/BCC-only sends (no to) address the envelope to to the configured EMAIL_FROM_ADDRESS so the real recipients keep their CC/BCC visibility semantics. HttpModule for this module is configured with a 10-second timeout and max 1 redirect, shared by every HTTP-based SMS/email provider above.

06 WhatsApp-Specific Feature Integrations

Separate from the plain delivery layer above — these call Meta's Graph API directly, or (in one case) have nothing to do with WhatsApp at all despite the directory name.

Meta WhatsApp Flows WhatsApp · Meta Graph API

A full loan-application journey conducted entirely inside a WhatsApp conversation using Meta's native "Flows" UI (forms rendered in-chat) — greeting → flow invite → encrypted flow data exchange → bank-account/Aadhaar/AA-consent follow-up templates.

  • GET https://graph.facebook.com — webhook verification handshake (inbound; Meta calls us)
  • POST https://graph.facebook.com/v21.0/{PHONE_NUMBER_ID}/messages — sends template messages (sendLoanJourneyTemplate, sendAAConsentTemplate, sendBankAccountTemplate, sendAadhaarTemplate, sendLoanApplicationTemplate) and plain text (sendTextMessage), via WhatsAppTemplateService
  • POST https://graph.facebook.com/v21.0/{PHONE_NUMBER_ID}/messages — same endpoint, called again directly from webhook.service.ts (~lines 83, 297, 405) for its own outbound replies within the webhook-handling flow
Modulesrc/external/flows/flows.controller.ts, flows.module.ts, src/external/flows/service/{flows,encryption,webhook,whatsapp-template,initial-details,bank-account,loan-application}.service.ts TriggerGET /flows (webhook verification, public) and POST /flows (v1, public) in FlowsController — Meta posts both ordinary WhatsApp Business Account webhook events and encrypted flow data-exchange requests to the same route. handleFlowRequest() branches on action: ping, INIT, data_exchange, BACK, else handleUnknownAction. Authprocess.env.WHATSAPP_ACCESS_TOKEN, PHONE_NUMBER_ID, WEBHOOK_VERIFY_TOKEN (matched against Meta's hub.verify_token on the GET handshake). WebhookGET /flows (verification handshake) and POST /flows v1 (@Version("1"), combined webhook + flow-data-exchange endpoint), both @AuthType("public").
Notes: EncryptionService decrypts inbound flow payloads with RSA-OAEP (SHA-256) using a private key loaded from PRIVATE_KEY_PATH (+ optional PRIVATE_KEY_PASSPHRASE) to recover an AES key, then AES-128-GCM-decrypts the flow data (16-byte auth tag split off the tail of the base64 blob). Responses are AES-128-GCM-encrypted back using the same session AES key, with the initialization vector bit-flipped (XOR 0xFF) per Meta's Flows spec before re-encrypting. If PRIVATE_KEY_PATH is unset or the file is missing/unreadable, privateKey is empty and decryptRequest() throws immediately. Session/phone-number correlation uses Redis (whatsapp:session:{flowToken}, 24h TTL) so flow-data-exchange round trips (which carry only a flow_token, not the phone number) can be matched back to the user mid-conversation. Flow completion (nfm_reply with flow_token starting LOAN_APP_ or LOAN_JOURNEY_) branches to webhookService.handleLoanApplicationSubmission() or handleFlowCompletion() respectively.
crm-chatbot (Central Chatbot proxy) AI/Chatbot Not WhatsApp

Lets partner staff ask an AI assistant questions inside the partner CRM console; this NestJS backend does not run any AI/LLM logic for it — it's a pure proxy to a separate microservice. Despite living in a directory suggestive of "WhatsApp CRM," this feature is completely unrelated to WhatsApp — see correction #2 above. The "crm-chatbot" name is a coincidence.

  • POST {CENTRAL_CHATBOT_URL}/chatbot/chat — forwards {query, brandId, brandName, partnerUserId, partnerUserEmail, partnerUserName}, header x-api-key: {CENTRAL_CHATBOT_API_KEY}
  • GET {CENTRAL_CHATBOT_URL}/chatbot/brand/{brandId}/partner/{partnerUserId}/sessions/{sessionId}/chat — fetches session history
Modulesrc/app/partner/crm-chatbot/crm-chatbot.controller.ts, crm-chatbot.service.ts, crm-chatbot.module.ts TriggerPOST /partner/brand/:brandId/chatbot/chat (AuthType('partner')) and GET /partner/brand/:brandId/chatbot/sessions/:sessionId in CrmChatbotController. Authprocess.env.CENTRAL_CHATBOT_URL, CENTRAL_CHATBOT_API_KEY. WebhookNone.
Notes: This is the directory an earlier brief pointed to for "WhatsApp CRM" — it is unrelated to WhatsApp. No whatsapp_crm_enabled toggle, unread-count endpoint, or WhatsApp conversation/message code exists anywhere in src/, despite matching Prisma schema models existing unused (see correction #2). If a WhatsApp staff-inbox feature exists, it is not yet implemented in this backend.
Web Chatbot (OpenAI) AI/Chatbot

A rule/step-driven conversational widget for the public marketing/loan site (general, apply-loan, track-application, calculate-emi, check-eligibility steps), using an LLM only for intent classification (deciding which step/flow a free-text user message maps to), not for general open-ended chat generation. Uses plain OpenAI, not Azure — see correction #3 above.

  • SDK this.client.chat.completions.create(...) — OpenAI Chat Completions via the openai npm SDK, default model gpt-4o-mini (overridable via process.env.OPENAI_MODEL); no custom baseURL, so this resolves to standard https://api.openai.com, not an Azure OpenAI resource endpoint
Modulesrc/external/chatbot/chatbot.controller.ts, chatbot.service.ts, chatbot-message.service.ts, chatbot.module.ts, intent/intent-classifier.service.ts, steps/*.ts TriggerPOST /web/chatbot/session (create session, AuthType("public"), ThrottlerGuard 20 req/min); GET /web/chatbot/session/:sessionId (fetch session + history, 30-min inactivity TTL, 410 Gone if expired); POST /web/chatbot/message (send message, routed through IntentClassifierService.classify()/classifyWithJourneyContext() to the OpenAI call). Authprocess.env.OPENAI_API_KEY — the module loads/initializes the client lazily in onModuleInit(); the client is constructed unconditionally with whatever apiKey value is present (including undefined) and only fails when a classification call is actually attempted. A matchDeterministicIntent()/matchDeterministicJourneyDecision() fast path must miss before OpenAI is hit at all, so many messages never need the key. WebhookNone.
Notes: ChatbotModule also imports OtpVerificationModule and CommunicationModule — track-application.step.ts uses OtpVerificationService/SMS to verify a user's identity before revealing application status inside the chat. On any OpenAI error, classify() falls back to Intent.UNKNOWN rather than throwing.

07 Telephony & Voice

Two human-agent dialer providers plus an AI voice-agent platform, all selected per-brand via the shared TelephonyDialerService.

Acefone Telephony

Click-to-call dialer connecting a partner-user telecaller to a borrower; also used for user/agent management on the Acefone PBX and inbound/outbound call-log webhooks. The implicit default telephony provider.

  • POST https://api.acefone.in/v1/click_to_call — places the agent↔customer call (async, destination_number, agent_number, caller_id)
  • GETPOSTPATCHDELETE https://api.acefone.in/v1/user[/{userId}] — Acefone PBX user/agent management (create, fetch, update, delete)
  • POST https://api.acefone.in/v1/broadcast/lead/{leadId} — broadcast-lead-based dialing
  • GET https://dialer-api.acefone.in/api — base URL constant on the service (legacy/alternate dialer-API host; not seen invoked directly in the reviewed call sites, which all hit api.acefone.in)
Modulesrc/external/acefone/acefone.controller.ts, acefone.service.ts, src/features/telephony/acefone/acefone-dialer.{service,controller,module}.ts, src/features/telephony/telephony-dialer.{service,controller}.ts TriggerPOST /telephony/dialer/initiate and /session in TelephonyDialerController (AuthType("partner")) → TelephonyDialerService.initiateCall(), which looks up the brand's primary BrandProvider (type TELEPHONY) and defaults to Acefone when no provider row exists at all. Also POST /acefone/dialer/initiate-lead in AcefoneDialerController for unconverted leads, and POST /acefone/user, GET /acefone/user in AcefoneController for PBX user management. AuthPer-brand via BrandProviderKeyReader.resolve(brandId, "TELEPHONY", "ACEFONE", ["ACEFONE_API_TOKEN"]), sent as Authorization: Bearer {token}. Per-telecaller agent number/caller ID come from partner_user_dialer_configs (keyed partner_user_id + provider=ACEFONE, columns agent_user_id/agent_allowed_caller_id). WebhookPOST /acefone/dialer/outbound and POST /acefone/dialer/inbound in AcefoneDialerController (AuthType("public")) → handleOutboundCallWebhook()/handleInboundCallWebhook(). Outbound events matched to the originating UserCall by ref_id; inbound events create a new UserCall on the fly, matching the caller's number against User.phoneNumber/alternate_phone_1/alternate_phone_2/AlternatePhoneNumber, and the answering agent against PartnerUser.phone_number (falling back to the user's currently allocated partner user).
Notes: Acefone is the implicit default — TelephonyDialerService falls back to Acefone whenever a brand has zero active BrandProvider rows of type TELEPHONY; "no configuration" means Acefone, not "no telephone." getBrandTelephonyProvider() mirrors this exactly for the console to decide whether to show a phone icon at all.
Callex Telephony

Alternate telephony provider to Acefone — an embeddable browser WebPhone (iframe) with its own login/session/token model, used when a brand's primary BrandProvider is CALLEX.

  • POST {base}/auth/userlogin — {domain, username, password} → {token}; base https://talk.callex.in:3300 (overridable via CALLEX_BASE_URL), domain defaults valoris.callex.in (overridable via CALLEX_DOMAIN)
  • POST {base}/call_originate/manual_call — {destination_number} → {crm_id, unique_id, origination_uuid, ...}
  • POST {base}/call_originate/hangup_call — {call_uuid}
  • POST {base}/call_originate/mute_unmute — {uuid, flag: "mute"|"un_mute"}
  • POST {base}/call_originate/hold_unhold — {uuid, flag: "hold"|"un_hold"}
  • GET {base}/user_login — resolves Callex's internal numeric user id for the configured username (needed because /logout requires it and login only returns a token)
  • POST {base}/logout — {user_id}
  • GET {base}/cdrs_report/get_recording_path?unique_id=...&type=0|1 — downloads a completed call recording (binary; type=1 = current table, type=0 = archive)
Modulesrc/external/callex/callex.service.ts, callex.module.ts, src/features/telephony/callex/callex-partner-user-config*.ts, callex-webhook.controller.ts, shared TelephonyDialerService TriggerSame TelephonyDialerService as Acefone, routed by brandProvider.provider === "CALLEX" — POST /telephony/dialer/initiate, /session, /lead/session, /lead/initiate, plus call-control routes POST /telephony/dialer/:callId/{end,mute,hold,sync}, GET /telephony/dialer/:callId/status, POST /telephony/dialer/callex/logout in TelephonyDialerController. AuthPer-partner-user Callex username/password, managed by CallexPartnerUserConfigService and exposed via CallexPartnerUserConfigController/CallexPartnerUserConfigsController. Access tokens cached per (brand, username) in-memory (CallexService.tokens Map) and also persisted/cached through callexPartnerUserConfigs.cacheAccessToken(). WebhookPOST /telephony/callex/webhook and alias POST /callex/webhook/handle in CallexWebhookController (AuthType("public") — no signature verification, since "Callex has not supplied a signature/authentication scheme" per the code comment). Handles ANSWER/HANGUP event types, matched to a UserCallEvent by origination_uuid/unique_id/crm_id (legacy fallback to acefone_call_id for pre-migration rows). A HANGUP with positive billsec triggers an async recording fetch via syncCallexRecording(), uploading to private S3 (AwsPrivateS3Service.uploadPrivateDocument) — only the S3 key is stored; the raw Callex recording URL is never persisted/exposed.
Notes: Recording retrieval tries type=1 (current) then falls back to type=0 (archive). Phone-number formatting is Callex-specific: 10-digit numbers are sent bare (not +91-prefixed), matching Callex's own WebPhone. syncCallexRecording is also exposed on-demand via POST /telephony/dialer/:callId/sync for the call-history UI to retry.
Sphoro Voice Telephony · AI Voice

Two related capabilities on the same platform account: (1) fully AI-dialed outbound calls where a voice agent talks to the borrower with no human on the line, and (2) a human telecaller's in-browser softphone/handset — same provider, separate product surface ("the product has a human leg now").

  • SDK @sphoro/voice Node SDK — base URL https://voice.sphoro.com (overridable per-brand via SPHORO_VOICE_BASE_URL); wraps call creation, call tokens, transcripts, agent listing, and webhook-endpoint registration — no individual literal paths are hand-coded since the SDK owns the HTTP layer
Modulesrc/external/sphoro-voice/sphoro-voice.service.ts, sphoro-voice.verifier.ts, sphoro-voice.module.ts; src/features/telephony/sphoro-voice/sphoro-voice-{bootstrap,call,handset,webhook,dialer-config}.service.ts, sphoro-voice.controller.ts, sphoro-voice-handset.controller.ts, sphoro-voice-webhook.controller.ts. Note: src/features/sphoro-voice (without the telephony/ prefix) does not exist — only src/features/telephony/sphoro-voice exists. TriggerAI-dialed calls: POST /sphoro-voice/calls (AuthType("partner"), @Roles("SUPER_ADMIN") only) → SphoroVoiceCallService.initiateCall(); also reachable via the shared dialer path when a brand's primary TELEPHONY provider is SPHORO_VOICE (TelephonyDialerService.initiateSphoroVoiceCall(), delegates to the same service so both entry points write one consistent UserCall row). Human handset: POST /sphoro-voice/handset/calls (place a call + get credential), POST /sphoro-voice/handset/calls/:id/token (join an existing/ringing call), GET /sphoro-voice/handset/ringing (SSE feed of incoming calls) — AuthType("partner"), not SUPER_ADMIN-gated. Also GET /telephony/dialer/provider?brandId=... tells the partner console which provider a brand runs. AuthSee credential tables below. WebhookPOST /webhook/sphoro-voice in SphoroVoiceWebhookController (AuthType("public")). Body received as a raw Buffer (express.raw() mount in main.ts, required because the signature covers exact wire bytes) and verified via verifySphoroVoiceSignature() against header voiceai-signature, using secret process.env.SPHORO_VOICE_WEBHOOK_SECRET — a missing secret means every delivery is rejected (401, which the platform retries and eventually auto-disables). Valid events go to SphoroVoiceWebhookService.handleEvent().

Credential split — selection vs. API credential

TableColumn(s)Purpose
brand_providerstype=TELEPHONY, provider=SPHORO_VOICESelection only — tells TelephonyDialerService to route a brand's calls to Sphoro. Same table Acefone/Callex use for selection.
brand_dialer_configs (BrandDialerConfig)provider=SPHORO_VOICE, auth_tokenAPI credential — read per-brand by SphoroVoiceService.credential(), cached per-brand for 60s (CREDENTIAL_TTL_MS). Explicitly not a single deployment-wide SPHORO_VOICE_API_KEY env var — that was removed because "one key in the environment meant one Sphoro account for a backend that serves many brands."
PartnerUserDialerConfig (partner_user_dialer_configs)agent_user_id (Sphoro platform "member id"), voice_agent_id/outbound_voice_agent_idPer-telecaller agent/member config, read via the shared helper sphoro-voice-dialer-config.ts (voiceDialerConfig()/voiceMemberId()/voiceOutboundAgentId()), used identically by both the AI-call service and the handset service to avoid drift.
Notes: This two-table split (provider selection on brand_providers vs. provider credentials on brand_dialer_configs) is specific to telephony and worth calling out for anyone extending it. The handset's /ringing SSE route fans out one upstream Sphoro connection per brand a telecaller works on into a single response stream, with a 15-second keepalive comment to defeat proxy buffering (plus an explicit X-Accel-Buffering: no header for nginx). Gating AI-dialed call initiation on SUPER_ADMIN while leaving the handset open to any partner user is deliberate — "a telephone... gating it on the highest role... means the people whose job is to make calls cannot make them."

08 Marketing & Affiliate

Meta Conversions API (CAPI) Marketing

Server-side ad-conversion event reporting to Meta (Facebook/Instagram) ad pixels, so conversions (signup, disbursal, etc.) are attributed even when client-side pixel tracking is blocked.

  • POST https://graph.facebook.com/v21.0/{META_PIXEL_ID}/events — body {data: [{event_name, event_time, event_id, action_source: "website", event_source_url, user_data (SHA-256 hashed PII: em/ph/fn/ln/external_id + fbc/fbp/client_ip/client_user_agent), custom_data}], access_token, test_event_code?}
Modulesrc/external/meta-capi/meta-capi.service.ts, meta-capi.interface.ts, meta-capi.module.ts, src/core/aws/sqs/aws-meta-capi-sqs.service.ts, src/core/workers/meta-capi-worker.service.ts TriggerEnqueued via AwsMetaCapiSqsService.sendToMetaCapiQueue() (SQS, FIFO-aware with per-user MessageGroupId) from business events; consumed and sent by meta-capi-worker.service.ts polling the queue, calling MetaCapiService.sendEvent(). Authprocess.env.META_CAPI_ENABLED (hard kill switch — both the enqueue step and the send step check it independently), META_PIXEL_ID, META_CAPI_ACCESS_TOKEN, optional META_CAPI_TEST_EVENT_CODE, SQS_META_CAPI_QUEUE_URL. WebhookNone (outbound-only reporting API).
Notes: PII (email, phone, name) is SHA-256 hashed client-side before transmission, per Meta's CAPI spec. A 200 HTTP response does not guarantee acceptance — the service explicitly logs the full response body because Meta can return events_received: 0 with rejection reasons even on a 200.
AdsPlay Marketing · Affiliate

Fires a disbursal-event postback to AdsPlay's affiliate tracking system so an AdsPlay-attributed user's loan disbursal is recorded for commission/attribution.

  • GET https://affiliates.adsplay.in/post_install_custom_event.php?clickid={clickId}&eventname=disbursal
Modulesrc/external/adsplay/adsplay.service.ts, adsplay.module.ts TriggerCalled internally by AdsplayService.notifyDisbursal(userId), invoked from src/features/payment/disbursement/disbursement-payment.service.ts and the bank-specific disbursement providers (yesbank.disbursement.service.ts, hdfc.disbursement.service.ts) once a loan is disbursed. AuthNone — the clickid itself (captured at signup time from the adsplay UTM source into UTMTracking.clickid) is the correlating token; no API key. WebhookNone (outbound-only postback).
Notes: Silently no-ops if the user has no prior adsplay-sourced UTM tracking row with a clickid — most users never trigger an actual HTTP call here.
Riskcovry Marketing · Insurance

Purchases a group personal-accident/health insurance policy for the borrower at loan disbursement and tracks its status/certificate through to download.

  • POST {RISKCOVRY_BASE_URL}/api/partner/groups/purchase — purchases the policy (Partner-Code/Partner-Key headers)
  • POST {RISKCOVRY_BASE_URL}/api/partner/policies/get_policy_status — {policy_no} → status + certificate URL
Modulesrc/external/riskcovry/external.service.ts (raw HTTP client), riskcovry.service.ts (business orchestration: purchase, status polling, certificate S3 upload, policy email), riskcovry.module.ts TriggerRiskcovryService.triggerPolicyPurchase(loanId) and checkPolicyStatus(loanId, policyNo), called from src/core/cron/services/riskcovary-insurance.service.ts (scheduled reconciliation) and from disbursement-payment.service.ts / yesbank.disbursement.service.ts / hdfc.disbursement.service.ts at disbursal time. sendPolicyEmail(loanId) sends the certificate once available. Authprocess.env.RISKCOVRY_BASE_URL, RISKCOVRY_PARTNER_CODE, RISKCOVRY_PARTNER_KEY; product config via RISKCOVRY_PACKAGE_CODE (default FINTECH_CLOUD_ACCIDENT_HEALTH), RISKCOVRY_PLAN_CODE (default RISKCOVRY_POCKET_PLAN_FINTE), RISKCOVRY_SUM_INSURED (default 50000). WebhookNone — status is polled, not pushed.
Notes: Purchase failures parse a nested reason.policy_no from the error body to detect "policy already exists" as a distinct case (existingPolicyNo). Certificates are downloaded and re-uploaded into this app's own S3 rather than linking Riskcovry's URL directly (uploadCertificateToS3).
Loanwalle Marketing · Affiliate

Inbound-only integration: Loanwalle (an external affiliate/aggregator) sends pre-qualified leads and redirects its users into our app via an encrypted auto-login token. This backend makes no outbound HTTP calls to Loanwalle — it is purely a receiver.

  • None outbound — grep for httpService/axios in loanwalle.service.ts returns no hits.
Modulesrc/external/loanwalle/loanwalle.controller.ts, loanwalle.service.ts, loanwalle.modules.ts TriggerPOST /loanwalle/leads — Loanwalle creates a lead (AuthType(['partner','credential']), gated by PermissionsEnum.LOANWALLE_API or ALL); GET /loanwalle/leads/:leadId — status lookup (despite the param name, looked up as Loan.id, a UUID); GET /loanwalle/test — credential-auth smoke test; POST /loanwalle/affiliate-login (v2, AuthType("public")) — the frontend calls this when a user lands via a Loanwalle redirect URL carrying an encrypted data query param; decrypts it and either logs the (existing, verified) user in directly or returns autofill fields for signup. Authx-api-credential header (brand-scoped, via partner_user_credentials) for the lead/status/test routes; process.env.ENCRYPTION_SECRET_KEY to decrypt the affiliate-login payload. WebhookNone distinct from the above — /loanwalle/leads itself functions as the inbound webhook/ingestion endpoint.
Notes: This is architecturally the predecessor of the generalized marketplace module below — single-provider-hardcoded rather than provider-agnostic. See the relationship note under Marketplace.
Marketplace Marketing · Affiliate

The generalized, multi-provider version of the same "aggregator onboards a user elsewhere, hands them to us pre-qualified" pattern as Loanwalle. GoCredit is the first configured provider; adding another is a registry change, not new code (per the module's own README). Also inbound-only — no outbound calls to an external marketplace API were found; the one literal external-looking URL in the service is actually our own provider-specific subdomain used to build the browser redirect.

  • None outbound to a third party found; resolveProviderSubDomain() builds https://{provider-subdomain}/auto-login?token=...&provider=... as a redirect target for the user's browser, not a server-to-server call.
  • POST /marketplace/:provider/dedupe — checks if the user already exists before the aggregator proceeds
  • POST /marketplace/:provider/lead_create — creates the lead (200 w/ leadID + jwt_access_token + redirectUrl, or 409 if it already exists)
  • POST /marketplace/:provider/status — poll lead outcome by leadId/mobile/pancard (POST, not GET, specifically to keep PII out of access logs)
  • POST /marketplace/:provider/auth — issues a session token + redirect URL
  • POST /marketplace/:provider/token-refresh — refreshes a session for a returning user
  • POST /marketplace/:provider/auto-login — v2, AuthType("public"); called by the browser landing on {provider-subdomain}/auto-login?token=...; establishes a web session with no OTP
Modulesrc/external/marketplace/marketplace.controller.ts, marketplace.service.ts, marketplace.modules.ts, registry at src/shared/brands/marketplace-subdomain.util.ts TriggerBase path /marketplace/:provider — see endpoints above. Authx-api-credential: base64(access_key:secret_key) header (brand-scoped via partner_user_credentials.brand_id) + MARKETPLACE_SSO permission (RolePermissionGuard) on every route except auto-login, which is deliberately public since the browser must never hold the partner credential — the provider-issued JWT is itself the proof. WebhookNone beyond the inbound routes above functioning as the ingestion surface.
Notes — relationship to Loanwalle: Both implement the same inbound "aggregator → dedupe/lead-create → auto-login" shape. Loanwalle is the original, hardcoded-to-one-partner implementation (no :provider param, Loanwalle-specific DTOs). Marketplace is the newer, provider-parameterized generalization (:provider path segment, provider registry, subdomain-gated enablement per MarketplaceService.resolveProviderSubDomain). They are not the same code path and are not currently merged — Loanwalle has not been migrated onto the Marketplace abstraction.

09 Cloud Infrastructure (AWS)

S3 storage, Secrets Manager, and 17 SQS queues underpin the providers above — not vendor integrations themselves, but the AWS surface every one of them runs on top of.

ServiceFilePurpose
S3 (public)src/core/aws/s3/aws-public-s3.service.tsPublicly-servable uploads (images/video/audio/docs) with an allowlist of MIME types; includes Rekognition client wiring (liveness checks out of scope for this pass).
S3 (private)src/core/aws/s3/aws-private-s3.service.tsPrivate per-user/brand documents (CIBIL reports, AA data, payslips, bank statements, loan agreements, e-stamp certs, PD photos, call recordings, etc.) — keyed brandId/userId/type/.../documentId/..., served only via short-lived presigned view URLs, never a public bucket URL.
S3 (reports)src/core/aws/s3/aws-report-s3.service.tsGenerated operational/export report files (CSV/ZIP/TXT), keyed reports/{brandId}/{date}/{reportType}/..., 24h presigned URL expiry; defaults to the private bucket if no dedicated report bucket env var is set.
Secrets Managersrc/core/aws/secrets/aws-secrets.ts, secrets-config.loader.tsPre-loads a scoped secret bundle (AWS_SECRET_NAME, default prod/los) at boot into NestJS ConfigService via fetchAndSealSecrets(); scopes: DATABASE, AUTH, PAYMENT, CREDIT_BUREAU, COMMUNICATION (incl. MSG91/Brevo/Resend/WhatsApp/AiSensy/Gupshup/SMSGatewayHub/NimbusIT keys), EXTERNAL_SERVICES, REDIS. Skippable via SKIP_AWS_SECRETS=true (local dev). A separate, deliberately-not-bundled PII crypto secret is fetched independently (PII_CRYPTO_SECRET_NAME, default los/pii-crypto).
SQS — audit logsaws-audit-logs-sqs.service.tsQueues audit-log events for async write.
SQS — auto disbursementaws-auto-disbursement-sqs.service.tsQueues automated loan-disbursement triggers.
SQS — geocodingaws-geocode-sqs.service.tsOnboarding fan-out: geocoding lookups for addresses.
SQS — leads importaws-leads-import-sqs.service.tsBulk lead-import batch processing.
SQS — leads ingestaws-leads-ingest-sqs.service.tsReal-time single-lead ingestion from external sources.
SQS — leads reallocationaws-leads-reallocation-sqs.service.tsReassigns leads between partner users/queues.
SQS — Lendbox workflowaws-lendbox-workflow-sqs.service.tsLendbox (lending-partner) workflow event queue.
SQS — loan agreementaws-loan-agreement-sqs.service.tsLoan agreement generation/e-sign pipeline events.
SQS — loan allocationaws-loan-allocation-sqs.service.tsOnboarding fan-out: loan allocation to lending partner.
SQS — loan screeningaws-loan-screening-sqs.service.tsOnboarding fan-out: loan screening/eligibility checks.
SQS — Meta CAPIaws-meta-capi-sqs.service.tsQueues Meta Conversions API events (see Marketing section above).
SQS — NOCaws-noc-sqs.service.tsNo-Objection-Certificate generation queue.
SQS — onboarding fraudaws-onboarding-fraud-sqs.service.tsOnboarding fan-out: fraud-check events on user creation.
SQS — onboarding PANaws-onboarding-pan-sqs.service.tsOnboarding fan-out: PAN verification events.
SQS — onboarding UCICaws-onboarding-ucic-sqs.service.tsOnboarding fan-out: UCIC (Unique Customer ID) dedup events.
SQS — remindersaws-remindar-sqs.service.tsRepayment/collection reminder dispatch queue.
SQS — reportsaws-report-sqs.service.tsAsync report-generation job queue.
SQS — transactional emailaws-transactional-email-sqs.service.tsQueues transactional email sends for async delivery.
SQS — underwritingaws-underwriting-sqs.service.tsOnboarding fan-out: underwriting decision events.
SQS — onboarding fan-out clientonboarding-fanout-sqs.client.tsShared base class (OnboardingFanoutSqsClient<T>) extended by the geocode/fraud/PAN/UCIC/loan-allocation/loan-screening/underwriting queue services above.
SQS — FIFO utilitysqs-fifo.util.tsShared helpers (isFifoQueueUrl, buildMessageGroupId) for per-entity message ordering on .fifo queues.