0

i am trying to fetch an access token by calling an API with an auth code and keeping getting a 400 error.

I have read many a web sites and can't see what is wrong with this. thanks. I have left in commented bits as this is other ways I have tried. Appreciate any quick advice

HttpWebRequest request = WebRequest.Create("https://identity.xero.com/connect/token") as HttpWebRequest;

request.Headers.Add("Authorization", "Basic " + b64_id_secret);

//string data = "{ grant_type : refresh_token, refresh_token : " + l_auth_code+ "}";
//string data = "{ 'grant_type' : 'authorization_code', 'code' : '" + l_auth_code + "', 'redirect_uri' : '" + C_XERO_REDIRECT_URL + "'}";

request.ContentType = "application/json";
request.Method = "POST";
//request.ContentType = "application/json";
//request.ContentLength = postBytes.Length;
//request.Accept = "application/json";

using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
                        string json = "{\"grant_type\":\"authorization_code\"," +
                                      "\"code\":\"" + l_auth_code + "\","+
                                      "\"redirect_uri\":\"" + C_XERO_REDIRECT_URL + "\"}";
                        streamWriter.Write(json);
}
// crashes here
var httpResponse = (HttpWebResponse)request.GetResponse();

using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
}
Ab Bennett
  • 1,391
  • 17
  • 24
  • Do you already follow... xero guide to use their API? – Smankusors Mar 06 '20 at 00:57
  • yes, read them inside out, they have no c# code other than a library which i cant use. have identical code working in python that needs to be cut over – Ab Bennett Mar 06 '20 at 02:54
  • The example in their documentation uses `application/x-www-form-urlencoded` content type. Maybe try changing to that in your code – devNull Mar 06 '20 at 03:03
  • ok thanks, how do you know that by the way, although I am confused, as I am passing json not key value pairs. This also made no difference – Ab Bennett Mar 06 '20 at 03:16
  • @AbBennett the example I found is in their [oauth documentation](https://developer.xero.com/documentation/oauth2/auth-flow). And you'd need to update to send a `form-urlencoded` body instead of JSON. – devNull Mar 06 '20 at 03:22
  • See [this answer](https://stackoverflow.com/a/4015346/5803406) for an example of posting a urlencoded body with C# – devNull Mar 06 '20 at 03:25
  • Thanks for the tips above using a post string fixed the problem had misread that piece of text – Ab Bennett Mar 06 '20 at 05:35

0 Answers0