Paypal REST api call works from cURL but not from C# code

前端 未结 4 1500
旧时难觅i
旧时难觅i 2021-02-09 01:12

I\'m trying to call Paypal api from my code. I set up the sandbox account and it works when I use curl but my code isn\'t working the same way, returning 401 Unauthorized instea

4条回答
  •  无人及你
    2021-02-09 02:12

    I too suffered from a lack of example code and various issues with response errors and codes.

    I am a big fan of RestClient as it helps a lot with integrations and the growing number of RESTful API calls.

    I hope this small snippet of code using RestSharp helps someone: -

            if (ServicePointManager.SecurityProtocol != SecurityProtocolType.Tls12) ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // forced to modern day SSL protocols
            var client = new RestClient(payPalUrl) { Encoding = Encoding.UTF8 };
            var authRequest = new RestRequest("oauth2/token", Method.POST) {RequestFormat = DataFormat.Json};
            client.Authenticator = new HttpBasicAuthenticator(clientId, secret);
            authRequest.AddParameter("grant_type","client_credentials");
            var authResponse = client.Execute(authRequest);
            // You can now deserialise the response to get the token as per the answer from @ryuzaki 
            var payPalTokenModel = JsonConvert.DeserializeObject(authResponse.Content);
    

提交回复
热议问题