微信小程序一键登录

//小程序一键登录
    public function wechat()
    {
        $code = $this->request->post('code');    //前端获取传过来的code
        if (!$code){
            return $this->err('缺少参数');
        }

        //获取秘钥key
        if ($res = Db::table('***')->where([***])->find()){
            if ($info = $this->wechatGet($res['appid'],$res['secret'],$code)){
                $arr = array(
                    'phone'=>$info['phoneNumber'],
                    'name'=>$info['phoneNumber'],
                    'image'=>'https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132'
                );

                if ($log = $this->login($arr)){
                    return $this->succ('登录成功',$log);
                }
            }
        }

        return $this->err('登录失败');
    }

public function login($data = [])
    {

       if (empty($data)){
            return false;
        }
        
        个人的登录操作
    }  


    //封装调用
//小程序登录
    protected function wechatGet($appid,$secret,$code){
        $url = 'https://api.weixin.qq.com/cgi-bin/token';
        $data = array(
            'grant_type'=>'client_credential',
            'appid'=>$appid,
            'secret'=>$secret
        );

        $ch = curl_init();

        // 构建查询字符串
        $queryString = http_build_query($data);
        $fullUrl = $url. '?'. $queryString;
        curl_setopt($ch, CURLOPT_URL, $fullUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $response = curl_exec($ch);
        if (curl_errno($ch)) {
            return false;
        }

        curl_close($ch);
        $access_token = json_decode($response,true)['access_token'];
        return $this->wechatPost($access_token,$code);

    }
    protected function wechatPost($access_token,$code){
        $ch = curl_init();
        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$access_token";
        $data = ['code'=>$code];
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        $response = curl_exec($ch);
        if (curl_errno($ch)) {
            return false;
        }
        curl_close($ch);
        //验证是否成功
        $info = json_decode($response,true);
        if ($info['errcode'] !== 0){
            return false;
        }

        return $info['phone_info'];
    }

 

posted @ 2024-06-25 10:57  祈愿仙帝  阅读(2)  评论(0编辑  收藏  举报