记录微信扫码关注公众号实现 pc 网站登录

记录微信扫码关注公众号实现pc 网站登录
框架tp5.1
1.公众号基本设置 完成token验证
记录微信扫码关注公众号实现 pc 网站登录_第1张图片
2.服务器端获取access_token
官方文档
记录微信扫码关注公众号实现 pc 网站登录_第2张图片
3.根据 access_token 换取 ticket
官方文档
记录微信扫码关注公众号实现 pc 网站登录_第3张图片
4.根据 ticket 获得图片路径
记录微信扫码关注公众号实现 pc 网站登录_第4张图片
5.获取微信推送消息 备注(微信推送路径是上方1 公众号配置的 url)

官方文档接收事件推送
记录微信扫码关注公众号实现 pc 网站登录_第5张图片
上代码:
发送curl 请求封装:

/**
 *
 * 发送curl请求
 * @param $url
 * @param string $method  球球方法
 * @param null $postfields 请求数据
 * @param array $headers 头部
 * @param bool $debug 调试
 * @return array
 */
function http($url, $method = '', $postfields = null, $headers = array(), $debug = false)
{
     
    $ci = curl_init();
    /* Curl settings */
    curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ci, CURLOPT_TIMEOUT, 30);
    curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
    switch ($method) {
     
        case 'POST':
            curl_setopt($ci, CURLOPT_POST, true);
            if (!empty($postfields)) {
     
                curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
            }
            break;
    }
    curl_setopt($ci, CURLOPT_URL, $url);
    curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ci, CURLINFO_HEADER_OUT, true);
    $response = curl_exec($ci);
    $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
    if ($debug) {
     
        echo "=====post data======\r\n";
        var_dump($postfields);
        echo '=====info=====' . "\r\n";
        print_r(curl_getinfo($ci));
        echo '=====$response=====' . "\r\n";
        print_r($response);
    }
//    echo curl_getinfo($ci, CURLINFO_HEADER_OUT);
    curl_close($ci);
    return array($http_code, $response);
}

获取token自定义封装

//获取token
    public function getAccessToken(){
     
        //获取token
        $wx_access_token=config('wx_access_token.');
        //判定token是否过期
        if($wx_access_token['expires_time'] > time()){
     
            $token=$wx_access_token['access_token'];
        }else{
     //从新获取token
            $appid="appid";
            $secret="secret";
            $access_token_url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
            $access_token_date=http($access_token_url);
            $access_token_date=json_decode($access_token_date[1],true);
            if(isset($access_token_date['access_token'])){
     
                $token=$access_token_date['access_token'];
                $code = "return [
                'access_token' => '" . $access_token_date['access_token'] . "',
                'expires_in' => '" . $access_token_date['expires_in'] . "',
                'expires_time' => '" .($access_token_date['expires_in']+time()) . "',
                ]";
                $code = " . $code . ";";
                file_put_contents(Env::get('config_path') . "wx_access_token.php",$code);
            }else{
     
                return array('code'=>$access_token_date['errcode'],'msg'=>$access_token_date['errmsg']);
            }
        }
        return array('code'=>0,'token'=>$token);
    }

获取二维码及获取用户扫码状态

        //获取用户扫码状态
    public function getUserQrkoude(){
     
        if (Request::isPost() && Request::isAjax()) {
     
            $param = Request::param();
            $token=Request::has('token') ? $param['token'] : 0;
            if($token){
     
                $result=Db::name('wx_token_log')->where('token',$token)->find();
                if($result['start'] == 1 && $result['uid'] != 0){
     
                    //查询用户信息
                    $user=Db::name('user')->where('id',$result['uid'])->find();
                    if($user){
     
                        $auth = new Auth();
                        $auth->setLoginGlobal($user);//设置登录状态
                        exit(json_encode(array('code'=>0,'msg'=>"ok",'url'=>url('index/user/index'))));
                    }else{
     
                        exit(json_encode(array('code'=>1,'msg'=>"用户未找到")));
                    }
                }else{
     
                    exit(json_encode(array('code'=>1,'msg'=>"error")));
                }
            }else{
     
                exit(json_encode(array('code'=>2,'msg'=>"Missing Parameters")));
            }
        }else{
     
            exit(json_encode(array('code'=>2,'msg'=>"Request type error")));
        }
    }
    //获取公众号二维码APi
    public function getWxImg(){
     
        if (Request::isPost() && Request::isAjax()) {
     
            //生成签名
            $token=md5(microtime().request()->ip());
            //存储数据库
            $save_wx_token_log=array('token'=>$token,'add_date'=>time(),'start'=>0);
            $save_wx_token_log_id=Db::name('wx_token_log')->insertGetId($save_wx_token_log);
            if($save_wx_token_log_id){
     
                $userLogic = new UserMsq();
                exit(json_encode($userLogic->getWxTencentImg($save_wx_token_log_id,$token)));
            }
        }else{
     
            exit(json_encode(array('code'=>2,'msg'=>"Request type error")));
        }
    }

前端获取二维码 且进行轮训查询用户状态

	var begin;
    var token;
    //获取二维码
    function getWx(obj){
     
        if(obj == 0){
     
            $.ajax({
     
                type:"POST",
                url: "/index/user/getWxImg",
                data: {
     },
                dataType:"json",
                success:function(res){
     
                    if(res.code == 0){
     
                        $('#wxQrCode').attr('src',res.url);
                        token=res.token
                        begin=setInterval("getUserQrkoude()",500);
                    }else{
     
                        alert(res.msg);
                    }
                }
            });
        }else{
     
            clearInterval(begin);
        }
    }
    //获取用户状态
    function getUserQrkoude() {
     
        $.ajax({
     
            type:"POST",
            url: "/index/user/getUserQrkoude",
            data: {
     token},
            dataType:"json",
            success: function (res) {
     
                if (res.code == 0){
     
                    window.location.href=res.url;
                }
            }
        })
    }

接取微信推送封装(返回参数官方文档有说明根据需求开发)

    public function index(){
     
        $echoStr = Request::get('echostr');
        if($echoStr){
     
            echo $echoStr;
        }
        $get_push_xml=file_get_contents('php://input');
        if($get_push_xml){
     
            //xml 转换数组
            $get_push = json_decode(json_encode(simplexml_load_string($get_push_xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
            $ToUserName=$get_push['ToUserName'];
            $OpenID=$get_push['FromUserName'];
            //推送事件类型
            if($get_push['MsgType'] == 'event'){
     
                if($get_push['Event'] == 'subscribe' && !isset($get_push['EventKey'])){
      //关注/取消关注事件subscribe(订阅)
                    echo "success";exit;
                }elseif($get_push['Event'] == 'unsubscribe'){
      //关注/取消关注事件unsubscribe(取消订阅)
                    echo "success";exit;
                }elseif($get_push['Event'] == 'subscribe' && isset($get_push['EventKey'])){
      //扫描带参数二维码事件   用户未关注时,进行关注后的事件推送  Evenkey 区分扫码关注还是  其他关注
                    $EventKey=$get_push['EventKey'];//携带的token
                    $qrscene=explode('_',$EventKey);
                    $this->setUser($OpenID,$qrscene);
                }elseif($get_push['Event'] == 'SCAN'){
      //扫描带参数二维码事件 用户已关注时的事件推送
                    $qrscene=$get_push['EventKey'];
                    $this->setUser($OpenID,$qrscene);
                }
                $str="
                      
                      
                      %s
                      
                      
                    ";
                $str = sprintf($str,$OpenID,$ToUserName,time(),'登录成功');
                echo $str;
            }elseif($get_push['MsgType'] == 'text' || $get_push['MsgType'] == 'image' || $get_push['MsgType'] == 'voice' || $get_push['MsgType'] == 'video'|| $get_push['MsgType'] == 'music'|| $get_push['MsgType'] == 'news'){
     
                $str="
                      
                      
                      %s
                      
                      
                    ";
                $str = sprintf($str,$OpenID,$ToUserName,time(),'[自动回复]您好当前公众号正在开发中,敬请期待...');
                echo $str;
            }

        }

    }
    //查询用户信息更改wx_token_log  状态
    //查询用户信息更改wx_token_log  状态此处可根据返回的openid 查询用户信息
   //[获取用户基本信息(UnionID机制)]https://developers.weixin.qq.com/doc/offiaccount/User_Management/Get_users_basic_information_UnionID.html#UinonId)
    public function setUser($OpenID,$qrscene){
     
        $update=array('wx_gz'=>1);
        $userLogic = new UserMsq();
        $data=$userLogic->getAccessToken();
        if($data['code']==0){
     
            $token=$data['token'];
            $openid=$OpenID;
            $url="https://api.weixin.qq.com/cgi-bin/user/info?access_token=$token&openid=$openid&lang=zh_CN";
            $wxUserInfo=http($url);
            if($wxUserInfo[0]== 200 ){
     
                $wxUserInfo=json_decode($wxUserInfo[1],true);
                if(isset($wxUserInfo['openid'])){
     
                    $update['openid']=$wxUserInfo['openid'];
                    $update['nickname']=$wxUserInfo['nickname'];
                    $update['header_picture']=$wxUserInfo['headimgurl'];
                    $update['wx_gz']=$wxUserInfo['subscribe'];
                }
            }
        }
        $user_id=Db::name('user')->where('openid',$OpenID)->value('id');
        if($user_id){
     //用户存在
                Db::name('user')->where('id',$user_id)->update($update);
        }else{
     //不存在
            $user_id=Db::name('user')->insertGetId($update);
        }
        //更改token状态
        if($user_id){
     
            Db::name('wx_token_log')->where('id',$qrscene)->update(array('start'=>1,'uid'=>$user_id));
        }
    }

你可能感兴趣的:(微信扫码关注公众号实现登录,php,ajax,javascript,jquery,css)