1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* Simple, free webhook to start using WhatsApp Platform.
* Handles GET request for verification, and POST request for notifications.
* Meta example: https://glitch.com/edit/#!/whatsapp-cloud-api-echo-bot
*
* Setup:
* 1. Make sure your val name, and thus the val generated HTTP endpoint does not have underscores.
* Underscores present in the endpoint may error out the verification step.
* 2. Set your env variable `WHATSAPP_WEBHOOK_VERIFY_TOKEN`
* Set env variables in val: https://docs.val.town/reference/environment-variables/
* hub.verify_token value: https://developers.facebook.com/docs/graph-api/webhooks/getting-started
*
* Note:
* - As of Mar 2024, Retool webhooks don't support GET requests. So we use val.
*/
export default async function(req: Request): Promise<Response> {
// HANDLE GET REQUEST FOR 'VERIFICATION REQUESTS'
if (req.method === "GET") {
const url = new URL(req.url);
const mode = url.searchParams.get("hub.mode");
const token = url.searchParams.get("hub.verify_token");
const challenge = url.searchParams.get("hub.challenge");
// Check the mode and token are sent correctly
// Return challenge to Meta to complete verification
if (mode === "subscribe" && token === Deno.env.get("WHATSAPP_WEBHOOK_VERIFY_TOKEN")) {
return new Response(challenge, { status: 200 });
}
return Response.json({ error: "Invalid verify token" }, { status: 403 });
}
// HANDLE POST REQUEST
if (req.method === "POST") {
return Response.json({ status: 200 });
}
// HANDLE OTHER REQUEST METHODS
return Response.json({ error: "Method Not Allowed" }, { status: 405 });
}