微信受权登陆。和其它受权相似,须要去官方渠道注册开发者帐号,微信受权登陆须要到微信公众平台申请.html
假设获取到了公众平台appid。json
和扫码相似,进入微信指定的一个连接。后端
可是受权登陆是先直接访问微信指定的页面。(扫码是从本身页面跳转到指定微信连接,再回调本身页面。受权是直接从指定的连接地址跳转回本身指定页面)api
先上代码:微信
var param=location.href.split("?")[1]; //wechat var url=encodeURIComponent("http://h5.laikanxing.com/h5-crowd/html/wechat.html?"+param); window.location.href="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxadc302736fea5abf&redirect_uri="+ url+"&response_type=code&scope=snsapi_userinfo&"+param+"#wechat_redirect";
param:须要带回的参数。app
url:回调页面。(公众平台注册的域)微信公众平台
以上步骤能够从前台跳转,能够从后端进行转发。看我的业务需求。url
当用户确认受权登陆之后,微信从定向到指定回调页面,而且url后拼接了换取用户信息的code。spa
拿到code之后,和网页扫码登陆同样,进行几步交换(必须后台进行)。code
后台Java代码:
/** * activity * * @param user * @return */ @RequestMapping(value = "/get/h5/wechat/{code}", method = RequestMethod.GET, produces = "application/json") @ResponseBody public LoginResultJSON getWechatUserInfo(@PathVariable("code") String code) { String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxadc302736fea5abcf&secret=11241d710a5726a57e6ebd2dfd98b0bf&code="+code+"&grant_type=authorization_code"; String result=RequestUtil.get(url); JSONObject jsonObject=new JSONObject(result); String access_token=jsonObject.getString("access_token"); String openid=jsonObject.getString("openid"); url="https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid; result=RequestUtil.get(url); jsonObject=new JSONObject(result); ThirdPartyUserLoginInfoJSON json=new ThirdPartyUserLoginInfoJSON(); json.setDeviceId(null); json.setDeviceSystem(null); json.setHeadUrl(jsonObject.getString("headimgurl")); json.setNickname(jsonObject.getString("nickname")); json.setSourceType(2); json.setUniqId(jsonObject.getString("openid")); return userService.thirdPartyLogin(json); }
具体换取解释,请看上篇。第三方登陆集合