微信公众号网页授权
- 准备工作
- 网页授权
准备工作
登录微信公众平台,启用“服务器配置”并添加相关配置
(1)代码中加入token校验的验证,这时可正确配置服务器,如下图:
其中url和token值要相对应。
@GetMapping("/wechat/security/")public void connectWeixin(HttpServletRequest request, HttpServletResponse response) throws IOException {PrintWriter print;String signature = request.getParameter("signature");String timestamp = request.getParameter("timestamp");String nonce = request.getParameter("nonce");String echostr = request.getParameter("echostr");log.info("\n[signature=" + signature+ "][timestamp=" + timestamp+ "][nonce=" + nonce+ "][echostr=" + echostr+ "][token=" + token + "]");// 通过检验signature对请求进行校验,若校验成功则原样返回echostr,表示接入成功,否则接入失败if (signature != null && SignUtil.checkSignature(signature, timestamp, nonce)) {try {print = response.getWriter();print.write(echostr);print.flush();print.close();log.info("wechat auth success...");} catch (IOException e) {e.printStackTrace();}} else {log.info("wechat auth failure...");}}
(2)将服务器ip加入IP白名单,以便之后调用获取access_token接口,如下图:
(3)设置网页授权域名,如下图:
网页授权
这里采用的是静默授权,用户感知的就是直接进入了回调页(往往是业务页面),具体可参照微信公众号开发文档: https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html
@RequestMapping("/wechatLogin")@ApiIgnorepublic void wechatLogin(Model model, HttpServletResponse response) {//第一步:引导用户进入授权页面同意授权,获取codetry {System.out.println("微信网页授权");String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid +"&redirect_uri=" + urlEncodeUTF8(http) +"&response_type=code" +"&scope=snsapi_base" +"&state=STATE#wechat_redirect";//授权页面地址//重定向到授权页面response.sendRedirect(url);} catch (Exception e) {e.printStackTrace();}}
用户同意授权,可获取code; 在回调页面,通过code换取网页授权access_token以及openId
非静默授权下还可获取用户的信息,这里不做过多介绍,根据开发文档接口即可,到这里微信公公众号的网页授权就算成功了,下面可以进行实际业务逻辑了。