java 后端获取支付宝小程序openid
@PostMapping("/getOpenidZFBSIX")
@CrossOrigin
@ResponseBody
public Map<String,Object> getOpenidZFBSIX(@RequestBody byte[] req)
{
HashMap<String, Object> objectObjectMap = new HashMap<>();
JSONObject json = JSONObject.parseObject(new String(req, Charset.forName("UTF-8")));
System.out.println("请求参数"+json);
String code = json.get("code").toString();
String openId=null;
//使用支付宝小程序的固定方法获取auth_code
if(code==null||code.length()==0) {
objectObjectMap.put("status","9995");
objectObjectMap.put("resMsg","code不能为空");
return objectObjectMap;
}else {
//String serverUrl, String appId, String privateKey, String format,String charset, String alipayPublicKey, String signType
//实例化客户端 参数:正式环境URL,Appid,应用私钥 PKCS8格式,字符编码格式,字符格式,支付宝公钥,签名方式
AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",wxspAppid,privateKey,"json","UTF-8",publicKey,"RSA2");
AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
// 值为authorization_code时,代表用code换取
request.setGrantType("authorization_code");
//授权码,用户对应用授权后得到的
request.setCode(code);
//这里使用execute方法
AlipaySystemOauthTokenResponse response = null;
try {
response = alipayClient.execute(request);
} catch (AlipayApiException e) {
throw new RuntimeException(e);
}
//刷新令牌,上次换取访问令牌时得到。见出参的refresh_token字段
request.setRefreshToken(response.getAccessToken());
//返回成功时 就将唯一标识返回
if(response.isSuccess()){
System.out.println("调用成功"+response.getUserId());
System.out.println("调用成功");
//我这里只返回了一个字段给前端用
openId=response.getOpenId();
} else {
}
}
System.out.println("+-----------"+openId.toString());
}