add whatsapp modules
This commit is contained in:
5
src/common/errors/whatsapp.error.ts
Normal file
5
src/common/errors/whatsapp.error.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
export class WhatsAppError extends Error {
|
||||
public constructor(message: string) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export abstract class AbstractWhatsAppService {
|
||||
public abstract sendMessage(to: string, message: string): Promise<void>;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { WhatsAppError } from "@/common/errors/whatsapp.error";
|
||||
import { AbstractWhatsAppService } from "@/common/services/whatsapp-service/abstract.whatsapp-service";
|
||||
import { whatsAppBusinessConfig } from "@/configs/whatsapp-business.config";
|
||||
|
||||
export class MetaWhatsAppService extends AbstractWhatsAppService {
|
||||
public async sendMessage(to: string, message: string): Promise<void> {
|
||||
const response = await fetch(
|
||||
`https://graph.facebook.com/v22.0/${whatsAppBusinessConfig.phoneNumberId}/messages`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${whatsAppBusinessConfig.accessToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
messaging_product: "whatsapp",
|
||||
to,
|
||||
type: "text",
|
||||
text: { body: message },
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
console.error(await response.json());
|
||||
throw new WhatsAppError("Failed to send WhatsApp message");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,8 @@
|
||||
export function generateRandomCode(length: number): string {
|
||||
const numbers = "0123456789";
|
||||
|
||||
export function generateRandomCode(length: number, characters: string): string {
|
||||
let result = "";
|
||||
for (let i = 0; i < length; i++) {
|
||||
const randomIndex = Math.floor(Math.random() * numbers.length);
|
||||
result += numbers[randomIndex];
|
||||
const randomIndex = Math.floor(Math.random() * characters.length);
|
||||
result += characters[randomIndex];
|
||||
}
|
||||
|
||||
return result;
|
||||
|
||||
Reference in New Issue
Block a user