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

时间:2013-10-09 21:40:51

标签: rest paypal jersey-client

我正在尝试让这个工作https://developer.paypal.com/webapps/developer/docs/integration/direct/make-your-first-call/ 使用Java + Jersey应用程序。好像我在POST params中遗漏了一些东西。

public String getPaypalToken() {
    Client client = Client.create();
    WebResource webResource = client.resource("https://api.sandbox.paypal.com/v1/oauth2/token");
    MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
    queryParams.add("username", CLIENT_ID + ":" + SECRET );
    queryParams.add("grant_type", "client_credentials");
    ClientResponse response = webResource.accept("application/json").acceptLanguage("en_US").type("application/x-www-form-urlencoded").post(ClientResponse.class, queryParams);
    return response.toString();
}

使用我之前得到的代码:POST https://api.sandbox.paypal.com/v1/oauth2/token返回的响应状态为401 Unauthorized。

此CURL命令行选项可以正常工作:

curl -X POST https://api.sandbox.paypal.com/v1/oauth2/token  -H "Accept: application/json"  -H "Accept-Language: en_US"  -u "EOJ2S-Z6OoN_le_KS1d75wsZ6y0SFdVsY9183IvxFyZp:EClusMEUk8e9ihI7ZdVLF5cZ6y0SFdVsY9183IvxFyZp"  -d "grant_type=client_credentials"

任何建议将不胜感激。 学家

2 个答案:

答案 0 :(得分:1)

curl中的-u选项发送base64编码的“username:password”字符串。我不认为在queryParams地图中添加客户端ID /秘密也是一样的(除非泽西以不同的方式对待'用户名'键,我不认为它。)

你应该尝试

webResource.header(“授权”,“基本”+ Base64.encode(CLIENT_ID +“:”+ SECRET.getBytes()))

答案 1 :(得分:1)

Just sharing my solution:

Dictionary<string, string> sdkConfig = new Dictionary<string, string>();
sdkConfig.Add("mode", "sandbox");

string clientid = "<your client id>";
string secretid = "<your secret id>";
string accessToken = new OAuthTokenCredential(clientid, secretid, sdkConfig).GetAccessToken();

I previously encountered unauthorized response using RestSharp, then found this. I'm using paypal .net sdk from nuget package. Reference.