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
CodePudding user response:
And it will never authorize, because HttpClient variable knows nothing about your credentials. You initialized it in WebClient, but you are not using it.
CodePudding user response:
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.