本文共 2254 字,大约阅读时间需要 7 分钟。
1、以snsapi_base为scope发起的网页授权,是用来获取进入页面的用户的openid的,并且是静默授权并自动跳转到回调页的。用户感知的就是直接进入了回调页(往往是业务页面)
2、以snsapi_userinfo为scope发起的网页授权,是用来获取用户的基本信息的。但这种授权需要用户手动同意,并且由于用户同意过,所以无须关注,就可在授权后获取该用户的基本信息。https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html
根据上述官方文档实现第一步,用户同意授权,获取code。
前端主动跳转到下面的连接地址,改地址会从微信服务器获取到code,这个code是后面换取token的凭证。
微信处理完后回跳转回调redirect_uri/?code=CODE&state=STATE。,这个url通常对应spring controller层的接口。https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx73a924c42a171243&redirect_uri=http%3a%2f%2fbis.beyandtech.com%2fsales%2fwx%2fwxpreReg&response_type=code&scope=snsapi_userinfo&state=shba01,e2c028b7063f498ba3388ec0cb2e6bdf,0,0#wechat_redirect
后端接口收到微信服务器的回调请求,处理code和state参数。code作用是获取token进而获取用户信息,state可以用来定义其他参数(逗号可以分割多个参数,后端解析)
授权过程一共四部,我们只是建议从第二部开始由后端完成。
@GetMapping("/sales/wx/wxpreReg") public String wxpreReg( String code,String state) { logger.info("wxpreReg:code={},state={}",code,state); String arr[] = state.split(","); Long pathIda = wxService.wxpreReg(code,arr[0],arr[1],arr[2], Long.valueOf(arr[3])); String parms= "parm1="+arr[0]+"&parm2="+arr[1]+"&parm3="+pathIda+"&oauth=1"; return "redirect:https://xxx.xxxxxx.com/index.html/#/pages/login/login?"+parms; }
private static String ACCESSTOEKN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=xxxxx&secret=xxx&code=CODE&grant_type=authorization_code";private static String USERINFO_URL = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";public JSONObject getUserInfo(String code){ String url = ACCESSTOEKN_URL.replaceAll("CODE",code); String jsonstr = restTemplate.getForObject(url,String.class); JSONObject jsonObject =JSONObject.parseObject(jsonstr); System.out.println(jsonstr); String url1 = USERINFO_URL.replaceAll("ACCESS_TOKEN",jsonObject.getString("access_token")) .replaceAll("OPENID",jsonObject.getString("openid")); String jsonstr1 = restTemplate.getForObject(url1,String.class); System.out.println(jsonstr1); return JSONObject.parseObject(jsonstr1);}
以上就完成了H5页面授权,获取用户信息,并且重定向页面到原来页面,附加参数oauth=1,前端识别后就可以判断是否授权了
转载地址:http://qhtm.baihongyu.com/