c# - 带有 RestSharp 的 Paypal Rest Api 在 xamarin android 中不工作

标签 c# paypal xamarin.forms httpclient restsharp

当我调用 Paypal Rest API 时,RestSharp 组件出现错误。

我有以下使用 Xamarin for Android 的代码。

    public async Task<PayPalGetTokenResponse> GetAccessToken()
    {
        var restRequest = new RestRequest("/oauth2/token", Method.POST);
        // Add headers
        restRequest.AddHeader("Accept", "application/json");
        restRequest.AddHeader("Accept-Language", "en_US");

        // Make Authorization header
        restClient.Authenticator = new HttpBasicAuthenticator(Config.ApiClientId, Config.ApiSecret);

        // add data to send
        restRequest.AddParameter("grant_type", "client_credentials");

        var response = restClient.Execute<PayPalGetTokenResponse>(restRequest);

        response.Data.DisplayError = CheckResponseStatus(response, HttpStatusCode.OK);

        return response.Data;
    }

但出现错误:“Error: SecureChannelFailure (The authentication or decryption has failed.)”

我也使用了 ModernHttpClient 但得到了同样的错误

 public async Task<PayPalGetTokenResponse> GetAccessToken()
 {         
        string clientId = Config.ApiClientId;
        string secret = Config.ApiSecret;
        string oAuthCredentials =      Convert.ToBase64String(Encoding.Default.GetBytes(clientId + ":" + secret));
        string uriString = Config.ApiUrl+"/oauth2/token";
        PayPalGetTokenResponse result;

        HttpClient client = new HttpClient(new NativeMessageHandler());
        var h_request = new HttpRequestMessage(HttpMethod.Post, uriString);
        h_request.Headers.Authorization = new AuthenticationHeaderValue("Basic", oAuthCredentials);
        h_request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        h_request.Headers.AcceptLanguage.Add(new StringWithQualityHeaderValue("en_US"));
        h_request.Content = new StringContent("grant_type=client_credentials", UTF8Encoding.UTF8);
        try
        {

            HttpResponseMessage response = await client.SendAsync(h_request);
            //if call failed ErrorResponse created...simple class with response properties
            if (!response.IsSuccessStatusCode)
            {
                var error = await response.Content.ReadAsStringAsync();
                var errResp = JsonConvert.DeserializeObject<string>(error);
                //throw new PayPalException { error_name = errResp.name, details = errResp.details, message = errResp.message };
            }
            var success = await response.Content.ReadAsStringAsync();
            result = JsonConvert.DeserializeObject<PayPalGetTokenResponse>(success);
        }
        catch (Exception)
        {
            throw new HttpRequestException("Request to PayPal Service failed.");
        }
        return result;
    }

最佳答案

您是否尝试强制使用现代 SSL 协议(protocol)?

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

这对我有用:

if (ServicePointManager.SecurityProtocol != SecurityProtocolType.Tls12)
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; 

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);

关于c# - 带有 RestSharp 的 Paypal Rest Api 在 xamarin android 中不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39567830/

相关文章:

c# - 加载程序集 Xamarin.Android.Support.v4 时出现异常

c# - Xamarin.Android nuget 包引用 System.Web

c# - 在托管 Web 服务器中安排作业

php - IPN Paypal 协议(protocol)实际上需要 HTTP 200 响应吗?

php - 是否有用于更改 RecurringPaymentsProfile 信用卡号的 API?

c# - 将文本设置为剪贴板 Xamarin

c# - 页面加载后,Xamarin WebView.CanGoBack 和 CanGoForward 始终返回 false

c# - 如何使用 Web 代理从 Internet 读取 XML?

c# - 犀牛模拟 : AAA Synax: Assert property was set with a given type

php - 带有额外信息的 Paypal 结帐