微信公众号第三方h5页面登录

admin3年前公众号&小程序551

官方文档:https://developers.weixin.qq.com/doc/oplatform/Website_App/WeChat_Login/Wechat_Login.html

参考文档:https://www.cnblogs.com/jj0219/p/10436664.html


1.先注册https://open.weixin.qq.com/,获取开放平台app_id和app_secret

2.公众号自动登录和PC端扫码登陆如果要统一账号,那需要到开放平台绑定下公众号

 //生成扫码登录的URL    private function qrconnect($redirect_url, $scope, $state = NULL)    {        $WeChatLoginConfig = !empty($this->usersConfig['wechat_login_config']) ? unserialize($this->usersConfig['wechat_login_config']) : [];                $url = "https://open.weixin.qq.com/connect/qrconnect?appid=" . $WeChatLoginConfig['open_appid'] . "&redirect_uri=" . urlencode($redirect_url) . "&response_type=code&scope=" . $scope . "&state=" . $state . "#wechat_redirect";        return $url;    }            //生成OAuth2的Access Token    private function oauth2_access_token($code)    {        $WeChatLoginConfig = !empty($this->usersConfig['wechat_login_config']) ? unserialize($this->usersConfig['wechat_login_config']) : [];                $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $WeChatLoginConfig['open_appid'] . "&secret=" . $WeChatLoginConfig['open_appsecret'] . "&code=" . $code . "&grant_type=authorization_code";        $res = $this->http_request($url);        return json_decode($res, true);    }
    //获取用户基本信息(OAuth2 授权的 Access Token 获取 未关注用户,Access Token为临时获取)    private function oauth2_get_user_info($access_token, $openid)    {        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $access_token . "&openid=" . $openid . "&lang=zh_CN";        $res = $this->http_request($url);        return json_decode($res, true);    }
    public function http_request($url){        return file_get_contents($url);    }




 // 登录
    public function login()
    {
        // 若已登录则重定向
        if ($this->users_id > 0) {
            $this->redirect('user/Users/centre');
            exit;
        }
        
        // 若为微信端则重定向
        $website = input('param.website/s');
        if (isWeixin() && empty($website)) {
            $this->redirect('user/Users/users_select_login');
            exit;
        }

        // 默认开启验证码
        $is_vertify          = 1;
        $users_login_captcha = config('captcha.users_login');
        if (!function_exists('imagettftext') || empty($users_login_captcha['is_on'])) {
            $is_vertify = 0; // 函数不存在,不符合开启的条件
        }
        $this->assign('is_vertify', $is_vertify);

        /*微信扫码登录 - 判断是否显示微信登录按钮*/
        $usersConfig = getUsersConfigData('all');
        $WeChatLoginConfig = !empty($usersConfig['wechat_login_config']) ? unserialize($usersConfig['wechat_login_config']) : [];
        if(empty($WeChatLoginConfig)) $this->error('尚未配置扫码登录参数');
        if(empty($WeChatLoginConfig['open_appid']) || empty($WeChatLoginConfig['open_appsecret']) ) $this->error('尚未配置扫码登录参数');

        $weapp_wxlogin = 1;
        $redirect_uri = tpCache('web.web_basehost');
        $redirect_uri = urlencode($redirect_uri);//该回调需要url编码
        $wechat_login_config = unserialize(getUsersConfigData('wechat.wechat_login_config'));
        if(empty($wechat_login_config)) $weapp_wxlogin = 0;
        if($weapp_wxlogin) {
            $appID = $WeChatLoginConfig['open_appid'];
            $scope="snsapi_login";
            /*
            //准备向微信发请求
            $url = "https://open.weixin.qq.com/connect/qrconnect?appid=" . $appID."&redirect_uri=".$redirect_uri."&response_type=code&scope=".$scope."&state=STATE#wechat_redirect";
            $res = file_get_contents($url);

            $res = str_replace("/connect/qrcode/", "https://open.weixin.qq.com/connect/qrcode/", $res);
            */
            $this->assign('appid', $appID);
            $this->assign('wxcodeimg', $res);
        }

        $this->assign('weapp_wxlogin', $weapp_wxlogin);
        /*end*/

        if (1 == config('global.opencodetype')) {
            $type = input('param.type/s');
            $this->assign('type', $type);
        }

        // 跳转链接
        $referurl = input('param.referurl/s', null, 'htmlspecialchars_decode,urldecode');
        if (empty($referurl)) {
            if (isset($_SERVER['HTTP_REFERER']) && stristr($_SERVER['HTTP_REFERER'], $this->request->host())) {
                $referurl = $_SERVER['HTTP_REFERER'];
            } else {
                $referurl = url("user/Users/centre");
            }
        }
        cookie('referurl', $referurl);
        $this->assign('title', '登录');
        $this->assign('referurl', $referurl);
        return $this->fetch('users_login');
    }
    
    
    // 微信扫码登录处理
    public function scale_wx_login() {
        $get = input('get.');
        if (!empty($get['code'])){
            //获取token
            $oauth2_info = $this->oauth2_access_token($get["code"]);
            //获取用户信息
            $userinfo = $this->oauth2_get_user_info($oauth2_info['access_token'], $oauth2_info['openid']);
            // 查询这个openid是否已注册
            $where = [
                'open_id' => $userinfo['unionid'],
                'lang'    => $this->home_lang
            ];
            $Users = $this->users_db->where($where)->find();
            if (!empty($Users)) {
                // 已注册
                session('users_id', $Users['users_id']);
                session('users', $Users);
                cookie('users_id', $Users['users_id']);
                $this->redirect(url('user/users/centre'));
            } else {
                // 未注册
                $username = substr($userinfo['unionid'], 6, 8);
                // 查询用户名是否已存在
                $result = $this->users_db->where('username', $username)->count();
                if (!empty($result)) {
                    $username = $username . rand('100,999');
                }
                
                // 新增会员和微信绑定
                $UsersData = [
                    'username'       => $username,
                    'nickname'       => $userinfo['nickname'],
                    'open_id'        => $userinfo['unionid'],
                    'password'       => '', // 密码默认为空
                    'last_ip'        => clientIP(),
                    'reg_time'       => getTime(),
                    'last_login'     => getTime(),
                    'is_activation'  => 1, // 微信注册会员,默认开启激活
                    'register_place' => 2, // 前台微信注册会员
                    'login_count'    => Db::raw('login_count+1'),
                    'head_pic'       => $userinfo['headimgurl'],
                    'lang'           => $this->home_lang,
                ];
                // 查询默认会员级别,存入会员表
                $level_id           = $this->users_level_db->where([
                    'is_system' => 1,
                    'lang'      => $this->home_lang,
                ])->getField('level_id');
                $UsersData['level'] = $level_id;

                $users_id = $this->users_db->add($UsersData);
                if (!empty($users_id)) {
                    // 新增成功,将会员信息存入session
                    $GetUsers = $this->users_db->where('users_id', $users_id)->find();
                    session('users_id', $GetUsers['users_id']);
                    session('users', $GetUsers);
                    cookie('users_id', $GetUsers['users_id']);
                    $this->redirect(url('user/users/centre'));
                } else {
                    $this->error('未知错误,无法继续!');
                }
                }
            //处理用户登录逻辑
            //登录成功后跳转
            header("Location:************");
        }else {
            $this->error('出错啦');
        }
    }


相关文章

小程序搭建即时通讯方案

https://blog.csdn.net/weixin_43881802/article/details/123481902...

小程序添加分包的时候报错 “pages *** 不应该在分包 subPackages[*] 中”

分包和主包不能一个路径,可以这样写"root":"pages/weixiuConfirm"...

附常见小程序 referer 的配置域名:

平台referer备注微信小程序https://servicewechat.com/{appid}/{version}/page-frame.html头条抖音https://tmaservice.de...

小程序子组件向父组件传递数据

小程序子组件向父组件传递数据

 绑定点击事件, 子组件触发父组件的自定义事件 this.triggerEvent("事件名",参数)向父组件传递参数123456789101112131415//子组件...

公众号自动登录php

public function isWeixin()     {       ...

发表评论    

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。