DEV Community

Saikrishna T Bijil
Saikrishna T Bijil

Posted on

Sending messages through WhatsApp cloud API using Javascript

In this article we are going to send a WhatsApp message using the cloud api in javascript
So Meta has an API for sending and receiving WhatsApp messages, It is called WhatsApp Business Platform. Which has a cloud api, Which we are going to use.

  1. Log In with a facebook account or Create a account in developers.facebook.com
  2. Go, to my apps section in the website. And create a new app. Make sure to select other in the setup Image of facebook developers whatsapp cloud api dashboard
  3. After complete setup of the app go to the dashboard of your app and scroll down to the add product section Image of facebook developers whatsapp cloud api dashboard Then click on and set for the product WhatsApp.
  4. After that you should make a Meta Business Account or if you already have one choose it. Image of facebook developers whatsapp cloud api dashboard After choosing hit continue,
  5. Now go to the sidebar under Products -> WhatsApp click on Getting Started. Then under Send and receive messages add a "To phone number", Now you can only send messages to verified phone numbers from a test phone number. If you want you can add your phone number so that you can send messages to any phone number(no need for verifying the phone numbers to send messages). Image of facebook developers whatsapp cloud api dashboard Image of facebook developers whatsapp cloud api dashboard Now choose a test phone number and hit send message and the message will be sent. Image of facebook developers whatsapp cloud api dashboard

Now as we have done all the account relates stuffs now lets send a message using Java Script

  1. Lets make the curl request into a fetch request
fetch('https://graph.facebook.com/v16.0/19929109201920/messages', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer EAALL7G3gE4IBAK6BD49qQLyGgPZB3gz9UQgHyJ8JlZBxNqzA1LpGDlfRdKZAzu6lQ',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    messaging_product: 'whatsapp',
    to: '911234567890',
    type: 'template',
    template: {
      name: 'hello_world',
      language: {
        code: 'en_US'
      }
    }
  })
})
.then(response => {
  console.log(response)
})
.catch(error => {
  console.error(error)
})
Enter fullscreen mode Exit fullscreen mode

Replace the Authorization, fetch url and "to phone number" with yours. You can find the url and the Authorization in the getting started page.

Image of facebook developers whatsapp cloud api dashboard

*Keep in mind that the Authorization key will update every 24 hours.*

Now basically we are sending messages using the hello_world template you can setup your own templates if you want to by going to the WhatsApp manager

Image of facebook developers whatsapp cloud api dashboard

Top comments (0)