Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 91 additions & 0 deletions src/controllers/gupshup-webhook.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import {
Body,
Controller,
HttpCode,
HttpStatus,
Logger,
Post,
Req,
} from "@nestjs/common";
import { ApiTags } from "@nestjs/swagger";
import { Request } from "express";
import { Auth } from "src/decorators/auth.decorator";
import { Public } from "src/decorators/public.decorator";
import { AuthType } from "src/enums/auth-type.enum";

@Auth(AuthType.None)
@Controller("webhook/whatsapp/gupshup")
@ApiTags("Solid Core")
export class GupshupWebhookController {
private readonly logger = new Logger(GupshupWebhookController.name);

@Public()
@Post()
@HttpCode(HttpStatus.OK)
async receiveWebhook(@Req() req: Request, @Body() body: unknown) {
const userAgent = req.headers["user-agent"] ?? null;
this.logger.log(
`Received Gupshup WhatsApp webhook${userAgent ? ` from ${userAgent}` : ""}`,
);
this.logger.debug(`Gupshup webhook payload: ${JSON.stringify(body)}`);

const statusInfo = this.extractStatusInfo(body);
if (statusInfo) {
this.logger.log(
`Gupshup delivery update: status=${statusInfo.status ?? "unknown"}, messageId=${statusInfo.messageId ?? "n/a"}, destination=${statusInfo.destination ?? "n/a"}, reason=${statusInfo.reason ?? "n/a"}`,
);
}

return {
success: true,
message: "Webhook received",
};
}

private extractStatusInfo(body: unknown): {
status?: string;
messageId?: string;
destination?: string;
reason?: string;
} | null {
if (!body || typeof body !== "object") {
return null;
}

const payload = body as Record<string, unknown>;

const status =
this.asString(payload.status) ||
this.asString(payload.messageStatus) ||
this.asString((payload.payload as Record<string, unknown>)?.status) ||
this.asString((payload.payload as Record<string, unknown>)?.type);

const messageId =
this.asString(payload.messageId) ||
this.asString(payload.id) ||
this.asString((payload.payload as Record<string, unknown>)?.id) ||
this.asString((payload.payload as Record<string, unknown>)?.messageId);

const destination =
this.asString(payload.destination) ||
this.asString(payload.phone) ||
this.asString((payload.payload as Record<string, unknown>)?.destination) ||
this.asString((payload.payload as Record<string, unknown>)?.phone);

const reason =
this.asString(payload.reason) ||
this.asString(payload.error) ||
this.asString((payload.payload as Record<string, unknown>)?.reason) ||
this.asString((payload.payload as Record<string, unknown>)?.error);

if (!status && !messageId && !destination && !reason) {
return null;
}

return { status, messageId, destination, reason };
}

private asString(value: unknown): string | undefined {
return typeof value === "string" && value.trim() ? value.trim() : undefined;
}
}
155 changes: 155 additions & 0 deletions src/controllers/meta-cloud-whatsapp-webhook.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
import {
Body,
Controller,
Get,
HttpCode,
HttpStatus,
Logger,
Post,
Query,
Res,
} from "@nestjs/common";
import { ApiTags } from "@nestjs/swagger";
import { Response } from "express";
import { Auth } from "src/decorators/auth.decorator";
import { Public } from "src/decorators/public.decorator";
import { AuthType } from "src/enums/auth-type.enum";
import { SettingService } from "src/services/setting.service";
import type { SolidCoreSetting } from "src/services/settings/default-settings-provider.service";

@Auth(AuthType.None)
@Controller("webhook/whatsapp/meta-cloud")
@ApiTags("Solid Core")
export class MetaCloudWhatsappWebhookController {
private readonly logger = new Logger(MetaCloudWhatsappWebhookController.name);

constructor(private readonly settingService: SettingService) {}

@Public()
@Get()
verifyWebhook(@Query() query: Record<string, unknown>, @Res() res: Response) {
const mode = this.resolveQueryValue(query, "hub.mode", "hub_mode", "mode");
const verifyToken = this.resolveQueryValue(
query,
"hub.verify_token",
"hub_verify_token",
"verify_token",
);
const challenge = this.resolveQueryValue(
query,
"hub.challenge",
"hub_challenge",
"challenge",
);

const configuredVerifyToken =
this.settingService.getConfigValue<SolidCoreSetting>(
"metaWhatsappWebhookVerifyToken",
) || process.env.COMMON_META_WHATSAPP_WEBHOOK_VERIFY_TOKEN;

const isVerificationCall = mode === "subscribe";
const tokenMatches =
!!configuredVerifyToken && verifyToken === configuredVerifyToken;

if (isVerificationCall && tokenMatches && challenge) {
this.logger.log("Meta Cloud WhatsApp webhook verified successfully.");
res.writeHead(HttpStatus.OK, {
"Content-Type": "text/plain",
"Content-Length": Buffer.byteLength(String(challenge)),
});
res.write(String(challenge));
return res.end();
}

this.logger.warn(
`Meta Cloud webhook verification failed. mode=${mode ?? "n/a"}, tokenMatch=${tokenMatches}`,
);

res.writeHead(HttpStatus.FORBIDDEN, { "Content-Type": "text/plain" });
return res.end("Webhook verification failed");
}

@Public()
@Post()
@HttpCode(HttpStatus.OK)
async receiveWebhook(@Body() body: unknown) {
this.logger.log("Received Meta Cloud WhatsApp webhook");
this.logger.debug(`Meta Cloud webhook payload: ${JSON.stringify(body)}`);

const statusInfo = this.extractStatusInfo(body);
if (statusInfo) {
this.logger.log(
`Meta Cloud delivery update: status=${statusInfo.status ?? "unknown"}, messageId=${statusInfo.messageId ?? "n/a"}, destination=${statusInfo.destination ?? "n/a"}, reason=${statusInfo.reason ?? "n/a"}`,
);
}

return {
success: true,
message: "Webhook received",
};
}

private extractStatusInfo(body: unknown): {
status?: string;
messageId?: string;
destination?: string;
reason?: string;
} | null {
if (!body || typeof body !== "object") {
return null;
}

const payload = body as Record<string, unknown>;
const entries = payload.entry as Array<Record<string, unknown>> | undefined;
const changes = entries?.[0]?.changes as Array<Record<string, unknown>> | undefined;
const value = changes?.[0]?.value as Record<string, unknown> | undefined;
const statuses = value?.statuses as Array<Record<string, unknown>> | undefined;
const status = statuses?.[0];

if (!status) {
return null;
}

const errors = status.errors as Array<Record<string, unknown>> | undefined;

return {
status: this.asString(status.status),
messageId: this.asString(status.id),
destination: this.asString(status.recipient_id),
reason:
this.asString(errors?.[0]?.title) || this.asString(errors?.[0]?.message),
};
}

private asString(value: unknown): string | undefined {
return typeof value === "string" && value.trim() ? value.trim() : undefined;
}

private resolveQueryValue(
query: Record<string, unknown>,
...keys: string[]
): string | undefined {
for (const key of keys) {
const directValue = this.asString(query[key]);
if (directValue) {
return directValue;
}
}

const hubRaw = query.hub;
if (hubRaw && typeof hubRaw === "object" && !Array.isArray(hubRaw)) {
const hub = hubRaw as Record<string, unknown>;
for (const key of ["mode", "verify_token", "challenge"]) {
const value = this.asString(hub[key]);
if (
value &&
keys.some((candidate) => candidate.endsWith(key) || candidate === key)
) {
return value;
}
}
}

return undefined;
}
}
65 changes: 33 additions & 32 deletions src/factories/whatsapp.factory.ts
Original file line number Diff line number Diff line change
@@ -1,42 +1,43 @@
import { Inject, Injectable, Logger } from "@nestjs/common";
import { ConfigType } from "@nestjs/config";
import { Injectable, Logger } from "@nestjs/common";
import { ModuleRef } from "@nestjs/core";
import { SolidRegistry } from "src/helpers/solid-registry";
import { IWhatsAppTransport } from "src/interfaces";
import { SettingService } from "src/services/setting.service";
import type { SolidCoreSetting } from "src/services/settings/default-settings-provider.service";

function norm(s?: string) {
return s?.trim().toLowerCase();
}

// This factory will be use to return a mail service instance, using the configured environment variables
@Injectable()
export class WhatsAppFactory {
private readonly logger = new Logger(this.constructor.name);
constructor(
private readonly moduleRef: ModuleRef, // Use the module ref to dynamically resolve the mail service
private readonly solidRegistry: SolidRegistry,
private readonly settingService: SettingService,
) { }

getWhatsappService(name: string = null): IWhatsAppTransport {
// This is the default provider
const whatsappServiceName = name || this.settingService.getConfigValue<SolidCoreSetting>("whatsappProvider");
if (!whatsappServiceName) {
throw new Error("Unable to resolve whatsapp provider")
}
const whatsappProviders = this.solidRegistry.getWhatsappProviders();

// Return the instance which matches the whatsappServiceName
if (!whatsappProviders.length) {
// throw new Error("No mail providers are registered.");
this.logger.error("No whatsapp providers are registered.");
}

const whatsappServiceProvider = whatsappProviders.find(provider => provider.name === whatsappServiceName);

return whatsappServiceProvider.instance as IWhatsAppTransport;
private readonly logger = new Logger(WhatsAppFactory.name);

constructor(
private readonly moduleRef: ModuleRef,
private readonly solidRegistry: SolidRegistry,
private readonly settingService: SettingService,
) {}

getWhatsappService(name?: string): IWhatsAppTransport {
const providerKey =
name ||
this.settingService.getConfigValue<SolidCoreSetting>("whatsappProvider");

if (!providerKey) {
throw new Error("Unable to resolve whatsapp provider");
}

const whatsappProviders = this.solidRegistry.getWhatsappProviders();

if (!whatsappProviders.length) {
throw new Error("No whatsapp providers are registered.");
}

const whatsappServiceProvider = whatsappProviders.find((provider) =>
provider.name?.toLowerCase().includes(providerKey.toLowerCase()),
);

if (!whatsappServiceProvider) {
throw new Error(`WhatsApp provider '${providerKey}' not found`);
}

}
return whatsappServiceProvider.instance as IWhatsAppTransport;
}
}
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,7 @@ export * from './services/solid-introspect.service'
export * from './services/user.service'
export * from './services/view-metadata.service'
export * from './services/whatsapp/Msg91WhatsappService' //rename
export * from './services/whatsapp/GupshupOtpWhatsappService'
export * from './services/setting.service'
export * from './services/encryption.service'
export * from './services/info.service'
Expand Down
55 changes: 49 additions & 6 deletions src/listeners/user-registration.listener.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,57 @@

import { User } from "../entities/user.entity";
import { OnEvent } from "@nestjs/event-emitter";
import { Injectable, Logger } from "@nestjs/common";
import { EventDetails, EventType } from "../interfaces";
import { WhatsAppFactory } from "src/factories/whatsapp.factory";

@Injectable()
export class UserRegistrationListener {
private logger = new Logger(UserRegistrationListener.name);
@OnEvent(EventType.USER_REGISTERED)
handleUserRegistration(event: EventDetails<User>) {
this.logger.log(`User registered with details: ${JSON.stringify(event.payload)}`);
private readonly logger = new Logger(UserRegistrationListener.name);

constructor(private readonly whatsAppFactory: WhatsAppFactory) {}

@OnEvent(EventType.USER_REGISTERED)
async handleUserRegistration(event: EventDetails<User>) {
this.logger.log(`User registered with details: ${JSON.stringify(event.payload)}`);

const notifyTo = process.env.WHATSAPP_EVENT_NOTIFY_TO;
if (!notifyTo) {
this.logger.debug("WHATSAPP_EVENT_NOTIFY_TO not set. Skipping registration WhatsApp notification.");
return;
}

try {
const whatsappService = this.whatsAppFactory.getWhatsappService();
const username = event.payload?.username || "User";
const userId = event.payload?.id || "N/A";

await whatsappService.sendWhatsAppMessage(
notifyTo,
"registration_event",
{
payload: {
channel: "whatsapp",
source: process.env.COMMON_GUPSHUP_WHATSAPP_SOURCE,
destination: notifyTo,
"src.name": process.env.COMMON_GUPSHUP_APP_NAME || "solidx",
message: {
type: "text",
text: `New user registered: ${username} (id: ${userId})`,
},
},
},
);

this.logger.log(`Sent registration WhatsApp notification to ${notifyTo}`);
} catch (error: any) {
const status = error?.response?.status;
const responseData = error?.response?.data;
const errorMessage = error?.message;
const stack = error?.stack;

this.logger.error(
`Failed to send registration WhatsApp notification to ${notifyTo}. status=${status ?? "unknown"}, response=${typeof responseData === "object" ? JSON.stringify(responseData) : responseData}, message=${errorMessage}, stack=${stack}`,
);
}
}
}
}
Loading