您的位置:首页 > 移动开发 > 微信开发

微信开发---------------------------网页授权获取用户openId

2018-03-13 17:45 986 查看
微信官方开发文档:点击打开链接
其实官方文档说的比较清楚,整个开发过程也比较简单,但是这里必须吐槽一下,网页授权需要域名,而且必须是备了案的,弄域名备案,然后域名解析,再到项目部署到服务器80端口下,虽然遇到的坑有点多,不过本菜鸟还是学到了许多知识,对于网站开发和建设有了进一步的了解。下面上本篇主题。
首先去设置授权回调域名,在公众号设置--功能设置--网页授权域名设置



域名设置成功后,就可以去取openId了,如果设置失败,一般是域名没备案或者下载存放的那个文件放的位置有问题。

网页授权有两种类型分别是静默授权和确认授权,一个是需要用户点击确认的,一个不需要直接跳转,我只需要取openId,
用静默授权就行,其它更多详细信息请查看官方文档,下面上我取openId的步骤和代码。

1.在自定义菜单那里设置url
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
注意APPID别写错,然后特殊字符url传参需要转义,重定向的uri填你接收的接口地址
2.接口里面获取微信服务器传过来的code,然后用code去取openId
获取code后,请求以下链接获取:https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
请求成功返回的正确数据:
{ "access_token":"ACCESS_TOKEN",
"expires_in":7200,
"refresh_token":"REFRESH_TOKEN",
"openid":"OPENID",
"scope":"SCOPE" }
这里的access_token和调用微信相关接口所需要的的access_token不一样。下面代码
这个请求地址应与你所重定向的地址一致/**
* 微信网页授权获取用户openId,先取到code然后用code去取openId
* @param req
*/
@RequestMapping("/wxOAuth")
public ModelAndView wxOAuth(HttpServletRequest req){
ModelAndView mv = new ModelAndView();
String code = req.getParameter("code");
log.info("code:" + code);
try {
String openId = wxService.getOpenId(code);
mv.addObject("oppenId", openId);
} catch (Exception e) {
e.printStackTrace();
log.error(e.getMessage(),e);
}
return mv;
}获取到code后,用get请求https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code地址,响应正确的话就可以取得openId
@Override
public String getOpenId(String code) throws Exception {
String openId = "";
String requestUrl = WxConstants.GET_OPENID_URL.replace("APPID", WxConstants.APP_ID)
.replace("SECRET", WxConstants.APP_SECRET).replace("CODE", code);
log.info("请求地址:" + requestUrl);
String result = HttpUtil.sendGet(requestUrl);
if(result != null){
JSONObject jsonResult = JSONObject.parseObject(result);
openId = jsonResult.getString("openid");
log.info("oppid:" + openId);
}
return openId;
}
public static String sendGet(String Url){
String result = null;
HttpClient hc = new HttpClient();
hc.getHttpConnectionManager().getParams().setConnectionTimeout(1000 * 5); // 链接超时5秒
hc.getHttpConnectionManager ().getParams().setSoTimeout(1000 * 5); // 读取超时5秒
GetMethod get = new GetMethod(Url);
try {
int code = hc.executeMethod(get);
log.info("请求认证返回码:" + code);
} catch (HttpException e) {
log.error(e.getMessage());
} catch (IOException e) {
log.error(e.getMessage());
}
try {
result = get.getResponseBodyAsString();
log.info("请求返回结果:" + result);
} catch (IOException e) {
log.error(e.getMessage());
}finally{ //释放连接资源
if(get != null){
get.releaseConnection();
hc.getHttpConnectionManager().closeIdleConnections(0);
}
}
return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  微信网页授权