User.php 13.7 KB
<?php

namespace app\api\controller;

use app\common\controller\Api;
use fast\Http;
use think\Db;
use think\Validate;
use wxapp\aes\WXBizDataCrypt;

/**
 * 登录接口
 */
class User extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

//    public function _initialize()
//    {
//        parent::_initialize();
//    }

    /**
     * @ApiTitle    (获取sessionKey和openid)
     * @ApiSummary  (获取sessionKey和openid)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/getSessionKey)
     * @ApiParams   (name="code", type="string", required=true, description="小程序code")
     * @ApiReturn({
        "code": 1,
        "msg": "获取成功",
        "time": "1553839125",
        "data": {
            "session_key": "session_key",//token
            "openid": "openid",//openid
        },
        })
     */
    public function getSessionKey()
    {
        $validate = new Validate([
            'code' => 'require',
        ]);

        $validate->message([
            'code.require' => '缺少参数code!',
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error(['code' => '40003', 'msg' => $validate->getError()]);
        }

        $code = $data['code'];
        $appId = config('app_id');
        $appSecret = config('app_secrets');

        $response = "https://api.weixin.qq.com/sns/jscode2session?appid=$appId&secret=$appSecret&js_code=$code&grant_type=authorization_code";
        $response = $this->http_get($response);
        $response = json_decode($response, true);
        if(!empty($response['errcode'])) {
            $this->error('操作失败',$response['errcode']);
        }
        $this->success('获取成功',$response);
    }
    //curl  get请求
    public function http_get($url){
        $curl = curl_init();//启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL,$url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, false);//不开启header
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // 获取的信息以文件流的形式返回
        $result = curl_exec($curl); //执行操作
        curl_close($curl);
        return $result;
    }

    /**
     * @ApiTitle    (小程序登录注册)
     * @ApiSummary  (小程序登录注册)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/login)
     * @ApiParams   (name="openid", type="string", required=true, description="openid")
     * @ApiParams   (name="session_key", type="string", required=true, description="session_key")
     * @ApiParams   (name="encrypted_data", type="string", required=true, description="encrypted_data")
     * @ApiParams   (name="iv", type="string", required=true, description="iv")
     * @ApiParams   (name="invite_id", type="int", required=false, description="邀请人ID")
     * @ApiReturn({
    "code": 1,
    "msg": "登陆成功",
    "time": "1553839125",
    "data": {
    "token": "token",//登录唯一标识
    "avatar": "头像"
    },
    })
     */
    public function login()
    {
        $validate = new Validate([
            'openid' => 'require',
            'session_key' => 'require',
            'encrypted_data' => 'require',
            'iv' => 'require',
        ]);

        $validate->message([
            'openid.require' => '缺少参数openid!',
            'session_key.require' => '缺少参数session_key!',
            'encrypted_data.require' => '缺少参数encrypted_data!',
            'iv.require' => '缺少参数iv!',
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error(['code' => '40003', 'msg' => $validate->getError()]);
        }

        $appId = config('app_id');

        $openid = $data['openid'];
        $sessionKey = $data['session_key'];

        $pc = new WXBizDataCrypt($appId, $sessionKey);
        $errCode = $pc->decryptData($data['encrypted_data'], $data['iv'], $wxUserData);

        if ($errCode != 0) {
            $this->error('检验数据失败!', ['errCode' => $errCode, 'param' => $data]);
        }

        $findThirdPartyUser = Db::name("third")
            ->where('openid', $openid)
            ->where('app_id', $appId)
            ->find();


        $currentTime = time();
        $ip = $this->request->ip(0, true);

        $wxUserData['sessionKey'] = $sessionKey;
        unset($wxUserData['watermark']);

        if ($findThirdPartyUser) {
            $token = generate_user_token($findThirdPartyUser['user_id']);

            $userData = [
                'loginip' => $ip,
                'logintime' => $currentTime,
                'login_times' => Db::raw('login_times+1'),
                'more' => json_encode($wxUserData)
            ];

            if (isset($wxUserData['unionId'])) {
                $userData['union_id'] = $wxUserData['unionId'];
            }

            Db::name("third")
                ->where('openid', $openid)
                ->where('app_id', $appId)
                ->update($userData);
            $this->success("登录成功!", ['user_id'=>$findThirdPartyUser['user_id'],'token' => $token, 'avatar' => $wxUserData['avatarUrl']]);
        } else {

            if(empty($data['invite_id'])){
                $invite_id = '';
            }else{
                $invite_id = $data['invite_id'];
            }
                Db::startTrans();
            $userId = Db::name("user")->insertGetId([
                'invite_id'  => $invite_id,
                'status'     => 'normal',
                'gender'     => $wxUserData['gender'],
                'nickname'   => $wxUserData['nickName'],
                'avatar'     => $wxUserData['avatarUrl'],
                'joinip'     => $ip,
                'jointime'   => $currentTime,
                'createtime' => $currentTime,
                'updatetime' => $currentTime,
                'loginip'    => $ip,
                'logintime'  => $currentTime,
                'rongyun_id' => 'xiaowei_'.substr($openid,-6)
            ]);
            $row = Db::name("third")->insert([
                'openid'          => $openid,
                'user_id'         => $userId,
                'nickname'        => $wxUserData['nickName'],
                'app_id'          => $appId,
                'loginip'         => $ip,
                'union_id'        => '',
                'logintime'       => $currentTime,
                'createtime'      => $currentTime,
                'login_times'     => 1,
                'more'            => json_encode($wxUserData)
            ]);

            if ($userId && $row) {
                Db::commit();
                $token = generate_user_token($userId);
                $this->success("登录成功!", ['user_id'=>$userId,'token' => $token, 'avatar' => $wxUserData['avatarUrl']]);
            } else {
                Db::rollback();
                $this->error('登录失败');
            }

        }

    }
    /**
     * @ApiTitle    (通过code获取token)
     * @ApiSummary  (通过code获取token)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/getToken)
     * @ApiParams   (name="code", type="string", required=true, description="code")
     * @ApiReturn({
    "code": 1,
    "msg": "SUCCESS",
    "time": "1553839125",
    "data": {
    "token": "token",//登录唯一标识
    },
    })
     */
    public function getToken(){
        $validate = new Validate([
            'code'           => 'require',
        ]);

        $validate->message([
            'code.require'           => '缺少参数code!',
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error(['code'=>'40003','msg'=>$validate->getError()]);
        }

        $code      = $data['code'];
        $appId     = config('app_id');
        $appSecret = config('app_secret');

        $response = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session?appid=$appId&secret=$appSecret&js_code=$code&grant_type=authorization_code");

        if (!empty($response['errcode'])) {
            $this->error('操作失败:',$response['errcode']);
        }

        $third = Db::name('third')->where(['openid'=>json_decode($response['msg'],true)['openid']])->find();
        if(empty($third)){
            $this->error('查无此人');
        }
        $user_token = Db::name('user_token')->where('user_id',$third['user_id'])->find();
        $data['token'] = $user_token['token'];
        $this->success('SUCCESS',$data);
    }

    /**
     * @ApiTitle    (判断用户身份)
     * @ApiSummary  (判断用户身份)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/judge)
     *
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1571492001",
        "data": {
            "nickname"://昵称
            "avatar"://头像
            "identity"://身份(1学生2老师
            "underway"://进行中的订单数
            "finish"://已完成的订单数
            "after"://售后的订单数
            "summarize"://待总结的订单数
            "jiesuan"://结算中的订单数
            "level"://星级
        }
    })
    */
    public function judge()
    {
        $user_id = $this->getUserId();

        $data = Db::name('user')
            ->field('id,avatar,nickname,identity')
            ->where('id',$user_id)
            ->find();
        if($data['identity'] == 1){
            //学生身份
            $data['underway'] = Db::name('order')
                ->where('user_id',$user_id)
                ->where('finish_status',1)
                ->count();
            $data['finish'] = Db::name('order')
                ->where('user_id',$user_id)
                ->where('finish_status',2)
                ->count();
            $data['after'] = Db::name('order')
                ->where('user_id',$user_id)
                ->where('finish_status',3)
                ->where('is_complaint',1)
                ->count();
        }else{
            //老师身份
            $teacher = Db::name('teacher')->where('user_id',$user_id)->find();
            //查看老师的已帮助人数以及评分星级
            $comment = Db::name('comment')->where('teacher_id',$teacher['id'])->select();
            //评价为五星的人数
            $five =  Db::name('comment')->where('teacher_id',$teacher['id'])->where('level',5)->count();
            //评价为四星的人数
            $four =  Db::name('comment')->where('teacher_id',$teacher['id'])->where('level',4)->count();
            //评价为三星的人数
            $three =  Db::name('comment')->where('teacher_id',$teacher['id'])->where('level',3)->count();
            //评价为二星的人数
            $two =  Db::name('comment')->where('teacher_id',$teacher['id'])->where('level',2)->count();
            //评价为一星的人数
            $one =  Db::name('comment')->where('teacher_id',$teacher['id'])->where('level',1)->count();
            if(!empty($comment)){
                $data['help_num'] = $five + $four + $three + $two + $one + $teacher['help_num'];
                $data['level'] = ceil(($teacher['help_num'] * 5 + $four * 4 + $three * 3 + $two * 2 + $one)/$teacher['help_num']);
            }else{
                $data['help_num'] = $teacher['help_num'];
                $data['level'] = $teacher['level'];
            }
            //进行中
            $data['underway'] = Db::name('order')
                ->where('teacher_id',$teacher['id'])
                ->where('finish_status',1)
                ->count();
            //待总结
            $data['summarize'] = Db::name('order')
                ->where('teacher_id',$teacher['id'])
                ->where('finish_status',2)
                ->where('is_summarize',2)
                ->count();
            //结算中
            $data['jiesuan'] = Db::name('order')
                ->where('teacher_id',$teacher['id'])
                ->where('finish_status',2)
                ->where('is_summarize',1)
                ->where('order_status',2)
                ->count();
            //已完成
            $data['finish'] = Db::name('order')
                ->where('teacher_id',$teacher['id'])
                ->where('finish_status',2)
                ->where('is_summarize',1)
                ->where('order_status',1)
                ->count();
            //售后
            $data['after'] = Db::name('order')
                ->where('teacher_id',$teacher['id'])
                ->where('finish_status',3)
//                ->where('is_complaint',['=',1],['=',3],'or')
                ->count();
        }
        $this->success('success',$data);
    }



    /**
     * @ApiTitle    (获取用户融云账号信息)
     * @ApiSummary  (获取用户融云账号信息)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/rongyun)
     *
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     *
     * @ApiReturn({
    "code": 1,
    "msg": "成功",
    "time": "1571492001",
    "data": {
        "id"://融云id
        "token"://融云token
    }
    })
     */
    public function rongyun() {
        $return = [
            'id' => '',
            'token' => ''
        ];
        if($this->userId) {
            $user_id = $this->getUserId();
            if($this->user['is_create'] == 1) {
                $return = [
                    'id' => $this->user['rongyun_id'],
                    'token' => $this->user['rongyun_token'],
                ];
            }
        }
        $this->success('成功',$return);
    }
}