Karim Fayed
Karim Fayed

Reputation: 69

Connecting to WhatsApp API using axios.post using TypeScript

I just started using the WhatsApp Cloud API. I took the example that was provided on glitch as a reference but there are things that are different since I'm taking the serverless approach.

As seen in glitch's example, it used axios(config) method and I tried it out and it worked fine after minor changes but when I tried axios.post() method I keep on getting the following error:

AxiosError: Request failed with status code 400

The axios(config) method (Which works)

await axios({
                    method: "POST", // Required, HTTP method, a string, e.g. POST, GET
                    url:"https://graph.facebook.com/{{Version}}/{{Phone-Number-ID}}/messages?access_token={{Token}}",
                    data: {
                        messaging_product: "whatsapp",
                        recipient_type: "individual",
                        to: {{Recipient-Phone-Number}},
                        text: {body: "Welcome back"},
                    },
                    headers: {"Content-Type": "application/json"},
                }); 

The axios.post() method (Which doesn't works)

let url = "https://graph.facebook.com/{{Version}}/{{Phone-Number-ID}}/messages" 
let payload = {
    messaging_product: "whatsapp",
    recipient_type: "individual",
    to: {{Recipient-Phone-Number}},
    text: {body: "Welcome back my friend"},
}

let  headers = {"Content-Type": "application/json", "Authorization":"Bearer {{token}}"
}

let params = {}
try
{
    const resp = await axios.post(url, {payload}, {headers, params});

    log("POST RESP",resp)
}
catch(error)
{
    throw error;
}

Upvotes: 0

Views: 724

Answers (1)

Bishan
Bishan

Reputation: 15710

The way you have passed parameters seems incorrect; const resp = await axios.post(url, {payload}, {headers, params});.

Try this code, instead:

let url = 'https://graph.facebook.com/<Version>/<Your Phone number ID>/messages';

let payload = {
            'messaging_product': 'whatsapp',
            'recipient_type': 'individual',
            'to': '123456789012',//Recipient Phone Number
            'type': 'text',
            'text': {
                'body': 'Welcome back my friend'
            }
        };

let  headers = {
                'Authorization': 'Bearer <Your Temporary access token>',
                'Content-Type': 'application/json'
               };

  axios.post(url, payload, {
    headers: headers
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

Upvotes: 1

Related Questions