Api.php
23.7 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
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
<?php
namespace app\common\controller;
use app\api\model\City2;
use app\api\model\Cm0address;
use app\api\model\Cm0bi;
use app\api\model\Cm0che0user;
use app\api\model\Cm0order;
use app\api\model\Cm0pei0good;
use app\api\model\Cm0s40order;
use app\api\model\GuanS4;
use app\api\model\Litestoregoods;
use app\api\model\Litestoregoodsspec;
use app\api\model\User;
use app\common\library\Auth;
use think\Config;
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 EasyWeChat\Foundation\Application;
/**
* 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 = [];
//拉黑操作
protected $hui = [];
/**
* 权限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()
{
// 处理跨域
header('Content-Type: text/html;charset=utf-8');
header('Access-Control-Allow-Origin:*'); // *代表允许任何网址请求
header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); // 允许请求的类型
header('Access-Control-Allow-Credentials: true'); // 设置是否允许发送 cookies
header('Access-Control-Allow-Headers: Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin'); // 设置允许自定义请求头的字段
// if (Config::get('url_domain_deploy')) {
// $domain = Route::rules('domain');
// if (isset($domain['api'])) {
// if (isset($_SERVER['HTTP_ORIGIN'])) {
// header("Access-Control-Allow-Origin: " . $this->request->server('HTTP_ORIGIN'));
// header('Access-Control-Allow-Credentials: true');
// header('Access-Control-Max-Age: 86400');
// }
// if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
// if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
// header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
// }
// if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
// header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
// }
// }
// }
// }
//移除HTML标签
$this->request->filter('trim,strip_tags,htmlspecialchars');
$this->auth = Auth::instance();
$modulename = $this->request->module();
$controllername = strtolower($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);
// 检测是否需要验证登录
$ip = request()->ip();
if ($ip == '127.0.0.1') {
$this->init2($path);
} else {
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);
}
}
}
$user_id = $this->auth->id;
if ($user_id > 0) {
$switch = User::where('id', $user_id)->value('switch');
if ($switch == 1) {
if ($this->auth->match($this->hui)) {
$this->error('你已经被拉黑', '', 411);
}
}
}
$upload = \app\common\model\Config::upload();
// 上传信息配置后
Hook::listen("upload_config_init", $upload);
Config::set('upload', array_merge(Config::get('upload'), $upload));
// 加载当前控制器语言包
$this->loadlang($controllername);
}
private function init2($path)
{
$this->auth->direct(7);
// 判断是否需要验证权限
if (!$this->auth->match($this->noNeedRight)) {
// 判断控制器和方法判断是否有对应权限
if (!$this->auth->check($path)) {
$this->error(__('You have no permission'), null, 403);
}
}
}
/**
* 加载语言文件
* @param string $name
*/
protected function loadlang($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;
}
//钱转换成积分
protected function moneyFen($money = 0)
{
$cm0bi = Cm0bi::find();
return round($cm0bi['ping'] * $money * 0.01, 2);
}
//通过普通商品ID,和规格数组,找到此商品;
protected function findGood($id, $gui_arr)
{
$data = Litestoregoodsspec::where('goods_id', $id)->select();
$row = [];
foreach ($data as $k => $v) {
$diff = array_diff($v['sku_arr'], $gui_arr);
if (empty($diff)) {
$row = $v;
}
}
return $row;
}
//普通商品订单,可以换取的积分
protected function fen_pu($order_no)
{
$order = Cm0order::where('order_no', $order_no)->find();
$data = unserialize($order['data']);
$fen = 0;
foreach ($data['order_good'] as $k => $v) {
$good = Litestoregoodsspec::where('goods_id', $v['goods_id'])
->where('spec_sku_id', $v['spec_sku_id'])
->find();
$fen += $good['fen'];
}
return round($fen, 2);
}
//判断库存是否充足,普通商品
protected function ck_ku($order_no)
{
$order = Cm0order::where('order_no', $order_no)->find();
$data = unserialize($order['data']);
foreach ($data['order_good'] as $k => $v) {
$good2 = Litestoregoods::where('goods_id', $v['goods_id'])->find();
if (empty($good2['is_delete']) || $good2['is_delete'] == 0) {
$this->error($good2['goods_name'] . '已下架');
}
$good = Litestoregoodsspec::where('goods_id', $v['goods_id'])
->where('spec_sku_id', $v['spec_sku_id'])
->find();
if ($good['stock_num'] < $v['good']['num']) {//库存数量,小于等于购买数量
$this->error($good['name'] . '库存不足');
}
}
return ['code' => 1];
}
//判断库存是否充足,配件商品,4s店
protected function ck_ku_pei($order_no)
{
$order = Cm0s40order::where('order_no', $order_no)->find();
$data = unserialize($order['data']);
foreach ($data['order_good'] as $k => $v) {
$good2 = Cm0pei0good::where('id', $v['good']['id'])->find();
if (empty($good2['is_delete']) || $good2['is_delete'] == 0) {
$this->error($good2['name'] . '已下架');
}
if ($good2['ku_num'] < $v['good']['gou_num']) {
$this->error($good2['name'] . '库存不足');
}
}
}
//还有库存的商品id
protected function haveKuIds()
{
$goods_id_arr = Litestoregoodsspec::where('stock_num', 'gt', 0)->column('goods_id');
return array_unique($goods_id_arr);
}
//下订单时找地址
protected function getAddress($user_id, $address_id)
{
if (empty($address_id)) {
$address = Cm0address::where('user_id', $user_id)->where('is_mo', 1)->find();
} else {
$address = Cm0address::where('id', $address_id)->find();
}
return $address;
}
//下单时的ping_fen和s4_fen,给$data赋值
protected function orderFen($data, $user)
{
//用户的积分
$data['ping_fen'] = $user['ping_fen'];
$data['s4_fen'] = $user['s4_fen'];
$data['ping_money2'] = $user['ping_money'];
$data['s4_money2'] = $user['s4_money'];
if ($user['ping_money'] >= $data['all_pay']) {
$data['ping_money'] = "可抵扣全额";
} else {
$data['ping_money'] = "可抵扣" . $user['ping_money'] . "元";
}
if ($user['s4_money'] >= $data['all_pay']) {
$data['s4_money'] = "可抵扣全额";
} else {
$data['s4_money'] = "可抵扣" . $user['s4_money'] . "元";
}
return $data;
}
//生成二维码
protected function shengCode($width = 430, $scene = 1, $page = '', $type = '')
{
// $type='user';//代表给用户生成的
// $type='s4';//代表给s4店生成的
$access_token = $this->get_accessToken();
$url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' . $access_token;
// $scene = 'NO1000000';//用户的user_id
// $width = 430;
$userId=$this->auth->id ?? 0;
// $sceneData="userId:".$userId.",scene:".$scene;
$sceneData = ["userId"=>$userId,"scene"=>$scene];
$data['scene'] = $sceneData;
$data['width'] = intval($width);
// $data['page'] = "pages/check_status/check_status";//跳转到的页面路径
if (!empty($page)) {
$data['page'] = $page;//跳转到的页面路径
}
$data = json_encode($data);
$return = $this->https_request($url, $data);
if ($type == 'user') {
$path2 = '/assets/code/user/' . $scene . '.jpg';
} elseif ($type == 's4') {
$path2 = '/assets/code/s4/' . $scene . '.jpg';
} elseif ($type == 'peijian') {
$path2 = '/assets/code/peijian/' . $scene . '.jpg';
} elseif ($type == 'putong') {
$path2 = '/assets/code/putong/' . $scene . '.jpg';
} elseif ($type == 'baoyang') {
$path2 = '/assets/code/baoyang/' . $scene . '.jpg';
} elseif ($type == 'qiang4s') {
$path2 = '/assets/code/qiang4s/' . $scene . '.jpg';
} elseif ($type == 'chegood4s') {
$path2 = '/assets/code/chegood4s/' . $scene . '.jpg';
} elseif ($type == 's4active2') {
$path2 = '/assets/code/s4active2/' . $scene . '.jpg';
}
$image = public_url() . $path2;
//判断保存目录是否存在
$path = substr($image, 0, strrpos($image, "/"));
checkPath($path);
file_put_contents($image, $return);
return $path2;
}
//发送https请求
protected function https_request($url, $data = null)
{
$curl = curl_init();
//curl_setopt ( $curl, CURLOPT_SAFE_UPLOAD, false);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
if (!empty ($data)) {
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}
//获取accessToken
protected function get_accessToken()
{
$config = \config('wechat');
$app = new Application($config);
$accessToken = $app->access_token; // EasyWeChat\Core\AccessToken 实例
$token = $accessToken->getToken('true'); // token 字符串
return $token;
}
//图片上传7牛云
protected function qiniu($filePath = '', $fileName = '')
{
$fileName = substr($fileName, 1);
$config = get_addon_config('qiniu');
$policy = array(
'saveKey' => $fileName,
);
$auth = new \addons\qiniu\library\Auth($config['app_key'], $config['secret_key']);
$token = $auth->uploadToken($config['bucket'], null, $config['expire'], $policy);
$multipart = [
['name' => 'token', 'contents' => $token],
[
'name' => 'file',
'contents' => fopen($filePath, 'r'),
'filename' => $fileName,
]
];
try {
$client = new \GuzzleHttp\Client();
$res = $client->request('POST', $config['uploadurl'], [
'multipart' => $multipart
]);
// $code = $res->getStatusCode();
//成功不做任何操作
} catch (\GuzzleHttp\Exception\ClientException $e) {
$this->error("上传失败");
}
}
//给车辆设为默认[只剩一个]
protected function cheLast()
{
$user_id = $this->auth->id;
$data = Cm0che0user::where('user_id', $user_id)->select();
if (sizeof($data) == 1) {//如果只剩这一个了,则把他设为默认的
Cm0che0user::where('id', $data[0]['id'])->update(['is_mo' => 1]);
}
}
//存4s的订单信息
protected function saveOrder4s($order_no, $order)
{
$data = Cm0s40order::where('order_no', $order_no)->value('data');
$data = unserialize($data);
$data['order2'] = $order;
Cm0s40order::where('order_no', $order_no)->update([
'data' => serialize($data),
]);
}
//存平台订单信息
protected function saveOrder($order_no, $order)
{
$data = Cm0order::where('order_no', $order_no)->value('data');
$data = unserialize($data);
$data['order2'] = $order;
Cm0order::where('order_no', $order_no)->update([
'data' => serialize($data),
]);
}
//保存平台的地址信息
protected function saveAddress($order_no, $address_id)
{
$data1 = Cm0order::where('order_no', $order_no)->value('data');
$data2 = Cm0s40order::where('order_no', $order_no)->value('data');
if (!empty($data1)) {
$data = unserialize($data1);
$data['address'] = Cm0address::where('id', $address_id)->find();
Cm0order::where('order_no', $order_no)->update([
'data' => serialize($data),
]);
}
if (!empty($data2)) {
$data = unserialize($data2);
$data['address'] = Cm0address::where('id', $address_id)->find();
Cm0s40order::where('order_no', $order_no)->update([
'data' => serialize($data),
]);
}
}
//1代表是开起正常定位
protected function dingWei2($type = 0)
{
$user_id = $this->auth->id;
$ip = request()->ip();
if ($ip == '127.0.0.1') {
$ip = "180.90.191.62";
}
$ak = "9e9GRCW4APBFcwrZENY4UAhn5utHkNl7";
$url = "http://api.map.baidu.com/location/ip?ak={$ak}&ip={$ip}&coor=bd09ll";
$city_data = file_get_contents($url);
$city = json_decode($city_data, true);
if (isset($city['content']['address_detail']['city'])) {
$city_find = City2::where('mergename', 'like', "%" . $city['content']['address_detail']['city'] . "%")
->where('mergename', 'like', "%" . $city['content']['address_detail']['province'] . "%")
->find();
} else {
$city_find = City2::where('id', 2)->find();
}
if ($type == 0) {
if ($user_id) {
$city_id = User::where('id', $user_id)->value('city_id');
$res = City2::where('id', $city_id)->find();
if ($res) {
return $res;
}
}
}
return $city_find;
}
//检查手机号
protected function ck_phone($phone)
{
if (!ck_phone($phone)) {
$this->error('手机号格式不正确');
}
}
//自己有没有关注4S店
protected function guan_4s($s4_id)
{
$user_id = $this->auth->id;
$find = GuanS4::where('user_id', $user_id)
->where('s4_id', $s4_id)
->find();
if (empty($find)) {
return 0;
} else {
return 1;
}
}
//处理字段数据 //二维数组形式
protected function chu_data($field_str, $data)
{
return chu_data($field_str, $data);
}
//处理数据 //一维的
protected function chu_find($field_str, $find)
{
return chu_find($field_str, $find);
}
//validate 检查是否存在
protected function check_data($check_arr)
{
// $check_arr = ['id' => '用户ID', 'che_id' => '车的ID'];
$rule = [];
foreach ($check_arr as $k => $v) {
$row = [];
$str = "{$k}|{$v}";
$row[$str] = 'require';
$rule = array_merge($rule, $row);
}
$validate = new \think\Validate($rule);
$param = $this->request->param();
$result = $validate->check($param);
if (!$result) {
$this->error($validate->getError());
}
}
//获取4s店id
protected function get_s4_id()
{
$user_id = $this->auth->id;
$user = User::where('id', $user_id)->find();
return $user['s4_id'];
}
//try错误信息
protected function err_msg($e)
{
$err = $e->getTrace();
$msg = err_msg($err);
$this->error($msg);
}
}