Search code examples
asp.net-mvcpaypalpaypal-rest-sdkunauthorized

The remote server returned an error: (401) Unauthorized. while using Paypal Rest APi


I'm using Paypal Rest APi. when I try to get access token it gives me Unauthorized error. Index Page

@Html.ActionLink("Pay with Paypal Account", "PaymentWithPaypal", "Paypal")

web.config

<configSection>
<section name="paypal" type="PayPal.SDKConfigHandler, PayPal"/>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSection>

    <paypal>
    <settings>
      <add name="mode" value="sandbox"/>
      <add name="connectionTimeout" value="360000"/>
      <add name="requestRetries" value="1"/>
      <add name="clientId" value="###########"/>
      <add name="clientSecret" value="**********"/>
    </settings>
  </paypal>
  <log4net>
    <appender name="FileAppender" type="log4net.Appender.FileAppender">
      <file value="my_app.log"/>
      <appendToFile value="true"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date       [%thread] %-5level %logger [%property{NDC}] %message%newline"/>
      </layout>
    </appender>
    <root>
      <level value="DEBUG"/>
      <appender-ref ref="FileAppender"/>
    </root>
  </log4net>
  <system.web>
    <securityPolicy>
      <trustLevel name="Full" policyFile="internal"/>
    </securityPolicy>

The error message is

The remote server returned an error: (401) Unauthorized.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: PayPal.IdentityException: The remote server returned an error: (401) Unauthorized

Error comes on following line

string accessToken = new OAuthTokenCredential(ClientId, ClientSecret, GetConfig()).GetAccessToken();

In Inspect element following message is given.

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

The code I used to integrate Rest Api can be found here http://www.codeproject.com/Articles/870870/Using-Paypal-Rest-API-with-ASP-NET-MVC

Can anyone please help me to resolve this issue.


Solution

  • Try Below Code

           Dictionary<string, string> payPalConfig = new Dictionary<string, string>();
           payPalConfig.Add("mode", "sandbox");
           OAuthTokenCredential tokenCredential = new AuthTokenCredential("myCliedId","myClientSecret", payPalConfig);
           string accessToken = tokenCredential.GetAccessToken();