node.jstwiliosmstwilio-node

sending customParams in Twilio SMS node js


I am sending SMS to users using Twilio SMS service, in nodejs. I am using twilio npm package.

I want to send customParams while sending the sms and get those params in webhook response when it gets delivere, so that I can update my database.

For example, something like this:

customParams: {
   userId: <userid>
}

Here is my code to create the sms:

twilioClient.messages.create({
    to: USER_PHONE,
    body: smsBody,
    messagingServiceSid: MSG_SERVICE_ID,
}).then(resp => {
    console.log('SMS sent', resp)
})

Please let me know how can we possibly send sms with custom parameters.


Solution

  • To get a webhook to let you know when the message is delivered you will need to set a statusCallback URL. You can add information to that URL by assigning query string parameters.

    For example:

    const statusCallbackUrl = new URL("https://example.com/statusCallback");
    statusCallbackUrl.searchParams.append("userId", userId);
    
    twilioClient.messages.create({
        to: USER_PHONE,
        body: smsBody,
        messagingServiceSid: MSG_SERVICE_ID,
        statusCallback: statusCallbackUrl.toString()
    }).then(resp => {
        console.log('SMS sent', resp)
    })
    

    When the webhook request is made to your status callback URL the query parameters will be sent to and you will be able to use the userId to find your user.