MyDaftQuestions
MyDaftQuestions

Reputation: 4691

How to get access token from PayPal in MVC

I am trying to get an access token from PayPal.

I have set it up as an application within PayPal, and I can see my client ID and secret

I am assuming I don't want to expose my secret in the javascript front end, so I am attempting to get the access code from the C#, pass the token to the front end so I can make AJAX posts/gets.

However, it always returns with unauthorized

This is my effort

var url = "https://api.paypal.com/v1/oauth2/token";

var clientId = "myClientId";
var pwrd = "mySecret";

var client = new WebClient();
client.Credentials = new NetworkCredential(clientId, pwrd);
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
client.Headers.Add("Accept: application/json");
var result = "";
using (var httpClient = new HttpClient())
{
    var response = await httpClient.PostAsync(url, null);
    result = response.StatusCode.ToString();
}

return View(model: result);
   

I do not understand why, when I run this from my live application, it fails

Edit

I replaced

using (var httpClient = new HttpClient())
{
    var response = await httpClient.PostAsync(url, null);
    result = response.StatusCode.ToString();
}

with

var clientId = "myClientId";
var seceret = "mySecret";

var client = new HttpClient();

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
    "Basic", Convert.ToBase64String(
        System.Text.ASCIIEncoding.ASCII.GetBytes(
           $"{clientId}:{seceret}")));

 var dict = new Dictionary<string, string>();
 dict.Add("Content-Type", "application/x-www-form-urlencoded");

 var req = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(dict) };
 var response = await client.SendAsync(req);

The same issue persists. I get a 401

Upvotes: 0

Views: 724

Answers (3)

Allie
Allie

Reputation: 1179

The following code worked for me :

   string bearerToken = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(
              $"{clientId}:{secret}"));

   var collection = new List<KeyValuePair<string, string>>();
   collection.Add(new("grant_type", "client_credentials"));
   collection.Add(new("ignoreCache", "true"));
   collection.Add(new("return_authn_schemes", "true"));
   collection.Add(new("return_client_metadata", "true"));
   collection.Add(new("return_unconsented_scopes", "true"));

   using (var client = new HttpClient())
   {
       var request = new HttpRequestMessage(HttpMethod.Post, $"{baseUrl}v1/oauth2/token");
       request.Headers.Add("Authorization", $"Basic {bearerToken}");
       request.Content = new FormUrlEncodedContent(collection);
       var response = await client.SendAsync(request);
       response.EnsureSuccessStatusCode();

       JObject jResponse = JObject.Parse(await response.Content.ReadAsStringAsync());
       string accessToken= jResponse["access_token"].ToString();
   }

Upvotes: 1

Preston PHX
Preston PHX

Reputation: 30359

To elaborate on the comment and other answer, here you create a variable named client

var client = new WebClient();
client.Credentials = new NetworkCredential(clientId, pwrd);
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
client.Headers.Add("Accept: application/json");

And in the next code that follows, you do nothing using that client variable. The above is completely ignored and irrelevant to this:

using (var httpClient = new HttpClient())
{
    var response = await httpClient.PostAsync(url, null);
    result = response.StatusCode.ToString();
}

return View(model: result);

So, make use of the client object you created -- likely with UploadValues or similar.

Upvotes: 1

Bartosz
Bartosz

Reputation: 1820

And it will never authorize, because HttpClient variable knows nothing about your credentials. You initialized it in WebClient, but you are not using it.

Upvotes: 2

Related Questions