Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PayPal API – Authorization header does not have valid access token

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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();
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading