0

Send Template Message

by
Published today

Send a pre-approved template message to a WhatsApp user. Templates are required to start conversations outside the 24-hour customer service window.

Script whatsapp_business Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 5 hours ago
1
//native
2

3
export type DynSelect_template_name = string
4

5
// Resolver: lists the WABA's approved message templates for the dropdown.
6
export async function template_name(auth: RT.WhatsappBusiness) {
7
  const apiVersion = auth.api_version || "v25.0"
8
  const r = await fetch(
9
    `https://graph.facebook.com/${apiVersion}/${auth.business_account_id}/message_templates?fields=name,language,status&limit=100`,
10
    {
11
      headers: {
12
        Authorization: `Bearer ${auth.token}`,
13
        Accept: "application/json",
14
      },
15
    }
16
  )
17
  const { data } = (await r.json()) as {
18
    data: { name: string; language: string; status: string }[]
19
  }
20
  return (data ?? []).map((t) => ({
21
    value: t.name,
22
    label: `${t.name} (${t.language}, ${t.status})`,
23
  }))
24
}
25

26
/**
27
 * Send Template Message
28
 * Send a pre-approved template message to a WhatsApp user. Templates are required to start conversations outside the 24-hour customer service window.
29
 */
30
export async function main(
31
  auth: RT.WhatsappBusiness,
32
  to: string,
33
  template_name: DynSelect_template_name,
34
  language: string,
35
  components: { [key: string]: any }[] | undefined
36
) {
37
  const apiVersion = auth.api_version || "v25.0"
38
  const url = new URL(
39
    `https://graph.facebook.com/${apiVersion}/${auth.phone_number_id}/messages`
40
  )
41

42
  const template: { [key: string]: any } = {
43
    name: template_name,
44
    language: { code: language },
45
  }
46
  if (components !== undefined && components.length > 0) {
47
    template.components = components
48
  }
49

50
  const response = await fetch(url, {
51
    method: "POST",
52
    headers: {
53
      Authorization: `Bearer ${auth.token}`,
54
      "Content-Type": "application/json",
55
      Accept: "application/json",
56
    },
57
    body: JSON.stringify({
58
      messaging_product: "whatsapp",
59
      recipient_type: "individual",
60
      to,
61
      type: "template",
62
      template,
63
    }),
64
  })
65

66
  if (!response.ok) {
67
    throw new Error(`${response.status} ${await response.text()}`)
68
  }
69

70
  return await response.json()
71
}
72