skip to Main Content

I’ve tested my Twilio number and personal number using Twilios website API so I know the problem isn’t with either of them. Using the below method and any phone number I try as recipientPhoneNumber in the ‘+1xxxxxxxxxx’ format returns the error:

Twilio API Response Text: {"code": 21604, "message": "A 'To' phone number is required.", "more_info": "https://www.twilio.com/docs/errors/21604", "status": 400}
Twilio API request error: HTTP/1.1 400 Bad Request
Twilio API Request Method: POST

I assumed I should be able to use any phone number, but to be safe I even verified my number as a ‘Caller ID’ within Twilio. I’ve encountered errors related to my account SID and Auth, and resolved them so I know they aren’t the problem.

public IEnumerator SendMessage(string recipientPhoneNumber, string message)
{
    // Create the JSON payload for the request
    Debug.Log("The recipient phone number is: " + recipientPhoneNumber);
    string jsonPayload = JsonUtility.ToJson(new
    {
        from = twilioPhoneNumber,
        to = recipientPhoneNumber,
        body = message
    });

    // Create the UnityWebRequest object
    UnityWebRequest request = UnityWebRequest.Post(twilioMessagesApiUrlFormatted, 
    jsonPayload);

    // Set the authorization header with your Account SID and Auth Token
    string auth = accountSid + ":" + authToken;
    string base64Auth = 
    System.Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(auth));
    string authorizationHeader = "Basic " + base64Auth;
    request.SetRequestHeader("Authorization", authorizationHeader);
    request.SetRequestHeader("Content-Type", "application/json");

    // Send the HTTP request
    request.uploadHandler = new 
    UploadHandlerRaw(System.Text.Encoding.UTF8.GetBytes(jsonPayload));
    request.downloadHandler = new DownloadHandlerBuffer();
    yield return request.SendWebRequest();
   
    
}

I recently created my Twilio account and don’t have strong experience with it so let me know if I need to make some configurations in the console or if something in my code is causing the recipient phone number to be misread or not sent correctly.

I call the method with

StartCoroutine(twilioSMS.SendMessage("+1xxxxxxxxxx", "This is a test message"));

Within the method I’ve even printed the ‘from’, ‘to’, ‘body’ so I know the method is receiving them.

Any guidance here would be of great help. Thanks

2

Answers


  1. Chosen as BEST ANSWER

    Sending an outgoing message in Twilio requires use of x-www-form-urlencoded format. The SendMessage method now uses a dictionary (formData) to hold the form data, and the UnityWebRequest.Post method is used to send the request with the form data.

    public IEnumerator SendMessage(string recipientPhoneNumber, string message)
    {
        // Create a dictionary to hold the form data
        Dictionary<string, string> formData = new Dictionary<string, string>
        {
            { "From", twilioPhoneNumber },
            { "To", recipientPhoneNumber },
            { "Body", message }
        };
    
        // Create the UnityWebRequest object
        UnityWebRequest request = UnityWebRequest.Post(twilioMessagesApiUrlFormatted, formData);
    
        // Set the authorization header with your Account SID and Auth Token
        string auth = accountSid + ":" + authToken;
        string base64Auth = System.Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(auth));
        string authorizationHeader = "Basic " + base64Auth;
        request.SetRequestHeader("Authorization", authorizationHeader);
    
        // Send the HTTP request
        yield return request.SendWebRequest();
    
    }
    

  2. Issue

    This

    new
    {
        from = twilioPhoneNumber,
        to = recipientPhoneNumber,
        body = message
    }
    

    is creating an instance of Anonymous Type which uses readonly properties.

    The built-in JsonUtility uses the default Unity Serializer which has certain limitations (see Unity Script Serialization) among them:

    • Only supports fields
    • Fields may not be readonly

    => If you print your jsonPayload you will find that it only contains

    {}
    

    Option 1

    You will either need to have a proper wrapper type like e.g.

    [Serializable]
    public class Message
    {
        public string from,
        public string to,
        public string body;
    }
    

    and explicitly use

    string jsonPayload = JsonUtility.ToJson(new Message
    {
        from = twilioPhoneNumber,
        to = recipientPhoneNumber,
        body = message
    });
    

    Option 2

    Or you could use a Tuple with explicit names instead

    string jsonPayload = JsonUtility.ToJson(
    (
        from: twilioPhoneNumber,
        to: recipientPhoneNumber,
        body: message
    ));
    

    Option 3

    or you will have to use another third-party JSON library that also supports readonly properties like e.g. the most commonly used Newtonsoft Json.NET (available as a package via Unity’s PackageManager)

    using Newtonsoft.Json;
    
    ...
    
    string jsonPayload = JsonConvert.SerializeObject(new
    {
        from = twilioPhoneNumber, 
        to = recipientPhoneNumber, 
        body = message
    });
    

    See .Net fiddle

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search