PublicController.php 12.1 KB
<?php
// +----------------------------------------------------------------------
// | bronet [ 以客户为中心 以奋斗者为本 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.bronet.cn All rights reserved.
// +----------------------------------------------------------------------
namespace api\wxapp\controller;

use think\Db;
use cmf\controller\RestBaseController;
use think\Log;
use wxapp\aes\WXBizDataCrypt;
use think\Validate;

/**
 * @title 公共模块
 * @description 公共模块
 * @package api\wxapp\controller
 */
class PublicController extends RestBaseController
{
    /**
     * @title 获取sessionKey和openid
     * @description 小程序登录注册
     * @url /wxapp/public/getSessionKey
     * @method POST
     *
     * @param name:code type:string require:1 other: desc:code
     *
     * @return session_key:session_key
     * @return openid:openid
     * @return is_register:1已注册 0未注册
     * @return userInfo:对象信息@!
     * @userInfo id:用户id avatar:用户头像 user_nickname:用户昵称 user_type:用户类型 2普通用户 3信贷员 mobile:手机号 user_status:用户状态;0:禁用,1:正常,2:未验证
     */
    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('appId');
        $appSecret = config('appSecret');
        $response = cmf_curl_get("https://api.weixin.qq.com/sns/jscode2session?appid=$appId&secret=$appSecret&js_code=$code&grant_type=authorization_code");

        $response = json_decode($response, true);
        if (!empty($response['errcode'])) {
            $this->error(['code'=>'41001','msg'=>'操作失败:'.$response['errcode']]);
        }
        $findThirdPartyUser = Db::name("third_party_user")
            ->alias('t')
            ->join('user u','t.user_id = u.id')
            ->where('t.openid', $response['openid'])
            ->where('t.app_id', $appId)
            ->field('u.id,u.avatar,u.user_nickname,u.user_type,u.mobile,u.user_status')
            ->find();
        if ($findThirdPartyUser && $findThirdPartyUser['user_status'] == 0) {
            $this->error(['code'=>'40012','msg'=>'您已被管理员拉黑']);
        }
        if ($findThirdPartyUser) {
            $response['is_register'] = 1;
            if ($findThirdPartyUser['user_type'] == 3) {
                $card = Db::name('card')->where(['user_id' => $findThirdPartyUser['id']])->field('id')->find();
                if ($card) {
                    $findThirdPartyUser['card_id'] = $card['id'];
                } else {
                    $findThirdPartyUser['card_id'] = null;
                }
            }
            $response['userInfo'] = $findThirdPartyUser;
        } else {
            $response['is_register'] = 0;
            $response['userInfo'] = [];
        }
        $this->success('获取成功',$response);
    }

    /**
     * @title 小程序登录注册
     * @description 小程序登录注册
     * @url /wxapp/public/login
     * @method POST
     *
     * @param name:openid type:string require:1 other: desc:openid
     * @param name:session_key type:string require:1 other: desc:session_key
     * @param name:encrypted_data type:string require:1 other: desc:encrypted_data
     * @param name:iv type:string require:1 other: desc:iv
     * @param name:type type:int require:1 other: desc:2普通用户3信贷业务员
     *
     * @return token:登录唯一标识
     */
    public function login()
    {
        $validate = new Validate([
            'openid'           => 'require',
            'session_key'           => 'require',
            'encrypted_data' => 'require',
            'iv'             => 'require',
            'type'             => 'require|in:2,3',
        ]);

        $validate->message([
            'openid.require'           => '缺少参数openid!',
            'session_key.require'           => '缺少参数session_key!',
            'encrypted_data.require' => '缺少参数encrypted_data!',
            'iv.require'             => '缺少参数iv!',
            'type.require'             => '缺少参数type!',
            'type.in'             => '参数type只能为2或3!',
        ]);

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

        $appId     = config('appId');

        $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(['code'=>'41002','msg'=>'检验数据失败!'],['errCode'=>$errCode,'param'=>$data]);
        }

        $findThirdPartyUser = Db::name("third_party_user")
            ->alias('a')
            ->join('__USER__ b','a.user_id=b.id','LEFT')
            ->field('a.user_id,b.avatar,b.user_nickname,a.openid,user_type')
            ->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 = cmf_generate_user_token($findThirdPartyUser['user_id'], 'wxapp');

            $userData = [
                'last_login_ip'   => $ip,
                'last_login_time' => $currentTime,
                'login_times'     => ['exp', 'login_times+1'],
                'more'            => json_encode($wxUserData)
            ];

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

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

            Db::startTrans();
            $userId = Db::name("user")->insertGetId([
                'create_time'     => $currentTime,
                'user_status'     => 1,
                'user_type'       => $data['type'],
                'sex'             => $wxUserData['gender'],
                'user_nickname'   => $wxUserData['nickName'],
                'avatar'          => $wxUserData['avatarUrl'],
                'last_login_ip'   => $ip,
                'last_login_time' => $currentTime
            ]);

            $row=Db::name("third_party_user")->insert([
                'openid'          => $openid,
                'user_id'         => $userId,
                'third_party'     => 'wxapp',
                'app_id'          => $appId,
                'last_login_ip'   => $ip,
                'union_id'        => isset($wxUserData['unionId']) ? $wxUserData['unionId'] : '',
                'last_login_time' => $currentTime,
                'create_time'     => $currentTime,
                'login_times'     => 1,
                'status'          => 1,
                'more'            => json_encode($wxUserData)
            ]);

            if($userId && $row){
                Db::commit();
                $token = cmf_generate_user_token($userId, 'wxapp');
                $this->success("登录成功!", ['token' => $token]);
            }else{
                Db::rollback();
                $this->error(['code'=>'40004','msg'=>'登录失败']);
            }

        }

    }

    /**
     * @title 获取手机号用户信息
     * @description 小程序登录注册
     * @url /wxapp/public/wxDecode
     * @method POST
     * @header name:XX-Token type:string require:1 default:abc other: desc:登录标识
     * @header name:XX-Device-Type type:string require:0 default:wxapp other: desc:设备类型
     *
     * @param name:session_key type:string require:1 other: desc:session_key
     * @param name:encrypted_data type:string require:1 other: desc:encrypted_data
     * @param name:iv type:string require:1 other: desc:iv
     *
     */

    public function wxDecode(){
        $validate = new Validate([
            'session_key'           => 'require',
            'encrypted_data' => 'require',
            'iv'             => 'require',
        ]);

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

        $param = $this->request->param();
        if (!$validate->check($param)) {
            $this->error(['code'=>'40003','msg'=>$validate->getError()]);
        }
        $appid = config('appId');
        $sessionKey = $param['session_key'];
        $encryptedData = $param['encrypted_data'];
        $iv = $param['iv'];
        $pc = new WXBizDataCrypt($appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data);
        if ($errCode == 0){
            Db::name('user')->where(['id' => $this->userId])->update(['mobile' =>$data['phoneNumber']]);
            $this->success("获取成功!", $data);
        } else {
            $arr = array(
                -41001=>'encodingAesKey非法',
                -41003=>'aes解密失败',
                -41004=>'解密后得到的buffer非法',
                -41005=>'base64加密失败',
                -41016=>'base64解密失败'
            );
            $errorMsg = isset($arr[$errCode]) ? $arr[$errCode] : $errCode;
            Log::error('微信数据解析失败: '.$errorMsg);
            $this->error(['code'=>'40004','msg'=>$errorMsg]);
        }
    }

    /**
     * @title 获取轮播图列表
     * @description 获取轮播图
     * @url /wxapp/public/getAdList
     * @method POST
     *
     * @header name:XX-Token type:string require:1 default:abc other: desc:登录标识
     * @header name:XX-Device-Type type:string require:0 default:wxapp other: desc:设备类型
     *
     * @return id:轮播图id
     * @return image:轮播图图片地址
     * @return content:轮播图内容
     */
    public function getAdList() {
        $result = Db::name('slideItem')->field('id,image,content')->select();
        if ($result === false) {
            $this->error(['code'=>'40000','msg'=>'获取失败']);
        }
        $this->success('获取成功',$result);
    }

    /**
     * @title 获取轮播图详情
     * @description 获取轮播图
     * @url /wxapp/public/getAdDetails
     * @method POST
     *
     * @header name:XX-Token type:string require:1 default:abc other: desc:登录标识
     * @header name:XX-Device-Type type:string require:0 default:wxapp other: desc:设备类型
     *
     * @param name:id type:int require:1 other: desc:轮播图id
     *
     * @return title:轮播图标题
     * @return image:轮播图图片地址
     * @return content:轮播图内容
     * @return author:作者
     * @return create_time:发布时间
     * @return headimg:发布人头像
     */
    public function getAdDetails() {
        $validate = new Validate([
            'id'           => 'require',
        ]);

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

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

        $result = Db::name('slideItem')->where(['id' => $data['id']])->field('title,image,content,author,create_time,headimg')->find();
        if ($result === false) {
            $this->error(['code'=>'40000','msg'=>'获取失败']);
        }
        if ($result) {
            $result['create_time'] = date('Y-m-d',strtotime($result['create_time']));
        }
        $this->success('获取成功',$result);
    }

}