Back to APIs

Send messages, images, video with WhatsApp.

Using the WhatsApp API with Trigger.dev

You can use Trigger.dev with any existing Node SDK or even just using fetch. Using io.runTask makes your WhatsApp background job resumable and appear in our dashboard.

Use io.runTask() and the official SDK or fetch.

Use our HTTP endpoint to subscribe to webhooks

Example code using WhatsApp

Below are some working code examples of how you can use WhatsApp with Trigger.dev. These samples are open source and maintained by the community, you can copy and paste them into your own projects.

1
import { TriggerClient, eventTrigger } from "@trigger.dev/sdk";
2
import z from "zod";
3
4
// You have to need Whatsapp Business API account
5
// Get started https://developers.facebook.com/docs/whatsapp/cloud-api/get-started
6
// For Permanent token you have to create system user https://business.facebook.com/settings/system-users
7
// User need to first send message then you can send message to user via API. Only hello_world message is allowed for first message.
8
// Learn more about cloud-api https://developers.facebook.com/docs/whatsapp/cloud-api/reference
9
const endpointURL = `https://graph.facebook.com/v17.0/${process.env.WHATSAPP_PHONE_NUMBER_ID}/messages`;
10
11
// Create request options
12
const requestOptions: RequestInit = {
13
method: "POST",
14
headers: {
15
Authorization: `Bearer ${process.env.WHATSAPP_BEARER_TOKEN}`,
16
"content-type": "application/json",
17
},
18
};
19
20
client.defineJob({
21
id: "whatsapp-send-messages",
22
name: "Whatsapp Send Messages",
23
version: "1.0.0",
24
trigger: eventTrigger({
25
name: "whatsapp-send-messages",
26
schema: z.object({
27
text: z.string(),
28
to: z.string(),
29
}),
30
}),
31
run: async (payload, io, ctx) => {
32
const { text, to } = payload;
33
34
// Wrap an SDK call in io.runTask so it's resumable and displays in logs
35
await io.runTask(
36
"Whatsapp Send Messages",
37
async () => {
38
// Make request using Fetch API
39
return await fetch(endpointURL, {
40
...requestOptions,
41
body: JSON.stringify({
42
messaging_product: "whatsapp",
43
recipient_type: "individual",
44
to,
45
type: "text",
46
text: {
47
body: text,
48
},
49
}),
50
}).then((response) => response.json());
51
},
52
53
// Add metadata to the task to improve the display in the logs
54
{ name: "Whatsapp Send Messages", icon: "whatsapp" }
55
);
56
},
57
});