Getting “A From phone number is required” in JSON call to Twilio

别说谁变了你拦得住时间么 提交于 2019-12-23 18:54:34

问题


I'm trying to use JSON over HTTP to communicate with the Twilio API (I'm running on asp.net vNext - and their C# library doesn't yet support coreclr)

I've got the following code, but every time I call the API I get the same 400 - Bad request response:

{"code": 21603, "message": "A 'From' phone number is required.", "more_info": "https://www.twilio.com/docs/errors/21603", "status": 400}

I'm using the following code to setup the request and make the call - the auth succeeds and I get the above error:

var byteArray = Encoding.ASCII.GetBytes("{AccountSid}:{AuthToken}");

HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

var jsonStr = JsonConvert.SerializeObject(new {
    From = WebUtility.UrlEncode("+15005550003"), // A test number twilio supply
    To = WebUtility.UrlEncode("{my phone number}"),
    Body = WebUtility.UrlEncode("Hi there from a pure json rest client...")
});

var response = await client.PostAsync("https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/SMS/Messages.json", new StringContent(jsonStr));

回答1:


After contacting support and dealing with a very helpful guy called Joshua, we have figured it out.

In Twilio docs you can either use a url with "messages.json" or "messages.xml" - I took that to mean: whichever url you use, the message (request and response) will have to follow that format.

Unfortunately that is not true - all requests to Twilio, must be of Content-Type: application/x-www-form-urlencoded

e.g. To=0123456789&From=9876543210&Body=Hi

in C# (HttpClient) that looks like:

_client.PostAsync(_url, new FormUrlEncodedContent(new Dictionary<string, string>(){
 { "To", "0123456789" }, 
 { "From", "9876543210" }, 
 { "Body", "Hi" } }));



回答2:


I'm Megan from the Developer Community team at Twilio.

It looks like the number you are using, "+15005550003" is one of Twilio's magic input numbers that actually represents the "To" field, thus the error you are receiving. Depending on what you want to test, you might try passing in "+15005550006" instead.

You can see more about what each magic input represents in the docs here.

Hope this helps!




回答3:


If using an SMS / Messaging Service which allows you to send from multiple phone numbers and you get this error,

then replace

{ "From","<number>" }

with

{ "MessagingServiceSid","<sid>" }

the SID can be found on the messaging services page https://www.twilio.com/console/sms/services



来源:https://stackoverflow.com/questions/33764125/getting-a-from-phone-number-is-required-in-json-call-to-twilio

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!