从cURL调用PaypalRESTapi但无法在C#代码中使用我设置了一个沙箱帐户,当我使用curl但它的代码以不同方式工作时,它可以工作,返回401Unauthorized。这是curl命令curlhttps://api.sandbox.paypal.com/v1/oauth2/token-H"Accept:application/json"-H"Accept-Language:en_US"-u"A***asdocumentedbyPaypal*:E****"-d"grant_type=client_credentials"更新:显然.Credentials问题,而是手动设置授权标头(见代码)这是代码(精简到本质):HttpWebRequestrequest=(HttpWebRequest)HttpWebRequest.Create("https://api.sandbox.paypal.com/v1/oauth2/token");request.Method="POST";request.Accept="应用程序/json";request.Headers.Add("Accept-Language:en_US")//这不起作用:**request。Credentials=newNetworkCredential("A****","E****");**//改为这样做**stringauthInfo=Convert.ToBase64String(System.Text.Encoding.Default.GetBytes("A****:E****"));**request.Headers["Authorization"]="Basic"+authInfo;**使用(StreamWriterswt=newStreamWriter(request.GetRequestStream())){swt.Write("grant_type=client_credentials");}request.BeginGetResponse((r)=>{try{HttpWebResponseresponse=request.EndGetResponse(r)asHttpWeb响应;//这里有异常....}catch(Exceptionx){....}//记录异常-401Unauthorized},null);这是对Fiddler(原始)捕获的代码的请求,由于某些原因没有授权参数:POSThttps://api.sandbox.paypal.com/v1/oauth2/tokenHTTP/1.1Accept:application/jsonAccept-Language:en_USHost:api.sandbox.paypal.comContent-Length:29Expect:100-continueConnection:Keep-Alivegrant_type=client_credentials希望下面的代码能帮助那些还在寻找好蛋糕连接PayPal的人像许多人一样,我花了很多时间试图让我的PayPal令牌访问失败,直到我发现以下内容:/questions/32994464/could-not-create-ssl-tls-secure-channel-despite-setting-servercertificatevalidaServicePointManager.ServerCertificateValidationCallback+=(sender,cert,chain,sslPolicyErrors)=>true;ServicePointManager.SecurityProtocol=Security.ProtocolSsl3|安全协议类型.Tls|安全协议类型.Tls11|安全协议类型.Tls12;try{//你的Paypal应用API的ClientIdstringAPIClientId="**_[your_API_Client_Id]_**";//你的Paypal应用API的密钥stringAPISecret="**_[your_API_secret]_**";使用(varclient=newSystem.Net.Http.HttpClient()){varbyteArray=Encoding.UTF8.GetBytes(APIClientId+":"+APISecret);客户。DefaultRequestHeaders.Authorization=newSystem.Net.Http.Headers.AuthenticationHeaderValue("基本",Convert.ToBase64String(byteArray));varurl=newUri("https://api.sandbox.paypal.com/v1/oauth2/token",UriKind.Absolute);client.DefaultRequestHeaders.IfModifiedSince=DateTime.UtcNow;varrequestParams=newList>{newKeyValuePair("grant_type","client_credentials")};varcontent=newFormUrlEncodedContent(requestParams);varwebresponse=awaitclient.PostAsync(url,content);varjsonString=awaitwebresponse.Content.ReadAsStringAsync();//响应将使用Jsonconver进行反序列化varpayPalTokenModel=JsonConvert.DeserializeObject(jsonString);}}catch(System.Exceptionex){//TODO:记录连接错误}}}publicclassPayPalTokenModel{publicstringscope{get;放;}publicstringnonce{get;放;}publicstringaccess_token{得到;放;}publicstringtoken_type{get;放;}publicstringapp_id{得到;放;}publicintexpires_in{得到;放;}}这段代码对我有用,希望你也有用这适用于使用HttpClient......'RequestT'是PayPal请求参数的通用名称,但未被使用。使用“ResponseT”,这是PayPal根据他们的文档做出的回应。“PayPalConfig”类使用ConfigurationManager从web.config文件中读取clientid和secret。需要牢记的是将Authorization标头设置为“Basic”而不是“Bearer”,以及您是否使用正确的媒体类型(x-www-form-urlencoded)正确构建了“StringContent”对象。//获取PayPalaccessTokenpublicasyncTaskInvokePostAsync(RequestTrequest,stringactionUrl){ResponseTresult;//'HTTPBasicAuthPost'stringclientId=PayPalConfig.clientId;stringsecret=PayPalConfig.clientSecret;字符串oAuthCredentials=Convert.ToBase64String(Encoding.Default.GetBytes(clientId+":"+secret));//基于'productionMode'stringuriString=PayPalConfig.endpoint(PayPalConfig.productionMode)+actionUrl;//到PayPAl'live'或'stage'HttpClient客户端=newHttpClient();//构造请求消息varh_request=newHttpRequestMessage(HttpMethod.Post,uriString);h_request.Headers.Authorization=newAuthenticationHeaderValue("Basic",oAuthCredentials);h_request.Headers.Accept.Add(newMediaTypeWithQualityHeaderValue("application/json"));h_request.Headers.AcceptLanguage.Add(newStringWithQualityHeaderValue("en_US"));h_request.Content=newStringContent("grant_type=client_credentials",UTF8Encoding.UTF8,"应用程序/x-www-form-urlencoded");尝试{HttpResponseMessageresponse=awaitclient.SendAsync(h_request);//ifcallfailedErrorResponsecreated...具有响应属性的简单类ErrorResponseerrResp=JsonConvert.DeserializeObject(error);thrownewPayPalException{error_name=errResp.name,details=errResp.details,message=errResp.message};}varsuccess=awaitresponse.Content.ReadAsStringAsync();结果=JsonConvert.DeserializeObject(成功);}catch(Exception){thrownewHttpRequestException("请求PayPal服务失败。");}返回结果;}重要信息:使用Task.WhenAll()确保您有结果//通过HttpClient调用获取访问令牌..并确保在继续之前有一个结果//所以您不会尝试传递一个空的或失败的令牌。publicasyncTaskAuthorizeAsync(TokenRequestreq){TokenResponse响应;try{vartask=newPayPalHttpClient().InvokePostAsync(req,req.actionUrl);等待Task.WhenAll(任务);响应=任务。结果;}catch(PayPalExceptionex){response=newTokenResponse{access_token="error",Error=ex};}返回响应;}Paypal已弃用TLS1.1,现在只接受1.2。不幸的是,.NET(4.7之前的版本)默认使用1.1,除非您另外配置它??。您可以使用此行打开TLS1.2。我建议将它放在Application_Start或global.asax中。ServicePointManager.SecurityProtocol=SecurityProtocolType.Tls12;我还缺少示例代码以及响应错误和代码的各种问题。我是RestClient的忠实粉丝,因为它对集成和越来越多的RESTfulAPI调用有很大帮助。我希望这段使用RestSharp的小代码可以帮助别人:-以上是C#学习教程:从cURL调用PaypalRESTapi,但不是C#代码分享全部内容,如果它对大家有用并且需要知道more希望大家多多关注C#学习教程—if(ServicePointManager.SecurityProtocol!=SecurityProtocolType.Tls12)ServicePointManager.SecurityProtocol=SecurityProtocolType.Tls12;//强制使用现代SSL协议varclient=newRestClient(payPalUrl){Encoding=Encoding.UTF8};varauthRequest=newRestRequest("oauth2/token",Method.POST){RequestFormat=DataFormat.Json};client.Authenticator=newHttpBasicAuthenticator(clientId,secret);authRequest.AddParameter("grant_type","client_credentials");varauthResponse=client.Execute(authRequest);//您现在可以根据@ryuzaki的回答反序列化响应以获取令牌varpayPalTokenModel=JsonConvert.DeserializeObject(authResponse.Content);如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
