I'm trying to call Paypal api from my code. I set up the sandbox account and it works when I use curl but my code isn't working the same way, returning 401 Unauthorized instead.
Here's the curl command as documented by Paypal
curl https://api.sandbox.paypal.com/v1/oauth2/token -H "Accept: application/json" -H "Accept-Language: en_US" -u "A****:E****" -d "grant_type=client_credentials" UPDATE: Apparently the .Credentials doesn't do the trick, instead setting Authorization header manually works (see code)
Here's the code (trimmed to its essence):
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://api.sandbox.paypal.com/v1/oauth2/token"); request.Method = "POST"; request.Accept = "application/json"; request.Headers.Add("Accept-Language:en_US") // this doesn't work: **request.Credentials = new NetworkCredential("A****", "E****");** // DO THIS INSTEAD **string authInfo = Convert.ToBase64String(System.Text.Encoding.Default.GetBytes("A****:E****"));** **request.Headers["Authorization"] = "Basic " + authInfo;** using (StreamWriter swt = new StreamWriter(request.GetRequestStream())) { swt.Write("grant_type=client_credentials"); } request.BeginGetResponse((r) => { try { HttpWebResponse response = request.EndGetResponse(r) as HttpWebResponse; // Exception here .... } catch (Exception x) { .... } // log the exception - 401 Unauthorized }, null); This is the request from code captured by Fiddler (raw), there are no authorization parameters for some reason:
POST https://api.sandbox.paypal.com/v1/oauth2/token HTTP/1.1 Accept: application/json Accept-Language: en_US Host: api.sandbox.paypal.com Content-Length: 29 Expect: 100-continue Connection: Keep-Alive grant_type=client_credentials