I'm trying to use the PayPal API with this code to get a Valid Token:
var clientId = "yyyy";
var secret = "xxxx";
var client = new RestClient("https://api-m.sandbox.paypal.com/");
client.AddDefaultHeader("Authorization", "Basic " +
Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", clientId,
secret))));
var request = new RestRequest("v1/oauth2/token", Method.Post);
request.AddParameter("grant_type", "client_credentials");
var response = await client.ExecuteGetAsync(request);
But the response coming back is:
{"error":"invalid_token","error_description":"Authorization header does not have valid access token"}
Is there something I'm missing, when I use Postman, I have the exact same parameters filled in Postman with my C# code as well.
Try switching the request class to a different one. For example you could use HttpClient
var clientId = "yyyy";
var secret = "xxxx";
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://api-m.sandbox.paypal.com/");
var authToken = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{clientId}:{secret}"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authToken);
var requestContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "client_credentials")
});
var response = await client.PostAsync("v1/oauth2/token", requestContent);
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
}