User.php 14.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
<?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_secret');

        $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")
     * @ApiReturn({
        "code": 1,
        "msg": "登陆成功",
        "time": "1553839125",
        "data": {
            "token": "token",//登录唯一标识
        },
        })
     */
    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("登录成功!", ['token' => $token]);
        } else {
            Db::startTrans();
            $userId = Db::name("user")->insertGetId([
                'status'     => 'normal',
                'id_num'     => date('Ymd').str_pad(mt_rand(1, 99999),5,'0',STR_PAD_LEFT).'8',
                'gender'     => $wxUserData['gender'],
                'nickname'   => $wxUserData['nickName'],
                'avatar'     => $wxUserData['avatarUrl'],
                'joinip'     => $ip,
                'jointime'   => $currentTime,
                'createtime' => $currentTime,
                'updatetime' => $currentTime,
                'loginip'    => $ip,
                'logintime'  => $currentTime,
            ]);
            $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("登录成功!", ['token' => $token]);
            } 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);
    }

    public function member(){
        $this->success('SUCCESS',$this->user);
    }

    /**
     * @ApiTitle    (个人中心)
     * @ApiSummary  (个人中心)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/info)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiReturn({
        "code": 1,
        "msg": "SUCCESS",
        "time": "1553839125",
        "data": {
            "id": "id",//用户id
            "score": //用户积分
            "identity": //身份
     *     "nickname"://昵称
     *     "avatar":头像
        },
        })
     */
    public function info()
    {
        $user_id = $this->getUserId();
        $data = Db::name('user')
            ->where('id',$user_id)
            ->field('id,score,identity,nickname,avatar,mobile')
            ->find();

        $farm = Db::name('farm')
            ->where('user_id',$user_id)
            ->find();
        if(!empty($farm)){
            $data['is_have'] = 1;
            $is_ren = Db::name('attestation')
                ->where('user_id',$user_id)
                ->find();
            if(!empty($is_ren)){
                if($is_ren['status'] == 1){
                    $data['is_ren'] = 1;
                }else{
                    $data['is_ren'] = 2;
                }
            }else{
                $data['is_ren'] = 0;
            }
            $this->success('success',$data);
        }else{
            $data['is_have'] = 2;
            $is_ren = Db::name('attestation')
                ->where('user_id',$user_id)
                ->find();
            if(!empty($is_ren)){
                $data['is_ren'] = 1;
            }else{
                $data['is_ren'] = 2;
            }
            $this->success('success',$data);
        }
    }



    /**
     * @ApiTitle    (邻居家的余粮)
     * @ApiSummary  (邻居家的余粮)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/residue)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     *
     * @ApiParams   (name="page", type="inter", required=false, description="当前页(默认1)")
     * @ApiParams   (name="pageNum", type="inter", required=false, description="每页显示数据个数(默认10)")
     *
     * @ApiReturn({
    "code": 1,
    "msg": "SUCCESS",
    "time": "1553839125",
    "data": {
    "id":项目ID,
    "farm_id":农场ID
    'project_name'://项目名称,
    "image"://项目图片
    'farm_name'://农场名称,
    "avatar"://头像
    'look_num'://浏览量,
    "good_num"://点赞量
    'thumbnail'://图片
    "address"://项目地址
    "status"://是否点过赞(1已经点过2没有点过)
    "hong_status"://0未授权1已经授权
    'createtime'://创建时间
    }
    })
     */
    public function residue()
    {
        $token = $this->request->header('token');
        $page = $this->request->param('page',1,'intval');
        $pageNum = $this->request->param('pageNum',6,'intval');

        //判断用户是否登录
        if($token){
            $user_id = $this->getUserId();
            $nong = Db::name('farm')
                ->where('user_id',$user_id)
                ->find();
            if(empty($nong)){
                $data = Db::name('project')
                    ->field('id,farm_id,project_name,address,image,good_num')
                    ->order('good_num desc,id desc')
                    ->page($page,$pageNum)
                    ->select();
                foreach ($data as &$v){
                    $v['image'] = 'http://q2ugvq3qf.bkt.clouddn.com'.$v['image'];
                    $zan = Db::name('good')
                        ->where('project_id',$v['id'])
                        ->where('user_id',$user_id)
                        ->find();
                    if($zan){
                        $v['statu'] = 1;
                    }else{
                        $v['statu'] = 2;
                    }
                    $farm = Db::name('farm')
                        ->alias('a')
                        ->join('user b','a.user_id = b.id')
                        ->field('a.name,b.avatar')
                        ->where('a.id',$v['farm_id'])
                        ->find();
                    $v['avatar'] = $farm['avatar'];
                    $v['farm_name'] = $farm['name'];
                    $v['hong_status'] = 1;
                }
                $this->success('success',$data);
            }else{
                $data = Db::name('project')
                    ->field('id,farm_id,project_name,address,image,good_num,province')
                    ->whereLike('province',"%$nong[province]%")
                    ->order('good_num desc,id desc')
                    ->page($page,$pageNum)
                    ->select();
                foreach ($data as &$v){
                    $v['image'] = 'http://q2ugvq3qf.bkt.clouddn.com'.$v['image'];
                    $zan = Db::name('good')
                        ->where('project_id',$v['id'])
                        ->where('user_id',$user_id)
                        ->find();
                    if($zan){
                        $v['statu'] = 1;
                    }else{
                        $v['statu'] = 2;
                    }
                    $farm = Db::name('farm')
                        ->alias('a')
                        ->join('user b','a.user_id = b.id')
                        ->field('a.name,b.avatar')
                        ->where('a.id',$v['farm_id'])
                        ->find();
                    $v['avatar'] = $farm['avatar'];
                    $v['farm_name'] = $farm['name'];
                    $v['hong_status'] = 1;
                }
                $this->success('success',$data);
            }
        }else {
            $data = Db::name('project')
                ->field('id,farm_id,project_name,address,image,good_num')
                ->order('good_num desc,id desc')
                ->page($page, $pageNum)
                ->select();
            foreach ($data as &$v) {
                $v['image'] = 'http://q2ugvq3qf.bkt.clouddn.com' . $v['image'];
                $farm = Db::name('farm')
                    ->alias('a')
                    ->join('user b', 'a.user_id = b.id')
                    ->field('a.name,b.avatar')
                    ->where('a.id', $v['farm_id'])
                    ->find();
                $v['avatar'] = $farm['avatar'];
                $v['farm_name'] = $farm['name'];
                $v['hong_status'] = 0;
            }
            $this->success('success', $data);
        }
    }

}