Login.php 11.4 KB
<?php
/**
 * Created by PhpStorm.
 * Login: Kevin
 * Date: 2022/06/12
 * Time: 15:34
 */

namespace app\api\controller\v1;

use lib\WXBizDataCrypt;
use think\Db;
use think\Request;

header('Access-Control-Allow-Origin:*');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header('Access-Control-Allow-Methods: GET, POST, PUT');

class Login extends Base
{ /**
 * 12.小程序授权注册用户、返回用户信息
 */
    public function get_user_by_shouquan()
    {
        $appid = $this->AppID;
        $AppSecret = $this->AppSecret;
        $code = $this->request->param("code");
//        $encryptedData = $this->request->param("encryptedData");
//        $iv = $this->request->param("iv");
//        $type = $this->request->param("type");
//
//        if ($type == 1) {
//            $encryptedData = urldecode($encryptedData);
//            $iv = urldecode($iv);
//            file_put_contents("ccc.txt", "授权A:" . date("Y-m-d H:i:s") . ":" . $encryptedData . PHP_EOL, FILE_APPEND);
////            file_put_contents("ccc.txt", "授权B:" . date("Y-m-d H:i:s") . ":" . $iv . PHP_EOL, FILE_APPEND);
//
//        }

        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $appid . "&secret=" . $AppSecret . "&js_code=" . $code . "&grant_type=authorization_code";
        $res = json_decode(http_request($url), true);
        if (!$res) {
            $res = json_decode(http_request($url), true);
        }
        print_r($res);return;

        $sessionKey = $res['session_key'];
        $openid = $res['openid'];//获取用户openid
        //$unionid = $res['unionid'];//获取用户openid
//        file_put_contents("ccc.txt", "授权1:" . date("Y-m-d H:i:s") . ":" . json_encode($res, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);

        require_once '../extend/lib/WXBizDataCrypt.class.php';

        $pc = new WXBizDataCrypt($appid, $sessionKey);

        //$errCode = $pc->decryptData($encryptedData, $iv, $data);

        //$data = json_decode($data, true);
//        file_put_contents("ccc.txt", "授权2:" . date("Y-m-d H:i:s") . ":" . $errCode . PHP_EOL, FILE_APPEND);
//        file_put_contents("ccc.txt", "授权3:" . date("Y-m-d H:i:s") . ":" . json_encode($data, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);

        if ($errCode != 0) {
            $ajax['code'] = 0;
            $ajax['info'] = $errCode;
            $errCode = $errCode == "-41001" || $errCode == "-41003" ? "授权失败,请尝试重新授权" : $errCode;
            $this->error($errCode);
        }
        if ($openid) {
            $openid_info = [
                "openid" => $openid,
                "unionid" => $unionid,
                "from" => "wx",
            ];
            if (!empty($data['nickName'])) {
                $openid_info['nickName'] = $data['nickName'];
            }
            if (!empty($data['gender'])) {
                $openid_info['gender'] = $data['gender'];
            }
            if (!empty($data['avatarUrl'])) {
                $openid_info['avatarUrl'] = $data['avatarUrl'];
            }
            if (!empty($data['country'])) {
                $openid_info['country'] = $data['country'];
            }
            if (!empty($data['province'])) {
                $openid_info['province'] = $data['province'];
            }
            if (!empty($data['city'])) {
                $openid_info['city'] = $data['city'];
            }
            if (!empty($data['phoneNumber'])) {
                $openid_info['phoneNumber'] = $data['phoneNumber'];
            }
            insert_openid_info($openid_info);//更新下微信用户信息到数据库
        }

        //直接通过unionid 查找用户信息
        $userres = Db::name("user")->where("wx_xcx_openid", $openid)->order("id desc")->find();

        if (empty($userres)) {
            //如果通过小程序openid找不到会员
            //注册处理
            $extend_data = [
                "nickname" => $openid_info['nickName'],
                "avatar" => $openid_info["avatarUrl"],
                "wx_xcx_openid" => $openid,
                "unionid" => $unionid,
            ];
            $username = $openid ? $openid : suiji_num("TY");
            $ret = $this->auth->register($username, "a123456", '', $data['phoneNumber'], $extend_data);
            if ($ret) {
                $return_data = $this->auth->getUserinfo();

                $is_mng_user = 0;//是否是社区管理员 0不是 1是
                $mng_area = [];//管辖区域(多个)
                $area = Db::name("hc_area_code_mng")->alias("a")
                    ->join("hc_area_code b", "b.code=a.mng_code")
                    ->where("a.mng_user_id", $return_data['id'])->field("b.code,b.name")->select();
                if (!empty($area)) {
                    $is_mng_user = 1;
                    $mng_area = $area;
                }
                $return_data['is_mng_user'] = $is_mng_user;
                $return_data['mng_area'] = $mng_area;

                if (empty($return_data['mobile'])) {
                    $this->success("授权成功,请继续认证手机号后才能正常使用", $return_data, 2);
                } else {
                    //这里是新注册用户,有手机号,需要判断下手机号有没有在区域管理员中存在,若存在就将id绑定过去
                    $bind = Db::name("hc_area_code_mng")->where("mng_admin_phone", $return_data['mobile'])->order("id desc")->find();
                    if (!empty($bind)) {
                        Db::name("hc_area_code_mng")->where("mng_admin_phone", $return_data['mobile'])->update(["mng_user_id" => $return_data['id']]);
                        if ($bind['mng_admin_name']) {
                            //将管理员姓名更新到用户表中
                            Db::name("user")->where("id", $return_data['id'])->update(["username" => $bind['mng_admin_name']]);
                        }
                    }
                }

                $this->success("登录成功!", $return_data);
            } else {
                $this->error($this->auth->getError());
            }
        } else {
            //小程序openid找到了会员
            $update_data = [];
            $update_data['logintime'] = time();
            if (empty($userres['mobile']) && !empty($openid_info['phoneNumber'])) {
                $update_data['mobile'] = $openid_info['phoneNumber'];
            }
//            if (!empty($openid_info['phoneNumber'])) {
//                $update_data['username'] = $openid_info['phoneNumber'];
//            }
//            if (!empty($openid_info['nickName']) && $openid_info['nickName']!="微信用户") {
//                $update_data['nickname'] = $openid_info['nickName'];
//            }


            if (!empty($openid_info['phoneNumber'])) {
                //这里是已注册过的用户,有手机号,需要判断下手机号有没有在区域管理员中存在,若存在就将id绑定过去
                $bind = Db::name("hc_area_code_mng")->where("mng_admin_phone", $openid_info['phoneNumber'])->order("id desc")->find();
                if (!empty($bind)) {
                    Db::name("hc_area_code_mng")->where("mng_admin_phone", $openid_info['phoneNumber'])->update(["mng_user_id" => $userres['id']]);
                    if ($bind['mng_admin_name']) {
                        //将管理员姓名更新到用户表中
                        Db::name("user")->where("id", $userres['id'])->update(["username" => $bind['mng_admin_name']]);
                    }
                }
            }

            Db::name("user")->where("wx_xcx_openid", $openid)->update($update_data);
            $this->auth->direct($userres['id']);
            $return_data = $this->auth->getUserinfo();

            $is_mng_user = 0;//是否是部门管理员 0不是 1是
            $mng_area = [];//管辖部门(多个)
            $area = Db::name("hc_area_code_mng")->alias("a")
                ->join("hc_area_code b", "b.code=a.mng_code")
                ->where("a.mng_user_id", $return_data['id'])->field("b.code,b.name")->select();
            if (!empty($area)) {
                $is_mng_user = 1;
                $mng_area = $area;
            }
            $return_data['is_mng_user'] = $is_mng_user;
            $return_data['mng_area'] = $mng_area;

            $this->success(__('登录成功'), $return_data);
        }
    }

    /**
     * 给后台添加用户时自动注册用
     */
    public function auto_regist_user($username, $password = "a123456", $email = "", $mobile, $extend_data)
    {
        $ret = $this->auth->register($username, $password, '', $mobile, $extend_data);
        if ($ret) {
            $return_data = $this->auth->getUserinfo();
            return array_callback(true, "用户添加成功", $return_data['id']);
        } else {
            return array_callback(false, $this->auth->getError());
        }
    }
    public function get_user_by_phone()
    {
        $user_id=$this->auth->id;
        $appid = $this->AppID;
        $AppSecret = $this->AppSecret;
        $post = $this->request->post();
        $code = $post['code'];
        $AccessToken=$this->getwxAccessToken($appid,$AppSecret);
        $phone=$this->getwxPhoneNumber($code,$AccessToken);
        $phone=json_decode($phone,true);
        $moblie=$phone['phoneNumber'];
        if($moblie){
            $res=Db::name("user")->where("id", $user_id)->update(["mobile" => $moblie]);
            $this->auth->direct($user_id);
            $return_data = $this->auth->getUserinfo();

            if($res){
                $this->success("登录成功!",$return_data);

            }else{
                $this->error("无法获取手机号,登录失败");

            }
        }else{
            $this->error("无法获取手机号,登录失败");
        }
    }




    //获取accesstoken
    function getwxAccessToken($appid,$AppSecret){
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$AppSecret."";
        $res = json_decode(http_request($url), true);
        return $res;
    }
    //获取手机号
    function getwxPhoneNumber($code,$token)
    {
        $token =$token['access_token'];
        $data['code'] = $code;//前端获取code
        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$token";
        $info = $this->Post(json_encode($data),$url);
        // 一定要注意转json,否则汇报47001错误
        $tmpinfo = json_decode($info);



        $code = $tmpinfo->errcode;
        $phone_info = $tmpinfo->phone_info;
        //手机号
        $phoneNumber = $phone_info->phoneNumber ;
        if ($code == '0') {
            return json_encode(['code' => 1, 'msg' => '请求成功', 'phoneNumber' => $phoneNumber]);
        } else {
            return json_encode($tmpinfo);
        }
    }

    function Post($curlPost, $url, $ssl = false)
    {
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_NOBODY, true);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        if (!$ssl) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        $return_str = curl_exec($curl);
        curl_close($curl);
        return $return_str;
    }
}