Common.php 12.4 KB
<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Area;
use app\common\model\Version;
use fast\Random;
use think\Config;
use Qiniu\Storage\UploadManager;
use Qiniu\Auth;
use think\Cache;
use think\Db;
use think\Validate;

/**
 * 公共接口
 */
class Common extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    /**
     * 加载初始化
     *
     * @param string $version 版本号
     * @param string $lng     经度
     * @param string $lat     纬度
     */
    public function init()
    {
        if ($version = $this->request->request('version')) {
            $lng = $this->request->request('lng');
            $lat = $this->request->request('lat');
            $content = [
                'citydata'    => Area::getCityFromLngLat($lng, $lat),
                'versiondata' => Version::check($version),
                'uploaddata'  => Config::get('upload'),
                'coverdata'   => Config::get("cover"),
            ];
            $this->success('', $content);
        } else {
            $this->error(__('Invalid parameters'));
        }
    }

    /**
     * @ApiTitle    (上传文件)
     * @ApiSummary  (上传文件)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/common/uploadFile)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     *
     * @ApiParams   (name="image[]", type="file", required=false, description="图片")
     *
     * @ApiReturn({
    "code": 1,
    "msg": "SUCCESS",
    "time": "1553839125",
    "data": {

    }
    })
     */
    public function uploadFile(){
        $files = request()->file('image');
        if (empty($files)) {
            $this->error('未检出文件上传');
        }
        $countFile = count($files);
        if($countFile > 9) {
            $this->error('最多上传5张图片');
        }
        $url2 = '';
//        $fan = '';
        $host = get_addon_config('qiniu')['cdnurl'];
        foreach ($files as $file){
            //移动到框架应用根目录/public/uploads/ 目录下
            $moveUrl = ROOT_PATH . 'public' . DS . 'uploads';
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
            if($info){
                //上传七牛云逻辑
                $url = str_replace('//', '/', str_replace('\\', '/', $info->getSaveName())); //20190602/1214564654.jpg目录

                $filePath = $moveUrl.DS.$url;//本地磁盘路径
                //上传至七牛云文件路径
                $qiniu_file = 'uploads/'.$url;
                $upManager = new UploadManager();
                $config = get_addon_config('qiniu');
                // 构建鉴权对象
                $auth = new Auth($config['app_key'], $config['secret_key']);
                // 生成上传 Token
                $token = $auth->uploadToken($config['bucket']);
                // 调用 UploadManager 的 putFile 方法进行文件的上传。
                $qi_res = $upManager->putFile($token,$qiniu_file , $filePath);
                if($qi_res){
                    $a = $host.'/'.$qiniu_file;
                    $sys = $this->getOperateSys();
                    //删除本地服务器图片逻辑
                    if($sys == 'Linux'){
                        unlink($filePath);//适用于linux
                    }
                    $url2 .= $a.',';
//                    $fan .= '/'.$qiniu_file.',';
                }else{
                    $this->error('上传七牛云出错!');
                }
            }else{
                $this->error($files->getError());
            }
        }
        $this->success('SUCCESS',rtrim($url2,','));
    }

    //判断当前操作系统
    public function getOperateSys(){
        $os_name = php_uname('s');
        //判断
        if(strpos($os_name,"Linux")!==false){
            $os_str="Linux";
        }else if(strpos($os_name,"Windows")!==false){
            $os_str="Windows";
        }else{
            $os_str='';
        }
        return $os_str;
    }

    /**
     * @ApiTitle    (获取验证码)
     * @ApiSummary  (获取验证码)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/common/getcode)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     *
     * @ApiParams   (name="phone", type="string", required=false, description="手机号")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "SUCCESS",
        "time": "1553839125",
        "data": {

        }
        })
     */
    public function getcode()
    {
        $phone = $this->request->param('phone');
        if (empty($phone)) {
            $this->error(['code' => 40005, 'msg' => '手机号不能为空']);
        }
        if (!preg_match('/^1[0-9]{10}$/', $phone)) {
            $this->error(['code' => 40005, 'msg' => "请输入正确的手机格式!"]);
        }
        //生成验证码
        $number = generateCode();
        //发送验证码
        $data = array(
            'content' => "【小微问问】提醒您,您的验证码是:" .$number.",十分钟之内有效,请勿向他人泄漏您的验证码",//短信内容
            'mobile' => $phone,//手机号码
            'productid' => '676767',//产品id
            'xh' => ''//小号
        );
        $result = send_sms($data);
        if (substr($result, 0, strpos($result, ',')) != "1") {
            $this->error(['code' => 42001, 'msg' => $result]);
        }
        Cache::set($phone,$number,600);
        $this->success('SUCCESS');
    }

    /**
     * @ApiTitle    (验证验证码)
     * @ApiSummary  (验证验证码)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/common/verify)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     *
     * @ApiParams   (name="phone", type="string", required=true, description="手机号")
     * @ApiParams   (name="code", type="string", required=true, description="验证码")
     *
     * @ApiReturn({
    "code": 1,
    "msg": "SUCCESS",
    "time": "1553839125",
    "data": {

    }
    })
     */
    public function verify()
    {
        $param = $this->request->param();
        $validate = new Validate([
            'phone' => 'require|max:11',
            'code'=>'require'
        ]);
        if (!$validate->check($param)) {
            $this->error(['code'=>40005,'msg'=>$validate->getError()]);
        }
        $code = Cache::get($param['phone']);
        if($param['code'] == $code){
            $this->success('SUCCESS');
        }else{
            $this->error('验证码错误或者失效,请重新发送');
        }

    }

    /**
     * @ApiTitle    (获取融云token)
     * @ApiSummary  (获取融云token)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/common/rong_getToken)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "SUCCESS",
        "time": "1553839125",
        "data": {

        }
        })
     */
    public function rong_getToken()
    {
        $user_id = $this->getUserId();
        $data = Db::name('user')
            ->where('id',$user_id)
            ->find();
        if($data['identity'] == 1){
            $rong['name'] = $data['nickname'];
            $rong['portraitUri'] = $data['avatar'];
        }else{
            //获取七牛云配置
            $qiniu = get_addon_config('qiniu');
            $http = $qiniu['cdnurl'];
            //身份为老师
            $teacher = Db::name('teacher')
                ->where('user_id',$user_id)
                ->find();
            $rong['name'] = $teacher['name'];
            $rong['portraitUri'] = $http.$teacher['thumbnail'];
        }
        $rong['userId'] = $user_id;
        $url = 'http://api-cn.ronghub.com/user/getToken.json';
        $postData = 'userId='.$rong['userId'].'&name='.$rong['name'].'&portraitUri='.$rong['portraitUri'];

        // post提交-推送
        $row = json_decode($this->request_post_push($url, $postData),true);

        print_r($row);die;

    }

    public function request_post_push($url = "", $postData = "") {

        // 参数为空返回状态
        if (empty($url) || empty($postData)) {
            return false;
        }

        //参数初始化
        $appKey = config('App_Key');
        $appSecret = config('App_Secret');

        $nonce = mt_rand(); // 获取随机数。

        $timeStamp = time();// 获取时间戳。

        $signature = sha1($appSecret.$nonce.$timeStamp);

        $httpHeader = array(

            'App-Key:'.$appKey, //	平台分配

            'Nonce:'.$nonce, //	随机数

            'Timestamp:'.$timeStamp, //	时间戳

            'Signature:'.$signature, //	签名

            'Content-Type: application/x-www-form-urlencoded',

        );

        // 初始化curl
        $ch = curl_init();
        // 设置你需要抓取的URL
        curl_setopt($ch, CURLOPT_URL, $url);
        // post提交方式
        curl_setopt($ch, CURLOPT_POST, 1);

        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        // 设置cURL 参数,要求结果保存到字符串中还是输出到屏幕上。
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // 设置header
        curl_setopt($ch, CURLOPT_HEADER, false);
        // 增加 HTTP Header(头)里的字段
        curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeader);

        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        // 终止从服务端进行验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
        // 运行curl
        $data = curl_exec($ch);
        // 关闭URL请求
        curl_close($ch);

        return $data ;
    }

    /**
     * @ApiTitle    (记录融云聊天内容)
     * @ApiSummary  (记录融云聊天内容)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/common/setOrderChat)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     *
     * @ApiParams   (name="order_id", type="interger", required=true, description="订单id")
     * @ApiParams   (name="chat_id", type="string", required=true, description="融云群聊id")
     * @ApiParams   (name="send_id", type="string", required=true, description="发送人id")
     * @ApiParams   (name="receive_id", type="string", required=true, description="接收人id")
     * @ApiParams   (name="type", type="interger", required=true, description="消息类型:1=文字2=图片3=文件")
     * @ApiParams   (name="text", type="string", required=false, description="文字内容")
     * @ApiParams   (name="image", type="string", required=false, description="图片")
     * @ApiParams   (name="file", type="string", required=false, description="文件")
     *
     * @ApiReturn({
    "code": 1,
    "msg": "SUCCESS",
    "time": "1553839125",
    "data": {

    }
    })
     */
    public function setOrderChat()
    {
        $validate = new Validate([
            'order_id' => 'require',
            'chat_id' => 'require',
            'send_id' => 'require',
            'receive_id' => 'require',
            'type' => 'require|in:1,2,3',
            'text' => 'require',
            'image' => 'require',
            'file' => 'require',
        ]);

        $validate->message([
            'order_id.require' => '缺少参数order_id!',
            'chat_id.require' => '缺少参数chat_id!',
            'send_id.require' => '缺少参数send_id!',
            'receive_id.require' => '缺少参数receive_id!',
            'type.require' => '缺少参数type!',
            'type.in' => 'type参数错误!',
            'text.require' => '缺少参数text!',
            'image.require' => '缺少参数image!',
            'file.require' => '缺少参数file!',
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        $data['createtime'] = $data['updatetime'] = time();
        Db::name("order_chat")->insertGetId($data);
        $this->success('消息记录成功');
    }

    public function create()
    {
        $url = 'http://api-cn.ronghub.com/chatroom/create.json';
        $id = 1;
        $name = "聊天室";
        $postData = 'id='.$id.'&name='.$name;
        $row = json_decode($this->request_post_push($url, $postData),true);
        print_r($row);die;
    }

    public function select()
    {
        $url = 'http://api-cn.ronghub.com/chatroom/query.json';
        $id = 1;
        $postData = 'chatroomId='.$id;
        $row = json_decode($this->request_post_push($url, $postData),true);
        print_r($row);die;
    }
}