PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, July 4, 2022

[FIXED] How to get access token from PayPal in MVC

 July 04, 2022     c#, paypal     No comments   

Issue

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


Solution

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



Answered By - Bartosz Olchowik
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing