美国流行的第三方支付dwolla,支持所有美国的主流银行。
对接Dwolla的第一步就是要获取注册应用的访问令牌。之后的每个接口都需要该令牌
由于 dwolla-swagger-java 这个库三年前由于开发团队缺少维护,所以从Dwolla的支持库里删除了,这给用java对接的人员带来了不小的麻烦。比如今天要说的获取令牌这一步。
首先注册一个沙盒账号用于测试,
接下来按照官方提供的接口说明,需要这些参数
POST https://api-sandbox.dwolla.com/token
Content-Type: application/x-www-form-urlencoded
Authorization: Basic base64编码后的client_id:client_secret
client_id: 就是控制面板中看到的key
client_secret: 就是控制面板中看到的secret
grant_type:client_credentials
这个接口通过postman测试没有问题,但通过代码测试就一直报,明明参数和postman设置的一样
{"code":"InvalidCredentials","message":"Missing or invalid Authorization header."}
后来通过Dwolla社区这个问题找到了解决方法
https://discuss.dwolla.com/t/authorization-api-not-working/6234
总结起来就是grant_type:client_credentials传错了,要传grant_type=client_credentials
直接上代码
public String getAccess() {
RequestBuilder requestBuilder = RequestBuilder.post();
// 设置body
requestBuilder.setEntity(new StringEntity("grant_type=client_credentials", "UTF-8"));
// 设置header
setRequestHeader(TOKEN_URL, requestBuilder, "application/x-www-form-urlencoded", null);
HttpUriRequest request = requestBuilder.build();
CloseableHttpResponse response = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
// 执行请求
response = httpClient.execute(request);
} catch (IOException e) {
StringBuilder error = new StringBuilder();
error.append("IOException when httpClient execute request![url=");
error.append(TOKEN_URL);
error.append("] - ");
if (e != null)
error.append(e.getMessage());
System.out.println(error);
}
String resultStr = null;
try {
// 解析返回
resultStr = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println(resultStr);
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
return resultStr;
}
private void setRequestHeader(String url, RequestBuilder requestBuilder, String contentType, String authHeader) {
requestBuilder.addHeader("Content-Type", contentType);
requestBuilder.addHeader("Accept", "*/*");
requestBuilder.setUri(url);
if (authHeader == null) {
String s = CLIENT_ID + ":" + CLIENT_SECRET;
String base64String = null;
try {
base64String = Base64.getEncoder().encodeToString(s.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
requestBuilder.addHeader("Authorization", "Basic " + base64String);
} else {
requestBuilder.addHeader("Authorization", "Bearer " + authHeader);
}
}
推荐使用官方提供的Postman集合进行编码过程的参考。点击“Run in Postman”会有帮助的
https://discuss.dwolla.com/t/using-postman-to-explore-and-debug-dwollas-v2-api/2758