Click here to Skip to main content
15,881,381 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I followed this PayPal document https://developer.paypal.com/docs/api/subscriptions/v1[^] for subscription API. I want to call this API https://api.sandbox.paypal.com/v1/billing/subscriptions/${subscriberId} using ASP .NET MVC. This API needs authorization token using PayPal clientID and secretID which I've successfully created the token but I've problem in calling subscription API.
curl -v -X GET 
https://api.sandbox.paypal.com/v1/billing/subscriptions/I-BW452GLLEP1G \
-H "Content-Type: application/json" \
-H "Authorization: Bearer Access-Token"


What I have tried:

Also I've just call this API using react JS and I'm getting desire result. But in ASP .NET MVC how to call this subscription API ? React JS Code:
JavaScript
async function checkPayPalPaymentStatus(subscriberId, access_token) {
  var token = `Bearer ${access_token}`;
  return await fetch(
    `https://api.sandbox.paypal.com/v1/billing/subscriptions/${subscriberId}`,
    {
      method: "GET",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
        Authorization: token,
      },
    }
  ).then((response) => response.json());
}

ASP .NET MVC Code(Problem):
C#
[HttpGet]
[Route("api/paypal/checkPayPalPaymentStatus")]
public async Task<object> CheckPayPalPaymentStatus(string accessToken)
{
    try
    {
        //
        string url = "https://api.sandbox.paypal.com/v1/billing/subscriptions/" + "I-BW452GLLEP1G";
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Headers["Authorization"] = "Bearer " + Convert.ToBase64String(Encoding.Default.GetBytes(accessToken));
        request.Accept = "application/json";
        request.Method = "GET";
        request.ContentType = "application/json";

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream streamResponse = response.GetResponseStream();
        StreamReader streamRead = new StreamReader(streamResponse);
        string responseString = streamRead.ReadToEnd();
        JObject jsonConvertedResponseString = JObject.Parse(responseString);
        return new
        {
            Success = true,
            Message = "",
            Data = jsonConvertedResponseString
        };
    }
    catch (Exception ex)
    {
        return new
        {
            Success = false,
            Message = ex.Message,
            Data = DBNull.Value
        };
    }
}
Posted
Updated 21-Jan-21 22:26pm
v2
Comments
Richard Deeming 22-Jan-21 4:28am    
Your React code passes the access_token to the authorization header unchanged. But your C# code extracts the bytes and encodes them in Base64.

Are you sure you're not double-encoding the access token in your C# code?
Muhmmad Nauman 25-Jan-21 4:31am    
Yes, I'm getting access_token as response from paypal token api i.e https://api.sandbox.paypal.com/v1/oauth2/token and passing access_token as parameter in above my api function.
And I'm getting error "The remote server returned an error: (401) Unauthorized." on line (HttpWebResponse)request.GetResponse();
Richard Deeming 25-Jan-21 4:35am    
Read my comment again: the working code passes the access token directly in the header; the not-working code takes the access token as a string, gets the bytes that represents that string, encodes those bytes with Base64, and then passes that new string to the API.

You are double-encoding the header value. The server doesn't understand the value you've sent, so it rejects your request as "unauthorized".
Richard Deeming 25-Jan-21 4:37am    
For example, if the access token is: NDI=

Your React code sends it as: NDI=; the API decodes that to "42", which is the expected value.

Your C# code sends it as: TkRJPQ==; the API decodes that to "NDI=", which is NOT the expected value.
Muhmmad Nauman 25-Jan-21 5:27am    
Thanks Richard for your support..
var client = new HttpClient();
client.BaseAddress = new Uri("https://api.sandbox.paypal.com");
var authHeader = new AuthenticationHeaderValue("Bearer", accessToken);
client.DefaultRequestHeaders.Authorization = authHeader;
client.DefaultRequestHeaders
.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync("/v1/billing/subscriptions/" + "I-BW452GLLEP1G").Result;
if (response.IsSuccessStatusCode)
{
string responseBody = response.Content.ReadAsStringAsync().Result;
JObject jsonConvertedResponseString = JObject.Parse(responseBody);
return new
{
Success = true,
Message = "",
Data = jsonConvertedResponseString
};
}
return new
{
Success = false,
Message = "Something went wrong.",
Data = DBNull.Value
};
This code working fine for me...

1 solution

Never, ever, accept code from a insecure website to handle anything to do with real money.
You do not know who is giving you the code, you do not know what it does, you do not know that it places the monies correctly into the appropriate account, without passing the details to any third parties.

Only get such code from paypal - the scope for fraud otherwise is far too large. And remember, you personally could be liable for any monies lost if your action is seen to be negligent - which getting your code from a public forum would most certainly be!

So talk to Paypal: their tech support is pretty good, and remember - they only get paid when you do ... so they have a good incentive to help you get up and running quickly!
 
Share this answer
 
Comments
Christian Graus 22-Jan-21 3:36am    
Jesus.....
OriginalGriff 22-Jan-21 4:05am    
No, I'm OriginalGriff ... :laugh:
Richard Deeming 22-Jan-21 4:25am    
He's not the messiah... :D
OriginalGriff 22-Jan-21 5:28am    
... I'm a very naughty boy!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900