Common.php 9.3 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\Request;

/**
 * 公共接口
 */
class Common extends Api
{
    protected $noNeedLogin = ['init'];
    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 > 5) {
            $this->error('最多上传5张图片');
        }
        $url2 = '';
//        $fan = '';
        $host = 'http://q2ugvq3qf.bkt.clouddn.com';
        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();
                $accessKey = '-5ozVJMiyjFqls8LWSXNciKa6rkedQBAxLyPazuJ';
                $secretKey = 'nztK57AGUF6TKhfftSviQdakMK0VCsPYwRwjBJDg';
                $auth = new Auth($accessKey, $secretKey);
                $bucketName = 'guotrace';
                $token = $auth->uploadToken($bucketName);

                $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;
    }

    public function imgcode($user_id,$url)
    {
        $domain_name = $this->request->domain();//域名
        $url .= $url.'?id='.$user_id;
        if(empty($url)){
            $this->error('缺少必要参数');
        }
        if(!file_exists("./upload/code/code_$user_id.jpg")){
            $code = $this->getusercode($user_id,$url);
        }else{
            $code = "code/code_$user_id.jpg";
        }
        $data = $domain_name.'/upload/'.$code;
        return $data;
    }
    public function getusercode($user_id,$url){
        $savePath = './../public/upload/get_code/';
        $filename = "code_$user_id.jpg";
        if(!file_exists($savePath.$filename)){
            $access_token = $this->get_access_token();
            $qrcode = $this->imgShare($user_id,$access_token,$url);
        }else{
            $qrcode = "code/code_".$user_id.".jpg";
        }
        return $qrcode;
    }
    public function imgShare($user_id,$access_token,$path){
        $url = "https://api.weixin.qq.com/wxa/getwxacode?access_token=".$access_token;
        $post['path'] = $path;
        $post['width'] = 280;
        $result = $this->curl($url, json_encode($post));
        $array = json_decode($result, true);
        if($array['errmsg']) {
            return false;
        }
        // 分享二维码保存到用户数据
        if (!file_exists(ROOT_PATH . 'public' . DS . 'upload/code/')) {
            mkdir(ROOT_PATH . 'public' . DS . 'upload/code/', 0777, true);
        }
        $filename = "code_".$user_id.".jpg";
        $furl = ROOT_PATH . 'public' . DS . 'upload/code/'.$filename;
        file_put_contents($furl, $result);
        return "code/".$filename;
    }
    protected function curl($url, $post = null, $header = null) {
        // 初始化
        $curl = curl_init();
        // 设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        // 请求头
        if($header) {
            curl_setopt($curl,CURLOPT_HTTPHEADER,$header);
        }
        // 设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_NOBODY, 0);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        // 设置获取的信息以文件流的形式返回,而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        if($post) {
            curl_setopt($curl, CURLOPT_POST, 1);
            //把POST的变量加上
            curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
        }
        // 执行命令
        $data = curl_exec($curl);
        if (curl_errno($curl)) {
            $data = curl_error($curl);
        }
        return $data;
    }
    //获取access_token
    public function get_access_token()
    {
        $app_id = config('app_id');
        $app_secret = config('app_secret');
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$app_id.'&secret='.$app_secret;
        $res = $this->http_get($url);
        $json_arr = json_decode($res,true);
        $token = $json_arr['access_token'];
        return $token;
    }
    //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;
    }
    //curl post请求
    public function http_post($url,$data){
        $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_POST, true); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, false); // 开启header
        //curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);//请求头部
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // 获取的信息以文件流的形式返回
        $result = curl_exec($curl); //执行操作
        curl_close($curl);
        return $result;
    }


    public function shou($farm_id,$project_id,$page){
        //获取二维码链接
        $get_code_url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$this->get_access_token();
        $data = [
            'scene' => 'farm_id='.$farm_id.'&project_id='.$project_id,
            'width' => 280,
//            'page' => $page,
        ];
        $data = json_encode($data);
        $code_res = $this->http_post($get_code_url,$data);
        file_put_contents('upload/project'.$project_id.'.jpg',$code_res);
        $code_url = 'http://trace.w.brotop.cn/upload/project'.$project_id.'.jpg';
        return $code_url;
    }

}