微信授权code和openid都从服务端处理并拿到,但是现在想往前端传openid,前端怎么通过异步请求拿到openid.
有没有什么办法可以处理,是要在redirect_uri这个地址里填前端页面?
代码如下:
@RequestMapping(value = "/getCode", method = RequestMethod.GET)
public String getCode(HttpServletRequest request) {
String url = "";
try {
// 第一步:用户同意授权,获取code
url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid
//这个backUrl的域名必须要进行再公众号中进行注册验证,这个地址是成功后的回调地址,在配置文件配置
+ "&redirect_uri="+URLEncoder.encode(backUrl, "UTF-8")
+ "&response_type=code"
+ "&scope=snsapi_base"
+ "&state=STATE#wechat_redirect";
log.info("forward重定向地址{" + url + "}");
} catch (Exception e) {
e.printStackTrace();
}
return "redirect:"+url;//必须重定向,否则不能成功
}
//回调函数
@RequestMapping("/goWxCallBack")
public @ResponseBody String goWxCallBack(HttpServletRequest request) {
String openid = "";
try {
String code = request.getParameter("code");
log.info("code:"+code);
Map<String, String> params = new HashMap();
params.put("secret", appsecret);
params.put("appid", appid);
params.put("grant_type", "authorization_code");
params.put("code", code);
String result = HttpUtils.httpRequestToString(
"https://api.weixin.qq.com/sns/oauth2/access_token", params);
log.info("返回结果:"+result);
//解析result
if (result != null) {
JSONObject object = (JSONObject) JSON.parse(result);
openid = object.getString("openid");
log.info("openid:"+openid);
}
} catch (Exception e) {
e.printStackTrace();
}
return openid;
}