如何使用http请求获取paypal访问令牌?

时间:2015-11-07 11:47:30

标签: http paypal

我需要将我的移动应用与paypal集成。为此,我选择了Rest API。但我无法获得访问令牌!我使用Mozilla Firefox来测试网络操作。在这里我的要求

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

此处标题

ost: api.sandbox.paypal.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:42.0) Gecko/20100101 Firefox/42.0
Accept: application/json
Accept-Language: en-US
Accept-Encoding: gzip, deflate
Cache-Control: max-age=0, no-cache
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Pragma: no-cache
Referer: https://www.mozilla.org/ru/firefox/42.0/whatsnew/?oldversion=41.0.2
Content-Length: 172
Origin: https://www.mozilla.org
Connection: keep-alive

这里有params的身体

username=AWFcJ...FsdE:EFCK..Dfr43d
grant_type=client_credentials

在用户名中,我从仪表板中输入了我的客户端ID和密码。

回复是

400 Bad request. 
error:invalid_client
eror_description:Client credentials are missing

我做错了什么?请帮帮我

2 个答案:

答案 0 :(得分:0)

嗨,你的做法是正确的

试试这个

  public string clientId=<your client id>;
  public string secret=<your secret>;
  public string accessToken='';

  public void accessToken()
  {
      string input=clientId+':'+secret;
      Blob myBlob = Blob.valueof(input);
      string paramvalue = EncodingUtil.base64Encode(myBlob);
      Http http=new Http();
      HttpRequest req=new HttpRequest();
      req.setMethod('POST');
      string endpoint='https://api.sandbox.paypal.com/v1/oauth2/token?grant_type=client_credentials';
      req.setEndpoint(endpoint);
      req.setHeader('Authorization','Basic '+paramvalue);
      req.setHeader('Accept','application/json');
      req.setHeader('content-type','application/x-www-form-urlencoded');
      req.setHeader('Accept-Language','en_US');
      req.setHeader('Cache-Control','no-cache');
      req.setBody('grant_type=client_credentials');
      HttpResponse res = new HttpResponse();
      res = http.send(req);
      if(res.getStatusCode()==200)
      {
           Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
           accessToken = (string)results.get('access_token');
           system.debug(accessToken);
      }



  }

答案 1 :(得分:0)

您可以尝试一下,PayPalConfigDto包含一些您需要提供的基本内容。请记住,这些值应存储在应用程序的应用程序设置文件中,这只是一个简单的示例:

public class PayPalConfigDto
{
    public string BaseUrl { get; set; }

    public string TokenUrl => $"{BaseUrl}/v1/oauth2/token";

    public string ClientId { get; set; }

    public string ClientSecret { get; set; }
}

PayPal API响应对象:

public class TokenDto
{
    public string Scope { get; set; }

    public string Access_token { get; set; }

    public string Token_type { get; set; }

    public string App_id { get; set; }

    public string Expires_in { get; set; }

    public string Nonce { get; set; }
}

PayPalContext类:

public class PayPalContext
{
    private HttpClient _httpClient;

    private PayPalConfigDto _payPalConfig;

    public PayPalContext(HttpClient httpClient, PayPalConfigDto payPalConfig)
    {
        _httpClient = httpClient;
        _payPalConfig = payPalConfig;
    }

    public virtual async Task<string> GetToken()
    {
        var url = $"{_payPalConfig.TokenUrl}?grant_type=client_credentials";
        _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
            Convert.ToBase64String(Encoding.ASCII.GetBytes($"{_payPalConfig.ClientId}:{_payPalConfig.ClientSecret}")));

        var responseTask = _httpClient.PostAsync(url, null);
        responseTask.Wait();
        var response = responseTask.Result;

        var result = await response.Content.ReadAsStringAsync();
        if (!response.IsSuccessStatusCode)
        {
            var errorMessage = response.ToString();
            throw new Exception($"An issue occurred during the trial of getting PayPal token. {errorMessage}");
        }
        var tokenDto = JsonConvert.DeserializeObject<TokenDto>(result);

        return tokenDto.Access_token;
    }

}

GetToken方法需要对凭据进行编码,并基于this answer 您可以使用

轻松完成此操作
new AuthenticationHeaderValue("Basic",
            Convert.ToBase64String(Encoding.ASCII.GetBytes($"{_payPalConfig.ClientId}:{_payPalConfig.ClientSecret}")));

要测试所有内容,您可以创建一个简单的测试类,例如:

//[Ignore]
public class PayPalContextTests
{
    readonly PayPalConfigDto PayPalConfig = new PayPalConfigDto()
    {
        BaseUrl = "https://api.sandbox.paypal.com",
        ClientId = "your ClientId",
        ClientSecret = "your ClientSecret"
    };

    [Test]
    public async Task Should_return_valid_token()
    {
        var httpClient = new HttpClient();           
        var context = new PayPalContext(httpClient, PayPalConfig);
        var token = await context.GetToken();
        Assert.IsFalse(string.IsNullOrEmpty(token));
    }
}

我还认为this可以帮助您通过邮递员获得令牌,这是您可以在the main PayPal documentation中找到的东西的提示