使用 RestSharp 返回“状态代码:未找到”获取 PayPal 访问令牌

Posted

技术标签:

【中文标题】使用 RestSharp 返回“状态代码:未找到”获取 PayPal 访问令牌【英文标题】:Getting PayPal Access Token with RestSharp returning "Status Code: NotFound" 【发布时间】:2021-04-17 13:13:57 【问题描述】:

获取 PayPal 访问令牌不起作用

我收到了回复:

“状态码:未找到,内容类型:应用程序/json,内容长度:131)”

我的代码,使用 RestSharp

public void getToken()

    var clientId = "client-ID";
    var secret = "client-secret";

    if (ServicePointManager.SecurityProtocol != SecurityProtocolType.Tls12) ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // forced to modern day SSL protocols
    var client = new RestClient("https://api.paypal.com/v1/oauth2/token")  Encoding = Encoding.UTF8 ;
    var authRequest = new RestRequest("oauth2/token", Method.POST)  RequestFormat = DataFormat.Json ;
    client.Authenticator = new HttpBasicAuthenticator(clientId, secret);
    authRequest.AddParameter("grant_type", "refresh_token&refresh_token=refresh_token");
    var authResponse = client.Execute(authRequest);

我确实有点感觉我的grant_type 可能不正确,因为我不是 100% 确定这里实际发生了什么,经过一些研究后我仍然不清楚 - 但我选择了 @987654323 @。尽管refresh_token 是静态的,但我不确定您是否应该用值填充它,或者如何填充。

有人知道我做错了什么吗?如果我怀疑grant_type 是正确的?

【问题讨论】:

【参考方案1】:

你已经翻倍了。

new RestClient("https://api.paypal.com/v1/oauth2/token") 

这一行将该 URL 设置为 基地址,它被添加到您的其他路径字符串之前。因此,当您使用new RestRequest("oauth2/token", ...) 时,您最终获取的 URL 是

https://api.paypal.com/v1/oauth2/token/oauth2/token

只需从基地址中删除路径字符串,这样你就有了:

 new RestClient("https://api.paypal.com/v1") 

【讨论】:

似乎是一个愚蠢的问题,但它不需要是新的RestRequest("v1/oauth2/token", ...)吗?没有 v1,它给我一个 0 状态码,没有它,状态码是“badrequest”。 @MattHodson 你说得对,我并不是要删除 v1.1 版本。很抱歉,我放的太多了。您可以将 v1 添加到任一路径字符串。【参考方案2】:

我同意上述观点,但已经整理了一些答案

public string GetAccessToken()

  var clientId = "my_client_id";
  var secret = "my_password";

  var client = new RestClient("https://api-m.sandbox.paypal.com/")  Encoding = Encoding.UTF8 ;
  var authRequest = new RestRequest("v1/oauth2/token", Method.POST)  RequestFormat = DataFormat.Json ;
  client.Authenticator = new HttpBasicAuthenticator(clientId, secret);

  authRequest.AddParameter("grant_type", "client_credentials");
  var response = client.Execute(authRequest);

  AccessToken token = JsonConvert.DeserializeObject<AccessToken>(response.Content);
  return token.access_token;





public class AccessToken
 

    public string scope  get; set; 
    public string access_token  get; set; 
    public string token_type  get; set; 
    public string app_id  get; set; 
    public int expires_in  get; set; 
    public string nonce  get; set; 

  

【讨论】:

以上是关于使用 RestSharp 返回“状态代码:未找到”获取 PayPal 访问令牌的主要内容,如果未能解决你的问题,请参考以下文章

页面重定向时 HttpWebRequest 和 Restsharp 不返回响应

如何将 JSON 返回反序列化为从 RestSharp 调用到 API 的对象数组?

RestSharp Deserialize 返回空属性,但 xml.deserialize 测试有效

RestSharp 打印原始请求和响应标头

如何使用restsharp下载文件

RestSharp 获取 REST 数据但不会反序列化