Api.php
22.9 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
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
<?php
namespace app\common\controller;
use app\common\library\Auth;
use think\Config;
use think\Db;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\Hook;
use think\Lang;
use think\Loader;
use think\Request;
use think\Response;
use think\Route;
use think\Validate;
/**
* API控制器基类
*/
class Api
{
/**
* @var Request Request 实例
*/
protected $request;
/**
* @var bool 验证失败是否抛出异常
*/
protected $failException = false;
/**
* @var bool 是否批量验证
*/
protected $batchValidate = false;
/**
* @var array 前置操作方法列表
*/
protected $beforeActionList = [];
/**
* 无需登录的方法,同时也就不需要鉴权了
* @var array
*/
protected $noNeedLogin = [];
/**
* 无需鉴权的方法,但需要登录
* @var array
*/
protected $noNeedRight = [];
/**
* 权限Auth
* @var Auth
*/
protected $auth = null;
/**
* 默认响应输出类型,支持json/xml
* @var string
*/
protected $responseType = 'json';
/**
* 构造方法
* @access public
* @param Request $request Request 对象
*/
public function __construct(Request $request = null)
{
$this->request = is_null($request) ? Request::instance() : $request;
// 控制器初始化
$this->_initialize();
// 前置操作方法
if ($this->beforeActionList) {
foreach ($this->beforeActionList as $method => $options) {
is_numeric($method) ?
$this->beforeAction($options) :
$this->beforeAction($method, $options);
}
}
}
/**
* 初始化操作
* @access protected
*/
protected function _initialize()
{
//跨域请求检测
check_cors_request();
//移除HTML标签
$this->request->filter('trim,strip_tags,htmlspecialchars');
$this->auth = Auth::instance();
$modulename = $this->request->module();
$controllername = Loader::parseName($this->request->controller());
$actionname = strtolower($this->request->action());
// token
$token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
$path = str_replace('.', '/', $controllername) . '/' . $actionname;
// 设置当前请求的URI
$this->auth->setRequestUri($path);
// 检测是否需要验证登录
if (!$this->auth->match($this->noNeedLogin)) {
//初始化
$this->auth->init($token);
//检测是否登录
if (!$this->auth->isLogin()) {
$this->error(__('Please login first'), null, 401);
}
// 判断是否需要验证权限
if (!$this->auth->match($this->noNeedRight)) {
// 判断控制器和方法判断是否有对应权限
if (!$this->auth->check($path)) {
$this->error(__('You have no permission'), null, 403);
}
}
} else {
// 如果有传递token才验证是否登录状态
if ($token) {
$this->auth->init($token);
}
}
$upload = \app\common\model\Config::upload();
// 上传信息配置后
Hook::listen("upload_config_init", $upload);
Config::set('upload', array_merge(Config::get('upload'), $upload));
// 加载当前控制器语言包
$this->loadlang($controllername);
}
/**
* 加载语言文件
* @param string $name
*/
protected function loadlang($name)
{
$name = Loader::parseName($name);
Lang::load(APP_PATH . $this->request->module() . '/lang/' . $this->request->langset() . '/' . str_replace('.', '/', $name) . '.php');
}
/**
* 操作成功返回的数据
* @param string $msg 提示信息
* @param mixed $data 要返回的数据
* @param int $code 错误码,默认为1
* @param string $type 输出类型
* @param array $header 发送的 Header 信息
*/
protected function success($msg = '', $data = null, $code = 1, $type = null, array $header = [])
{
$this->result($msg, $data, $code, $type, $header);
}
/**
* 操作失败返回的数据
* @param string $msg 提示信息
* @param mixed $data 要返回的数据
* @param int $code 错误码,默认为0
* @param string $type 输出类型
* @param array $header 发送的 Header 信息
*/
protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = [])
{
$this->result($msg, $data, $code, $type, $header);
}
/**
* 返回封装后的 API 数据到客户端
* @access protected
* @param mixed $msg 提示信息
* @param mixed $data 要返回的数据
* @param int $code 错误码,默认为0
* @param string $type 输出类型,支持json/xml/jsonp
* @param array $header 发送的 Header 信息
* @return void
* @throws HttpResponseException
*/
protected function result($msg, $data = null, $code = 0, $type = null, array $header = [])
{
$result = [
'code' => $code,
'msg' => $msg,
'time' => Request::instance()->server('REQUEST_TIME'),
'data' => $data,
];
// 如果未设置类型则自动判断
$type = $type ? $type : ($this->request->param(config('var_jsonp_handler')) ? 'jsonp' : $this->responseType);
if (isset($header['statuscode'])) {
$code = $header['statuscode'];
unset($header['statuscode']);
} else {
//未设置状态码,根据code值判断
$code = $code >= 1000 || $code < 200 ? 200 : $code;
}
$response = Response::create($result, $type, $code)->header($header);
throw new HttpResponseException($response);
}
/**
* 前置操作
* @access protected
* @param string $method 前置操作方法名
* @param array $options 调用参数 ['only'=>[...]] 或者 ['except'=>[...]]
* @return void
*/
protected function beforeAction($method, $options = [])
{
if (isset($options['only'])) {
if (is_string($options['only'])) {
$options['only'] = explode(',', $options['only']);
}
if (!in_array($this->request->action(), $options['only'])) {
return;
}
} elseif (isset($options['except'])) {
if (is_string($options['except'])) {
$options['except'] = explode(',', $options['except']);
}
if (in_array($this->request->action(), $options['except'])) {
return;
}
}
call_user_func([$this, $method]);
}
/**
* 设置验证失败后是否抛出异常
* @access protected
* @param bool $fail 是否抛出异常
* @return $this
*/
protected function validateFailException($fail = true)
{
$this->failException = $fail;
return $this;
}
/**
* 验证数据
* @access protected
* @param array $data 数据
* @param string|array $validate 验证器名或者验证规则数组
* @param array $message 提示信息
* @param bool $batch 是否批量验证
* @param mixed $callback 回调方法(闭包)
* @return array|string|true
* @throws ValidateException
*/
protected function validate($data, $validate, $message = [], $batch = false, $callback = null)
{
if (is_array($validate)) {
$v = Loader::validate();
$v->rule($validate);
} else {
// 支持场景
if (strpos($validate, '.')) {
list($validate, $scene) = explode('.', $validate);
}
$v = Loader::validate($validate);
!empty($scene) && $v->scene($scene);
}
// 批量验证
if ($batch || $this->batchValidate) {
$v->batch(true);
}
// 设置错误信息
if (is_array($message)) {
$v->message($message);
}
// 使用回调验证
if ($callback && is_callable($callback)) {
call_user_func_array($callback, [$v, &$data]);
}
if (!$v->check($data)) {
if ($this->failException) {
throw new ValidateException($v->getError());
}
return $v->getError();
}
return true;
}
/**
* 刷新Token
*/
protected function token()
{
$token = $this->request->param('__token__');
//验证Token
if (!Validate::make()->check(['__token__' => $token], ['__token__' => 'require|token'])) {
$this->error(__('Token verification error'), ['__token__' => $this->request->token()]);
}
//刷新Token
$this->request->token();
}
/**
* 获取OpenId
*/
protected function OpenId($code)
{
$ch = curl_init();
$url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . appid . "&secret=" . secret . "&js_code=$code&grant_type=authorization_code";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$output = curl_exec($ch);
if ($output === FALSE) echo "CURL Error:" . curl_error($ch);
curl_close($ch);
$CurlResult = json_decode($output, true);
return $CurlResult['openid'];
}
/**
* 检测Token
*/
protected function IsToken()
{
$token = $this->request->header();
if (empty($token['token'])) $this->error('请登录后在操作', '', 401);
$is_token = Db::name('user')->where(['token' => $token['token']])->find();
if (!$is_token) $this->error('登陆已过期,请重新登陆', '', 90001);
return $is_token['id'];
}
/**
* 检测Token
*/
protected function Res($res)
{
if ($res) $this->success('成功', 1);
else$this->error('失败', 0);
}
/**
* 头像
*/
protected function UserAvatar($Url)
{
if (strstr($Url, '/uploads/')) return cdnurl($Url);
else return $Url;
}
/**
* 剩余飞行时间
*/
protected function HaveMinutes($UserId)
{
$Minutes = Db::name('goods_after')->where('user_id', $UserId)->field('SupMinutes')->select();
if (empty($Minutes)) return 0;
else foreach ($Minutes as $k => $v) {
$Sum[] = $v['SupMinutes'];
}
return array_sum($Sum);
}
/**
* 生成支付单号
*/
protected function PayOrder()
{
//生成订单号
$PayOrder = date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
return $PayOrder;
}
/**
* 日期转换
*/
protected function WeekAttr($Week)
{
//年月日
$WeekArray = array("日", "一", "二", "三", "四", "五", "六"); //先定义一个数组
//周*
$IsWeek = "周" . $WeekArray[date("w", strtotime($Week))];
$List = [
'date' => $Week,
'week' => $IsWeek,
];
return $List;
}
/**
* 去除重复数组
*/
protected function UnsetDobel($Array, $Key)
{
$tmp_arr = array();
foreach ($Array as $k => $v) {
if (in_array($v[$Key], $tmp_arr)) //搜索$v[$key]是否在$tmp_arr数组中存在,若存在返回true
{
unset($Array[$k]); //销毁一个变量 如果$tmp_arr中已存在相同的值就删除该值
} else {
$tmp_arr[$k] = $v[$Key]; //将不同的值放在该数组中保存
}
}
//ksort($arr); //ksort函数对数组进行排序(保留原键值key) sort为不保留key值
return array_values($Array);
}
/**
* 拦截当天
*/
protected function IsToDay($Id)
{
$to = strtotime(date("Y-m-d", strtotime("+1 day")));
if (Db::name('sun')->where(['id' => $Id])->value('createtime') < $to) $this->error('不能预约今天', 0);
}
/**
* VIP等级拦截
*/
protected function iSVip($Vip, $Id)
{
if ($Vip == 1) {
$data = date('Y-m-d', time());
$catime = strtotime($data) + 86400 * 3;
$time = Db::name('sun')->where(['id' => $Id])->value('createtime');
if ($catime < $time) $this->error('您不能预约超过两天后的时间', 0);
}
if ($Vip == 2) {
$data = date('Y-m-d', time());
$catime = strtotime($data) + 86400 * 6;
$time = Db::name('sun')->where(['id' => $Id])->value('createtime');
if ($catime < $time) $this->error('您不能预约超过五天后的时间', 0);
}
}
/**
* 预约最大次数拦截
*/
protected function CountNum($UserId, $Id)
{
$createtime = Db::name('sun')->where(['id' => $Id])->value('createtime');
//没明白为啥要用between
// $map['sun_createtime'] = ['BETWEEN', [$createtime - 2, $createtime + 5]];
$map['sun_createtime'] = $createtime;
$map['status'] = ['NEQ', 2];
$count = Db::name('yuyue')->where(['user_id' => $UserId])->where($map)->select();
if (count($count) > 1) $this->error('超过最大可预约次数', 0);
}
/**
* 是否购买机型拦截
*/
protected function IsBuyPlaneType($UserID, $ID)
{
$Info = Db::name('sun')
->alias('s')
->where(['s.id' => $ID])
->join('plane p', 'p.id=s.plane_id')
->join('goods_after g', 'g.plane_type_id=p.plane_type_id')
->where('g.user_id', $UserID)
->field('g.SupMinutes,g.AfterMinutes')
->find();
if (empty($Info)) $this->error('您还不能预约本机型,该机型剩余小时不足,请完成购买后再预约');
if (($Info['SupMinutes'] - $Info['AfterMinutes']) < Db::name('choose_hours')->where('id', 1)->value('Minutes')) $this->error('您的飞行小时剩余不足,请尽快完成购买在进行预约');
}
/**
* 是否爽约
*/
protected function IsNoPrice($UserID)
{
$Map['status'] = ['EQ', 2];
$Map['type'] = ['EQ', 2];
$Map['no_price_type'] = ['EQ', 1];
$Map['user_id'] = ['EQ', $UserID];
$IsNoPrice = Db::name('yuyue')->where($Map)->select();
if (!empty($IsNoPrice)) $this->error('您的预约有爽约行为,需要先支付爽约费才可以进行预约', '', 1975);
}
/**
* 新增预约
*/
protected function YuYue($UserID, $ID)
{
if (Db::name('sun')->where('id', $ID)->value('status') == 3) $this->error('您选择的时间中含已被其他人预约的时间,请重新选择预约', 0);
/*预约列表信息*/
$Info = Db::name('sun')->where('id', $ID)->find();
/*查询教练*/
$TeacherId = Db::name('teacher_work')->where('plane_id', $Info['plane_id'])->where('time', strtotime(date('Y-m-d', Db::name('sun')->where('id', $ID)->value('createtime'))))->value('teacher_id');
if (empty($TeacherId)) $this->error('该飞机类型暂无教练', 0);
/*增加待扣除飞行时间*/
$GoodsAfter = Db::name('goods_after')->where('plane_type_id', Db::name('plane')->where('id', $Info['plane_id'])->value('plane_type_id'))->where('user_id', $UserID)->find();
if (empty($GoodsAfter)) $this->error('您还没有购买该产品', 0);
Db::name('goods_after')->where('plane_type_id', Db::name('plane')->where('id', $Info['plane_id'])->value('plane_type_id'))->where('user_id', $UserID)->update(['AfterMinutes' => $GoodsAfter['AfterMinutes'] + 60]);
/*更改预约列表状态*/
Db::name('sun')->where('id', $ID)->update(['status' => 3, 'user_id' => $UserID, 'updatetime' => time()]);
/*新增预约信息*/
$Insert = [
'user_id' => $UserID,
'sun_id' => $ID,
'sun_createtime' => $Info['createtime'],
'plane_id' => $Info['plane_id'],
'teacher_id' => $TeacherId,
'status' => 0,
'type' => 0,
'no_price_type' => 0,
'no_price' => 0,
'FlyMinutes' => 0,
'createtime' => time(),
'updatetime' => time()
];
$Res = Db::name('yuyue')->insert($Insert);
if (!$Res) $this->error('新增预约失败');
}
/**
* 取消预约限制
*/
protected function KillGroup($id)
{
$Info = Db::name('sun')->where('id', $id)->find();
$Date = date('Y-m-d', $Info['createtime']);
if ($Info['time_id'] == 12) $Time = strtotime(date("$Date" . ' ' . '7:00'));
if ($Info['time_id'] == 11) $Time = strtotime(date("$Date" . ' ' . '8:00'));
if ($Info['time_id'] == 10) $Time = strtotime(date("$Date" . ' ' . '9:00'));
if ($Info['time_id'] == 9) $Time = strtotime(date("$Date" . ' ' . '10:00'));
if ($Info['time_id'] == 8) $Time = strtotime(date("$Date" . ' ' . '11:00'));
if ($Info['time_id'] == 7) $Time = strtotime(date("$Date" . ' ' . '12:00'));
if ($Info['time_id'] == 6) $Time = strtotime(date("$Date" . ' ' . '13:00'));
if ($Info['time_id'] == 5) $Time = strtotime(date("$Date" . ' ' . '14:00'));
if ($Info['time_id'] == 4) $Time = strtotime(date("$Date" . ' ' . '15:00'));
if ($Info['time_id'] == 3) $Time = strtotime(date("$Date" . ' ' . '16:00'));
if ($Info['time_id'] == 2) $Time = strtotime(date("$Date" . ' ' . '17:00'));
if ($Info['time_id'] == 1) $Time = strtotime(date("$Date" . ' ' . '18:00'));
if ($Time < time() + 86400) $this->error('您的会员等级不能取消超过24小时的预约', 0);
}
/**
* 预约列表时间转换
*/
protected function TimeCrcle($Id)
{
$Sun = Db::name('sun')->where('id', $Id)->find();
if ($Sun['time_id'] == 1) $Time = strtotime(date('Y-m-d', $Sun['createtime']) . '18:00');
if ($Sun['time_id'] == 2) $Time = strtotime(date('Y-m-d', $Sun['createtime']) . '17:00');
if ($Sun['time_id'] == 3) $Time = strtotime(date('Y-m-d', $Sun['createtime']) . '16:00');
if ($Sun['time_id'] == 4) $Time = strtotime(date('Y-m-d', $Sun['createtime']) . '15:00');
if ($Sun['time_id'] == 5) $Time = strtotime(date('Y-m-d', $Sun['createtime']) . '14:00');
if ($Sun['time_id'] == 6) $Time = strtotime(date('Y-m-d', $Sun['createtime']) . '13:00');
if ($Sun['time_id'] == 7) $Time = strtotime(date('Y-m-d', $Sun['createtime']) . '12:00');
if ($Sun['time_id'] == 8) $Time = strtotime(date('Y-m-d', $Sun['createtime']) . '11:00');
if ($Sun['time_id'] == 9) $Time = strtotime(date('Y-m-d', $Sun['createtime']) . '10:00');
if ($Sun['time_id'] == 10) $Time = strtotime(date('Y-m-d', $Sun['createtime']) . '9:00');
if ($Sun['time_id'] == 11) $Time = strtotime(date('Y-m-d', $Sun['createtime']) . '8:00');
if ($Sun['time_id'] == 12) $Time = strtotime(date('Y-m-d', $Sun['createtime']) . '7:00');
return $Time;
}
/**
* @ApiInternal
* 分页
*/
function page_array($count, $page, $array, $order)
{
global $countpage; #定全局变量
$page = (empty($page)) ? '1' : $page; #判断当前页面是否为空 如果为空就表示为第一页面
$start = ($page - 1) * $count; #计算每次分页的开始位置
if ($order == 1) {
$array = array_reverse($array);
}
$totals = count($array);
$countpage = ceil($totals / $count); #计算总页面数
$pagedata = array();
$pagedata = array_slice($array, $start, $count);
return $pagedata; #返回查询数据
}
/**
* @ApiInternal
* 发送自定义短信
*/
public function SendSms($Mobile, $Message, $KillID, $type)
{
//1=禁飞,2=开飞
$sms_write = Db::name('sms_write')->where(['kill_id' => $KillID, 'mobile' => $Mobile, 'type' => $type])->find();
if (empty($sms_write)) {
//发送短信
$url = "https://api.mix2.zthysms.com/v2/sendSms";
$tKey = time();
$password = md5(md5('cxz307311') . $tKey);
$date = array(
'username' => 'feixingyuyue', //用户名
'password' => $password, //密码
'tKey' => $tKey, //tKey
//每个包最大支持2000个号码。
'mobile' => $Mobile,
'content' => $Message
);
$ret = $this->httpPost($url, $date);
if ($ret['code'] != 200) {
$this->error('短信发送失败');
} else {
Db::name('sms_write')->insert(['mobile' => $Mobile, 'type' => $type, 'kill_id' => $KillID]);
}
}
}
/**
* @ApiInternal
* httpPost
*/
function httpPost($url, $date)
{
$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, json_encode($date)); // Post提交的数据包
curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
curl_setopt($curl, CURLOPT_HEADER, false); // 显示返回的Header区域内容
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // 获取的信息以文件流的形式返回
curl_setopt($curl, CURLOPT_HEADER, false); //开启header
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8')); //类型为json
$result = curl_exec($curl); // 执行操作
if (curl_errno($curl)) {
echo 'Error POST' . curl_error($curl);
}
curl_close($curl); // 关键CURL会话
return json_decode($result, true); // 返回数据
}
/**
* @ApiInternal
*/
public function Send($UserId, $Id)
{
$createtime = Db::name('sun')->where(['id' => $Id])->value('createtime');
$map['sun_createtime'] = ['BETWEEN', [$createtime - 2, $createtime + 5]];
$map['status'] = ['NEQ', 2];
$count = Db::name('yuyue')->where(['user_id' => $UserId])->where($map)->select();
if (count($count) > 1) {
return false;
}
return true;
}
}