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 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
<?php


namespace app\api\controller;

use app\api\model\Equipment;
use app\api\model\SubscribLog;
use app\common\controller\Api;
use think\Db;

/**
 * 应用端接口
 */
class App extends Api
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $api_model = null;
    protected $api_request_model = null;


    public function _initialize()
    {
        $this->api_model = new \app\api\model\Api();
        $this->api_request_model = new \app\api\model\ApiRequest();
    }

    /**
     * 获取access_token
     *
     * @ApiTitle    (获取access_token)
     * @ApiSummary  (获取access_token)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/app/getAccessToken)
     * @ApiParams   (name="app_id", type="integer", required=true, description="应用appid")
     * @ApiParams   (name="app_key", type="string", required=true, description="应用appkey")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功',
    'data':'{
        'access_token':'身份验证token',
        'expires_in':'过期时间',
    }'
    })
     */
    public function getAccessToken() {
        if($this->request->isGet()) {
            $data = $this->request->param();
            $validate = new \think\Validate([
                'app_id'                => 'require',
                'app_key'               => 'require'
            ]);
            $validate->message([
                'app_id.require'        => 'app_id参数错误!',
                'app_key.require'       => 'app_key参数错误!'
            ]);
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }
            // 查询数据
            $api_where = $api_request = [
                'app_id' => $data['app_id'],
                'app_key' => $data['app_key']
            ];
            $apiInfo = $this->api_model->where($api_where)->find();
            if(!$apiInfo) {
                $this->error('app_id参数错误');
            }
            // 添加接口访问记录并返回数据
            $api_request['access_token'] = $request_data['access_token'] = sha1(md5($apiInfo['app_id'].$apiInfo['app_key']).time().createNoncestr(10));
            $api_request['api_name'] = '获取access_token';
            $api_request['overtime'] = time() + 7200;
            $api_request['apply_data'] = json_encode($data);
            $request_data['expires_in'] = 7200;
            $result = $this->api_request_model->save($api_request);
            if(!$result) {
                $this->error('系统繁忙,请稍后再试');
            }
            $this->success('成功', $request_data);
        } else {
            $this->error('非法请求');
        }
    }

    /**
     * 数板列表
     *
     * @ApiTitle    (数板列表)
     * @ApiSummary  (数板列表)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/app/getEquipmentList)
     * @ApiParams   (name="app_id", type="integer", required=true, description="应用appid")
     * @ApiParams   (name="access_token", type="string", required=true, description="身份验证token")
     * @ApiParams   (name="number", type="string", required=true, description="数板仪编号")
     * @ApiParams   (name="start_time", type="string", required=true, description="开始时间")
     * @ApiParams   (name="end_time", type="string", required=true, description="结束时间")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功',
    'data':'{
    'access-token':'身份验证token',
    'expires_in':'过期时间',
    }'
    })
     */
    public function getEquipmentList() {
        if($this->request->isPost()) {
            $data = $this->request->param();
            $validate = new \think\Validate([
                'app_id'                => 'require',
                'access_token'          => 'require',
                'number'                => 'require',
//                'start_time'            => 'require',
//                'end_time'              => 'require'
            ]);
            $validate->message([
                'app_id.require'        => 'app_id参数错误!',
                'access_token.require'  => 'access_token参数错误!',
                'number.require'        => 'number参数错误!',
//                'start_time.require'    => 'start_time参数错误!',
//                'end_time.require'      => 'end_time参数错误!'
            ]);
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }
            $access_token = $data['access_token'];
            // 验证token是否过期
            $api_id = $this->check($data['app_id'],$access_token);
            // 查询数板仪列表
            $end_time = time();
            $start_time = $end_time - 90 * 24 * 60 * 60;
            $equipment_model = new Equipment();
            $where = [
                'number'    => $data['number'],
                'createtime'=> ['between',[$start_time,$end_time]]
            ];
            $request_data = $equipment_model->where($where)->select();
            $request_data = collection($request_data)->toArray();
            $this->success('成功', $request_data);
        } else {
            $this->error('非法请求');
        }
    }


    // 定时执行订阅信息通知(未通知成功的数据)
    public function subscrib_notice() {
        $subscrib_log_model = new SubscribLog();
        $where = [
            'is_success' => 0,
        ];
        $list = $subscrib_log_model->where($where)->where('times','<>',0)->select();
        foreach ($list as $k=>$v) {
//            parse_str(substr($v['content'],1,strlen($v['content'])-2), $parameter);
            $headers = ["Content-type: application/json;charset='utf-8'"];
            $result = $this->curl($v['notice_url'],$v['content'],$headers);
            $array = json_decode($result,true);
            if($array['code'] == 200) {
                // 发送订阅信息成功
                $update = [
                    'id' => $v['id'],
                    'is_success' => 1,
                ];
                $subscrib_log_model::update($update);
            }
            if($v['times'] > 0) {
                // 减少发送订阅信息次数
                $update = [
                    'id' => $v['id'],
                    'times' => $v['times'] - 1,
                ];
                // 如果到了最后一次通知,则将通知状态改为成功
                if($v['times'] == 1) {
                    $update['is_success'] = 1;
                }
                $subscrib_log_model::update($update);
            }
        }
//        \think\facade\Log::write('执行未通知成功回调'.date('Y-m-d H:i:s',time()),'subscrib_notice');
    }

    // 将信息通知给订阅系统
    private function notice($type, $subscrib_id, $content, $subscrib_log_type = 1) {
        $where = [
            'a.delete_time' => 0,
            'as.type' => $type,
            'as.subscrib_id' => $subscrib_id
        ];
        $apiList = $this->api_model->alias('a')
            ->join('__API_SUBSCRIB__ as','a.id = as.api_id')
            ->field('a.id,a.times,a.callback')
            ->where($where)
            ->select();
        return $this->send($apiList, $subscrib_id, $type, $content, $subscrib_log_type);
    }

    // 发送订阅消息
    private function send($subscribList, $subscrib_id, $type, $content, $subscrib_log_type = 1) {
        $subscrib_log_model = new SubscribLog();

        parse_str($content,$arr);
        $content = json_encode($arr);

        foreach ($subscribList as $k=>$v) {
            $insert = [
                'api_id' => $v['id'],
                'type' => $subscrib_log_type,
                'subscrib_id' => $subscrib_id,
                'notice_url' => $v['callback'],
                'content' => $content,
                'create_time' => time(),
            ];
            if($v['times'] == 0) {
                $v['times'] = -1;
            }
            $insert['times'] = $v['times'];
            $insert_result = $subscrib_log_model::create($insert);

            $headers = ["Content-type: application/json;charset='utf-8'"];
            $result = json_decode($this->curl($v['callback'],$content,$headers),true);

            if(empty($result['code'])) {
                //发送订阅信息成功
                $update = [
                    'id' => $insert_result->id,
                    'is_success' => 1
                ];
                $subscrib_log_model::update($update);
            }

//            json_decode($this->curl('http://rz.178games.net/api/callback/gjr',$content,$headers),true);
        }
        return true;
    }

    /**
     * 检查access-token是否过期
     * @param $app_id
     * @param $access_token
     */
    private function check($app_id,$access_token) {
        $api_request_where = [
            'api_request.app_id'        => $app_id,
            'api_request.access_token'  => $access_token
        ];
        $apiRequestInfo = $this->api_request_model->with(['api'])->where($api_request_where)->find();
        if(!$apiRequestInfo) {
            $this->error('access_token不存在');
        }
        if($apiRequestInfo['overtime'] < time()) {
            $this->error('access_token已过期');
        }
        return $apiRequestInfo;
    }
    /**
     * 数管图片识别
     *
     * @ApiTitle    (数管图片识别)
     * @ApiSummary  (数管图片识别)
     * @ApiMethod   (POST/GET)
     * @ApiRoute    (/api/app/getImageInfo)
     * @ApiParams   (name="app_id", type="integer", required=true, description="应用appid")
     * @ApiParams   (name="access_token", type="string", required=true, description="身份验证token")
     * @ApiParams   (name="customer_id", type="integer", required=true, description="用户id")
     * @ApiParams   (name="url", type="string", required=true, description="图片地址")
     * @ApiParams   (name="image_id", type="string", required=true, description="图片id")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="SUCCESS")
     * @ApiReturnParams   (name="data", type="object", sample="{'image_id':'int','timestamp':'string','result':{'id':'int','type':'string','total':'int','confirmation':'int','distrust':'int','image_path':'int'}}", description="扩展数据返回")
     * @ApiReturn   ({
        'code':'1',
        'msg':'返回成功',
        'data':'{
            'image_id':'图片id',
            'timestamp':'时间戳',
            'result':{
                'id':'ID',
                'type':'识别出的管的类型及大小',
                'total':'识别总数量',
                'confirmation':'确认数量',
                'distrust':'疑似数量',
                'image_path':'图片路径'
            },
        }'
    })
     */
    public function getImageInfo(){
        $param = $this->request->param();
        $validate = new \think\Validate([
            'app_id' => 'require',
            'customer_id' => 'require',
            'access_token' => 'require',
            'url' => 'require',
            'image_id' => 'require',
        ]);
        if (!$validate->check($param)) {
            $this->error($validate->getError());
        }
        $app_id = $param['app_id'];
        $customer_id = $param['customer_id'];
        $access_token = $param['access_token'];
        $url = $param['url'];
        $image_id = $param['image_id'];
        //验证token是否过期
        $api = $this->check($app_id,$access_token);
        //保存图片
        $file = $this->saveImage($url);
        //请求地址
        $url = config('validate.shuguan')['url'];
        $files = realpath(ltrim(".".$file, '@'));
        $files = new \CURLFile($files);
        $key = $this->getKey(20,false);
        $param['files'] = $files;
        $param['timestamp'] = date('Y-m-d H:i:s');
        $param['key'] = $key;
        $param['image_id'] = $image_id;
        $param['sign'] = $this->getSign($param);
        $result = $this->httpPost($url,$param);
        $data = json_decode($result,true);
        Db::startTrans();
        //保存数管信息
        $arr = [
            'api_id' => $api['api']['id'],
            'customer_id' => $api['api']['customer_id'],
            'yingyong_id' => $customer_id,
            'image_id' => $image_id,
            'files' => $file,
            'timestamp' => $param['timestamp'],
            'key' => $key,
            'sign' => $param['sign'],
            'createtime' => time(),
        ];
        $result1 = Db::name('shuguan')->insertGetId($arr);
        if(!$result1){
            Db::rollback();
            $this->error('sql执行失败');
        }
        //保存数管接口返回数据
        if(!empty($data['result'])){
            $arr2 = [];
            foreach($data['result'] as $key => $r){
                $arr1 = [
                    'shuguan_id' => $result1,
                    'type' => $r['type'],
                    'total' => $r['total'],
                    'confirmation' => $r['confirmation'],
                    'distrust' => $r['distrust'],
                    'image_path' => $r['image_path'],
                    'createtime' => time(),
                ];
                $arr2[] = $arr1;
            }
            $result2 = Db::name('shuguan_log')->insertAll($arr2);
            if(!$result2){
                Db::rollback();
                $this->error('sql执行失败');
            }
        }
        Db::commit();
        $this->success('SUCCESS',$result);
    }

    /**
     * 模拟调用
     */
    public function test(){
        dump(getAddress("N39.085660E117.068135"));
        exit();
        $url = "http://gangjuren.net/api/app/getImageInfo";
        $arr = [
            'url' => "http://company.zzspjob.com/6b408e79f3a21ac02746b218f6cbc99@3x.png",
            'app_id' => 'gjra2g11dg56ad7bb71',
            'customer_id' => '1',
            'access_token' => 'e508a6c25ed2ec1237fa8a0ba8a09357ff83b8c8',
            'image_id' => '1',
        ];
        $result = $this->httpPost($url,$arr);
        $this->success('',$result);
    }

    /**
     * 保存图片
     * @param $url
     * @return string
     */
    public function saveImage($url){
        $date = date('Ymd');
        $savePath = "./uploads/shuguan/$date/";
        if (!file_exists($savePath)){
            mkdir($savePath, 0777,true);
        }
        $image = file_get_contents($url);
        $file_name = md5(uniqid(rand())).".png";
        file_put_contents($savePath.$file_name,$image);
        return "/uploads/shuguan/$date/$file_name";
    }

    /**
     * 仿form-data提交表单
     * @param $url
     * @param $data
     * @return mixed
     */
    private function httpPost($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_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_POST, true); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS,  $data); // Post提交的数据包
        //curl_setopt($curl, CURLOPT_TIMEOUT, 120); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, false); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // 获取的信息以文件流的形式返回
        $result = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Error POST'.curl_error($curl);
        }
        curl_close($curl); // 关键CURL会话
        return $result; // 返回数据
    }

    /**
     * 获取随机字符串
     * @param $len 长度
     * @param bool $special 是否需要特殊字符
     * @return string 返回随机字符串
     */
    public function getKey($len, $special=true){
        $chars = array(
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
            "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
            "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
            "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
            "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
            "3", "4", "5", "6", "7", "8", "9"
        );
        if($special){
            $chars = array_merge($chars, array(
                "!", "@", "#", "$", "?", "|", "{", "/", ":", ";",
                "%", "^", "&", "*", "(", ")", "-", "_", "[", "]",
                "}", "<", ">", "~", "+", "=", ",", "."
            ));
        }
        $charsLen = count($chars) - 1;
        shuffle($chars);//打乱数组顺序
        $str = '';
        for($i=0; $i<$len; $i++){
            $str .= $chars[mt_rand(0, $charsLen)];//随机取出一位
        }
        return $str;
    }
    /**
     * 生成签名
     * @param array $param 要加密的数组
     * @return string 返回签名
     */
    protected function getSign($param){
        $key = $param['key'];
        unset($param['key']);
        unset($param['files']);
        //按照参数名ASCII字典序排序
        ksort($param);
        $arr = [];
        foreach($param as $k => $p){
            $arr[] = $k."=".$p;
        }
        //拼接成字符串
        $str = implode('&',$arr);
        //与key拼接
        $str = $str."&key=".$key;
        //进行加密
        $signature = MD5($str);
        //转换成大写
        $signature = strtoupper($signature);
        return $signature;
    }
}