JAVA获取用户openid
下面展示一些 内联代码片
。
@ApiOperation("获取微信小程序的openid")
@RequestMapping(value="/openid" ,method= RequestMethod.GET )
public Result<?> getOpenid(@RequestParam(name = "code") String code,//机器码
@RequestParam(name = "appid") String appid,
@RequestParam(name = "secret") String secret
) {
String params = "appid=" + appid + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code";
String url = "https://api.weixin.qq.com/sns/oauth2/access_token" ;
//发送请求
String sr = HttpRequest.sendGet(url, params);
//解析相应内容(转换成json对象)
JSONObject json = JSONObject.parseObject(sr);
//获取 refresh_token 进行获取openid
String refresh_token = json.getString("refresh_token");
String params2 = "appid=" + appid +"&grant_type=refresh_token&refresh_token="+refresh_token;
String url2 = "https://api.weixin.qq.com/sns/oauth2/refresh_token";
String sr2 = HttpRequest.sendGet(url2, params2);
JSONObject json2 = JSONObject.parseObject(sr2);
//用户的唯一标识(openid)
String openid = (String) json2.get("openid");
return Result.ok(openid);
}