Search code examples
gotwiliowhatsapptwilio-api

Trying Twilio whatsappp api call but getting error 20422


I am getting an error while using twilio whatsapp api.

Following is the code :

package main

import (
    "fmt"

    "github.com/twilio/twilio-go"
    api "github.com/twilio/twilio-go/rest/api/v2010"
)

func main() {

    clientParameter := twilio.ClientParams{}
    clientParameter.Username = "AC***********************ba"
    clientParameter.Password = "ce************************27"
    clientParameter.AccountSid = "AC************************ba"

    client := twilio.NewRestClientWithParams(clientParameter)

    params := &api.CreateMessageParams{}
    params.SetContentSid("HT**********************70")
    params.SetMessagingServiceSid("MG******************************0d")
    params.SetFrom("whatsapp:+917*******2")
    params.SetTo("whatsapp:+917********4")

    resp, err := client.Api.CreateMessage(params)
    if err != nil {
        fmt.Println(err.Error())
    } else {
        if resp.Sid != nil {
            fmt.Println(*resp.Sid)
        } else {
            fmt.Println(resp.Sid)
        }
    }
}

The error I am getting is -

Status: 400 - ApiError 20422: Invalid Parameter (null) More info: https://www.twilio.com/docs/errors/20422

Same error I am getting if trying through Postman.


Solution

  • Error 20422 means that one of these three conditions is not met:

    • Lacking a specified Content-Type header field
    • Invalid or missing XML data
    • Invalid parameter type or value

    The error log in the console might provide a more detailed explaination.

    Since you are using the SDK, it's most likely the third bullet point. Is there a reason why you are using a MessagingServiceSid and the From field? I'd recommend updating the client to the latest version and running this script:

    package main
    
    import (
        "fmt"
        "log"
        "os"
    
        "github.com/joho/godotenv"
        "github.com/twilio/twilio-go"
        api "github.com/twilio/twilio-go/rest/api/v2010"
    )
    
    
    func main() {
        err := godotenv.Load()
        if err != nil {
                log.Fatal("Error loading .env file")
        }
    
        client := twilio.NewRestClient()
    
        params := &api.CreateMessageParams{}
        params.SetTo("whatsapp:"+os.Getenv("RECIPIENT_PHONE_NUMBER"))
        params.SetFrom(os.Getenv("TWILIO_MESSAGING_SERVICE"))
        params.SetContentSid(os.Getenv("CONTENT_SID"))
    
        _, err = client.Api.CreateMessage(params)
        if err != nil {
            fmt.Println(err.Error())
        } else {
            fmt.Println("Message sent successfully!")
        }
    }