网站添加微信登录功能

来源:互联网 发布:沈阳淘宝代运营 编辑:程序博客网 时间:2024/05/14 18:05
/**微信扫二维码登录*///1、首页登录按钮html<a class="loginLink"><button class="btn btn-primary">登录</button></a>//2、登录按钮链接js$('.loginLink').attr('href', 'src/index.html#/access/signin/0');//3、路由跳转到signin.html js.state('access.signin', {    url: '/signin/{inOrUp}',    templateUrl: 'tpl/security/signin.html',    resolve: {        deps: ['uiLoad','$ocLazyLoad',            function (uiLoad, $ocLazyLoad) {                //return $ocLazyLoad.load('toaster')                //    .then( function(){                        return uiLoad.load(['js/app/security/controllers/signin.js'])                    //}                //);            }        ]    }})//4、微信登录按钮signin.html<button title="微信登录"  ng-click="goThirdPartyLogin()"></button>//5、微信登录按钮链接js$scope.goThirdPartyLogin = function(){    window.location = 服务器地址 + "/service/oauth2/weixinAuth";}//参考微信开发文档(https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419316505&token=&lang=zh_CN)//第一步:请求CODE//6、链接访问,后台返回第一个微信链接java    @RequestMapping(value="/oauth2/weixinAuth", method=RequestMethod.GET)    public void beginWeixinAuthenticate(HttpServletRequest request, HttpServletResponse response) throws IOException {        String state = RandomStateGenerator.generate(request);        response.setContentType("text/html;charset=utf-8");        request.getSession().setAttribute(                OAuth2WeixinResourceManager.WEIXIN_STATE_KEY, state);        response.sendRedirect(new WeixinOAuth().authorizeCodeURL(state));    }    //第一个微信链接WeixinOAuth.java    public String authorizeCodeURL(String state) {        return WeixinConfig.get("authURL").trim() + "?appid="                    + WeixinConfig.get("client_ID").trim() + "&redirect_uri="                    + WeixinConfig.get("redirect_URI").trim()                    + "&response_type=code&scope=" + WeixinConfig.get("auth_SCOPE").trim()                    + "&state=" + state;    }    /*        第一个微信链接样式 https://open.weixin.qq.com/connect/qrconnect?appid=wcfhsa30347e&redirect_uri=http://www.xxx.com/src/index.html%23/oauth_weixin&response_type=code&scope=snsapi_login,snsapi_userinfo&state=b55tqaferhdrAffdae24f26d09        此时打开二维码,用户扫描并且授权后,将会重定向到redirect_uri的网址上,并且带上code和state参数        重定向链接样式https://www.tubiaoxiu.com/src/index.html#/oauth_weixin?code=021dzgBA1dMagsdegdahragdzgBl&state=b55tqaferhdrAffdae24f26d09    *///第二步:通过code获取access_token//7、上一步重定向链接路由js    .state('oauth_weixin', {                    url: '/oauth_weixin',                    templateUrl: 'tpl/security/oauth_weixin_page.html',                    resolve: {                        deps: ['uiLoad','$ocLazyLoad',                            function (uiLoad, $ocLazyLoad) {                                //return $ocLazyLoad.load('toaster')                                //    .then( function(){                                        return uiLoad.load(['js/app/security/controllers/oauth_weixin.js'])                                    //}                                //);                            }                        ]                    }                })//8、路由指向的oauth_weixin.js        var reqPostCode = {            method: 'POST',            url: charts_server + '/oAuth2Login/weixin',            headers: {                'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'            },            data: param    }    var reqGetUserInfo = {            method: 'GET',            url: charts_server + '/service/user/info',            headers: {                'Content-Type': 'text/plain;charset=utf-8'            }    }    $scope.registerWithWeixin = function () {        $http(reqPostCode).then(function (response) {                          // 8.1 向后台发送请求,链接为 charts_server + '/oAuth2Login/weixin' + code                $http(reqGetUserInfo).then(                    function (response) {                        if (response.data.error) {                            $scope.isAuthSucceed = false;                        } else {                            $rootScope.userinfo.basic = response.data.object.basic;                            $rootScope.userinfo.contact = response.data.object.contact;                            $rootScope.userinfo.avatar = response.data.object.avatar;                            $rootScope.userinfo.limit = response.data.object.limit;                            $rootScope.userinfo.isLogin = true;                            $rootScope.userinfo.email = response.data.object.email;                            Idle.watch();                            if (window.parent !== window) {                                localStorage.setItem('ngStorage-userinfo', JSON.stringify($rootScope.userinfo));                                // 如果不是在顶层窗口中,需要向父窗口发消息,目前仅用于站内分享                                window.parent.postMessage('LOGIN_SUCCESS', local_server);                            } else {                                $state.go('app.charting_resource');   //8.2 登录成功后跳转到charts_server + '#/app/charting_resource'                            }                        }                    }, function (x) {                        toaster.pop('error', '', '跳转失败,请重新尝试');                        $scope.isAuthSucceed = false;                        $state.go('access.signin');                    }                );        }, function (error) {            toaster.pop('error', '', '跳转失败,请重新尝试');            $scope.isAuthSucceed = false;            $state.go('access.signin');        })    }//9、第三方登录验证过滤器    private static final String LOGIN_PATH = "/oAuth2Login/*";    if (request.getRequestURI().endsWith("weixin")) {            return doWeixinLogin(request, response);    }    protected Authentication doWeixinLogin(HttpServletRequest request,            HttpServletResponse response) {        String authCode = obtainAuthorizationCode(request);        if (authCode == null) {            throw new AuthenticationCredentialsNotFoundException("Weixin authentication code not exist.");        }        if (!RandomStateGenerator.isFromThis(authCode, RandomStateGenerator.STATE_AUTH)) {            checkState(request, OAuth2WeixinResourceManager.WEIXIN_STATE_KEY);  //检查state,防止csrf攻击(跨站请求伪造攻击)        }        CSOAuth2AuthorizationCodeAuthenticationToken token = new CSOAuth2AuthorizationCodeAuthenticationToken(                authCode, OAuth2ProviderType.WEIXIN);        // Allow subclasses to set the "details" property        setDetails(request, token);        return this.getAuthenticationManager().authenticate(token);    }//10、第8步中的路由app.charting_resource js    .state('app.charting_resource', {        url : '/charting_resource',        templateUrl : 'tpl/charting/resource.html',        resolve: {            deps: ['$ocLazyLoad',                function ($ocLazyLoad) {                    //return  $ocLazyLoad.load('toaster')                    //    .then(function(){                            return $ocLazyLoad.load(                                [                                    'js/app/misc/update_info_modal/modal.js',                                    'js/app/misc/update_info_modal/modal.css'                                ]);                        //});                }]        }    })
原创粉丝点击