Java实现支付宝用户授权,获取用户信息:
/***
* 支付宝用户授权,获取用户信息
* @author Mark
* @param code
* @return
*/
public static UserInfo getALiPayUserInfo(String code) {
UserInfo info = null;
//根据code获取accessToken
AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
"你的APPID", "你的支付宝私钥", "json",
"GBK", "你的支付宝公钥", "RSA2");
AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
request.setGrantType("authorization_code");
request.setCode(code);
request.setRefreshToken("201208134b203fe6c11548bcabd8da5bb087a83b");
AlipaySystemOauthTokenResponse response = null;
try {
response = alipayClient.execute(request);
} catch (AlipayApiException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (response.isSuccess()) {
//根据accessToken获取用户信息
AlipayClient alipayClients = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
"你的APPID", "你的支付宝私钥", "json",
"GBK", "你的支付宝公钥", "RSA2");
AlipayUserInfoShareRequest req = new AlipayUserInfoShareRequest();
AlipayUserInfoShareResponse res = null;
try {
res = alipayClients.execute(req, response.getAccessToken());
} catch (AlipayApiException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (res.isSuccess()) {
info = new UserInfo();
info.setUserId(res.getUserId());
info.setAvatar(res.getAvatar());
info.setProvince(res.getProvince());
info.setCity(info.getCity());
info.setNickName(res.getNickName());
info.setIsStudentCertified(res.getIsStudentCertified());
info.setUserType(res.getUserType());
info.setUserStatus(res.getUserStatus());
info.setIsCertified(res.getIsCertified());
info.setGender(res.getGender());
return info;
} else {
info = new UserInfo();
return info;
}
} else {
info = new UserInfo();
return info;
}
}