0

I tried but it's still showing this error Missing required parameter To in the post body I was TO data also. but it showing same error how to fix this issue.

Twilio Code

import axios from 'axios'
import qs from 'qs';
import * as Twilio from 'twilio';

export function sendOtpForValidUser(user_phone_number: string){

const data = JSON.stringify({
    "To":user_phone_number,
    "Channel":'sms'
})
console.log(data)
return axios.post(`https://verify.twilio.com/v2/Services/${serviceid}/Verifications`, data, {
    headers: {
        'Authorization': 'Basic ' + Buffer.from(accountSid + ':' + authToken).toString('base64'),
        'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
    },
}).then(message => {
    console.log('Message', message.status)
    var status = message.status
    return status
})
    .catch(error => {
        console.log(error)
        var status = error.data
        return status
    })


}

Error

{
      code: 20001,
      message: 'Missing required parameter To in the post body',
      more_info: 'https://www.twilio.com/docs/errors/20001',
      status: 400
    }

How to fix this Issue. I changed data this format qs.stringify(), JSON.stringfy() but it's same error

2 Answers2

1

Twilio developer evangelist here.

You're including the Twilio Node library here, but not using it. You don't have to use axios to build up this API call when you already include Twilio. You can send a new verification like this:

import * as Twilio from 'twilio';

const client = Twilio(accountSid, authToken);

export function sendOtpForValidUser(userPhoneNumber: string){
  return client.verify.services(serviceSid).verifications.create({
    to: userPhoneNumber,
    channel: 'sms'
  })
  .then(message => {
    console.log('Message', message.status)
    var status = message.status
    return status
  }) 
  .catch(error => {
    console.log(error)
    var status = error.data
    return status
  });
}
philnash
  • 70,667
  • 10
  • 60
  • 88
0

This worked for me when trying to do similar with Twilio Notify API (but using Node-Fetch instead of Axios).

const fetch = require('node-fetch');

const params = new URLSearchParams();
params.append('Body', 'Hello from Node-Fetch - It Works!');
params.append('ToBinding', '{ "binding_type": "sms", "address": "+1407xxxxxx" }');
params.append('ToBinding', '{ "binding_type": "sms", "address": "+1601xxxxxx" }');

let headers = {Authorization: 'Basic ' + new Buffer.from(process.env.TWILIO_ACCOUNT_SID + ":" + process.env.TWILIO_AUTH_TOKEN).toString("base64")};

console.log(`To String Output: ${params.toString()}`);

fetch('https://notify.twilio.com/v1/Services/ISxxxx/Notifications',
    {method: 'POST', headers: headers, body: params})
    .then(res => res.json())
    .then(json => console.log(json))
    .catch(err => console.log(err))
Alan
  • 10,465
  • 2
  • 8
  • 9