微信测试号实现个人第三方PC端网站二维码登录(代码实现篇)

我页面使用了生成二维码的js,是网上拿到的(太多转载,具体作者是啥不知道(#^.^#))

点击打开生成二维码js链接  直接复制js就OK。

好,正文来啦,我代码中是使用了springboot(SSM)+redis+shiro。。。

页面代码:

<!DOCTYPE html>
<html lang="zh_CN" xmlns:th="http://www.thymeleaf.org"
				xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta charset="UTF-8"/>
    <title>微信登录二维码</title>
    <script src='/js/jquery-2.0.3.min.js'></script>
    <script src="/js/qrcode.js"></script>
    <script type="text/javascript">
    /*<![CDATA[*/
    
    function checkLogin(){
    	var i = 0;
    	var sessionId = $("#sessionId").val();
    	if(sessionId!=""){
    		$.ajax({
                url: "/wechat/polling",
                type: "POST",
                data:{sessionId:sessionId},
                success: function (data) {
                	if(data.status=="200"){
                		window.clearInterval(c);
                		alert(data.message);
                		location.href = "/";
                	}else{
                		i++;
                		if(i>60){
                			window.clearInterval(c);
                			alert("二维码已失效!请刷新二维码。");
                		}
                	}
                }
        	});
    	}
    }
    
    function wechatLogin(){
    	$.ajax({
            url: "/wechat/wxLoginPage",
            type: "POST",
            success: function (data) {
            	$("#sessionId").val(data.sessionId);
            	
            	var qrcode = new QRCode(document.getElementById("code"), {
                    width : 200,//设置宽高
                    height : 200
                });
                qrcode.makeCode(data.uri);
                c = setInterval(checkLogin,5000);//轮询查询
            }
    	});
    }
    /*]]>*/
    </script>
</head>
<body>
	<shiro:guest>
		<input type="button" value="微信登录" onclick="wechatLogin()" />
	</shiro:guest>
	<shiro:user>
		<shiro:principal property="username" />您已登录。
	</shiro:user>
	
	<input type="hidden" id="sessionId"/>
	<br/><br/><br/><br/>
	<div id="code"></div> 
</body>
</html>

后台controller(@RequestMapping("/wechat"))代码:

//pc点击微信登录,生成登录二维码
    @RequestMapping(value = "/wxLoginPage",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,String> wxLoginPage(HttpServletRequest request) throws Exception {
    	String sessionId = request.getSession().getId();
    	logger.info("sessionId:"+sessionId);
        String uri = weChatAuthService.getAuthorizationUrl("pc",sessionId);//设置redirect_uri和state=sessionId以及测试号信息,返回授权url
        logger.info(uri);
        Map<String,String> map = new HashMap<String,String>();
        map.put("sessionId", sessionId);
        map.put("uri", uri);//用来前端生成二维码
        return map;
    }
    
    //扫描二维码授权成功,取到code,回调方法
    @RequestMapping(value = "/pcAuth")
    @ResponseBody
    public String pcCallback(String code,String state,HttpServletRequest request,HttpServletResponse response) throws Exception {
        String result = weChatAuthService.getAccessToken(code);//根据code获取access_token和openId,不懂看微信文档
        JSONObject jsonObject = JSONObject.parseObject(result);
        
        //String refresh_token = jsonObject.getString("refresh_token");
        String access_token = jsonObject.getString("access_token");
        String openId = jsonObject.getString("openId");
        
        logger.info("------------授权成功----------------");
        JSONObject infoJson = weChatAuthService.getUserInfo(access_token,openId);//根据token和openId获取微信用户信息,不懂看我上一篇文章开始分享的链接
        if(infoJson!=null){
        	String nickname = infoJson.getString("nickName");
            logger.info("-----nickname-----"+nickname);
            logger.info("-----sessionId-----"+state);
            infoJson.put("openId", openId);
            redisTemplate.opsForValue().set(state, infoJson, 10*60, TimeUnit.SECONDS);
            return "登录成功!";
        }
	    return "登录失败!";
    }
//轮询查询key
    @RequestMapping(value="/polling",method=RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> polling(String sessionId,HttpServletRequest request,HttpServletResponse response){
    	Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
    	
    	if(redisTemplate.hasKey(sessionId)){
    		JSONObject infoJson = (JSONObject)redisTemplate.opsForValue().get(sessionId);
    		redisTemplate.opsForValue().getOperations().delete(sessionId);
    		String openId = (String)infoJson.get("openId");
    		//根据openId判断我们网站是否存在该用户,数据库用户表会保存用户
            User user = userService.selectUserByWechat(openId);
            if (user == null) {
            	String nickname = (String)infoJson.get("nickName");
            	String sex = (String)infoJson.get("sex");
            	User newuser = new User();
            	newuser.setSex(sex);
            	newuser.setWechat(openId);
            	newuser.setNickname(nickname);
            	int i = userService.insertUser(newuser);//新增用户
            	if(i<1){
            		resultMap.put("status", 500);
        	        resultMap.put("message", "登录失败:");
        	        return resultMap;
            	}
            }
            //登录操作
    	    try {
    	    	UsernamePasswordToken token = new UsernamePasswordToken(openId, openId);//这里是用shiro登录,反正该openId已经微信扫码验证
    	        SecurityUtils.getSubject().login(token);
    	        resultMap.put("status", 200);
    	        resultMap.put("message", "登录成功");
    	        
    	        //更新用户最后登录时间
    	        Subject  currentUser = SecurityUtils.getSubject(); 
    			User luser = (User) currentUser.getPrincipal();
    	        User user1 = new User();
    	        user1.setId(luser.getId());
    	        user1.setLastLogDate(new Date());
    	        userService.updateUserByIdSelective(user1);//更新用户方法
    	        
    	        
    	    } catch (Exception e) {
    	        resultMap.put("message", "未知系统错误:" + e.getMessage());
    	    }
    	    return resultMap;
    	}else{//not has key
    		resultMap.put("status", 0);
    		return resultMap;
    	}
    }

上一篇文章《微信测试号实现个人第三方PC端网站二维码登录》

到这里就可以实现微信二维码登录我们的个人网站啦~~~~~






阅读更多
上一篇微信测试号实现个人第三方PC端网站二维码登录
下一篇js生成二维码
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭