Api.php
22.6 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
<?php
namespace app\common\controller;
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 think\Db;
/**
* 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()
{
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);
// 检测是否需要验证登录
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
* @access protected
*/
protected function is_token($token)
{
if (empty($token['authorization'])) {
$this->error('请登录后在操作');
}
$is_token = Db::name('user')->where(['token' => $token['authorization']])->find();
if (!$is_token) {
$this->error('登陆已过期,请重新登陆');
}
return $is_token['id'];
}
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, true); //开启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 $result; // 返回数据
}
//检测验证码
function CheckCode($mobile, $code)
{
if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
$this->error(__('手机号不正确'));
}
$ret = Db::name('sms')->where('mobile', $mobile)->where('code', $code)->find();
if ($ret) {
$time = time();
$times = $ret['createtime'] + 60 * 10;
if ($time > $times) {
$this->error(__('验证码已失效'));
}
} else {
$this->error(__('验证码不正确'));
}
}
//三维数组转二维
function three_arr($arr)
{
foreach ($arr as $value) {
foreach ($value as $v) {
$new_return_arr[] = $v;
}
}
return $new_return_arr;
}
//购物车商品价格
function CalculateCommodityAmount($product_id, $shopcar_id, $buy_num)
{
$list = Db::name('shopcar')
->alias('s')
->where(['s.id' => $shopcar_id])
->join('product p', 'p.id=s.product_id')
->join('class_con c', 'c.id=p.class_con_id')
->join('logo l', 'l.id=p.logo_id')
->field('p.stock,s.product_id,s.id,p.avatar,p.name,c.class_con,l.logo,s.buy_num')
->select();
$tidu = Db::name('product')->where(['id' => $product_id])->find();
if ($tidu['tidu1'] != "") {
if ($buy_num < $tidu['tidu1'] & $buy_num > 0) {
$price = $buy_num * $tidu['price'];
}
}
if ($tidu['tidu2'] != "") {
if ($buy_num > $tidu['tidu1'] - 1 & $buy_num < $tidu['tidu2']) {
echo '2';
dump($tidu['price1']);
dump($buy_num);
$price = $buy_num * $tidu['price1'];
dump($price);
}
}
if ($tidu['tidu3'] != "") {
if ($buy_num > $tidu['tidu2'] - 1 & $buy_num < $tidu['tidu3']) {
echo '3';
$price = $buy_num * $tidu['price2'];
}
}
if ($tidu['tidu4'] != "") {
if ($buy_num > $tidu['tidu3'] - 1 & $buy_num < $tidu['tidu4']) {
echo '3';
$price = $buy_num * $tidu['price3'];
}
}
if ($tidu['tidu5'] != "") {
if ($buy_num > $tidu['tidu4'] - 1 & $buy_num < $tidu['tidu5']) {
$price = $buy_num * $tidu['price4'];
}
if ($buy_num > $tidu['tidu5'] - 1) {
$price = $buy_num * $tidu['price5'];
}
}
$tidu_new = Db::name('product')->where(['id' => $product_id])->select();
foreach ($tidu_new as $k => $v) {
$gradient[$k]['tidu1'] = $v['tidu1'];
$gradient[$k]['price1'] = $v['price1'];
$gradient[$k]['tidu2'] = $v['tidu2'];
$gradient[$k]['price2'] = $v['price2'];
$gradient[$k]['tidu3'] = $v['tidu3'];
$gradient[$k]['price3'] = $v['price3'];
$gradient[$k]['tidu4'] = $v['tidu4'];
$gradient[$k]['price4'] = $v['price4'];
$gradient[$k]['tidu5'] = $v['tidu5'];
$gradient[$k]['price5'] = $v['price5'];
$num = count($gradient[$k]);
for ($i = 0; $i < $num / 2; $i++) {
$n = $i + 1;
$info[$i]['tidu'] = $gradient[$k]['tidu' . $n];
$info[$i]['price'] = $gradient[$k]['price' . $n];
}
}
foreach ($list as $k => $v) {
$list[$k]['avatar'] = cdnurl($v['avatar'], true);
$list[$k]['price'] = round($price, 2);;
$list[$k]['gradient'] = $info;
}
return $list;
}
//购物车商品价格
function GenerateOrderPriceCalculation($product_id, $buy_num)
{
$list = Db::name('product')
->alias('p')
->where(['p.id' => $product_id])
->join('class_con c', 'c.id=p.class_con_id')
->join('logo l', 'l.id=p.logo_id')
->field('p.id,p.avatar,p.name,c.class_con,l.logo')
->select();
$tidu = Db::name('product')->where(['id' => $product_id])->find();
if ($buy_num < $tidu['tidu1'] & $buy_num > 0) {
$price = $buy_num * $tidu['price'];
}
if ($buy_num > $tidu['tidu1'] - 1 & $buy_num < $tidu['tidu2']) {
$price = $buy_num * $tidu['price1'];
}
if ($buy_num > $tidu['tidu2'] - 1 & $buy_num < $tidu['tidu3']) {
$price = $buy_num * $tidu['price2'];
}
if ($buy_num > $tidu['tidu3'] - 1 & $buy_num < $tidu['tidu4']) {
$price = $buy_num * $tidu['price3'];
}
if ($buy_num > $tidu['tidu4'] - 1 & $buy_num < $tidu['tidu5']) {
$price = $buy_num * $tidu['price4'];
}
if ($buy_num > $tidu['tidu5'] - 1) {
$price = $buy_num * $tidu['price5'];
}
$tidu_new = Db::name('product')->where(['id' => $product_id])->select();
foreach ($tidu_new as $k => $v) {
$gradient[$k]['tidu1'] = $v['tidu1'];
$gradient[$k]['price1'] = $v['price1'];
$gradient[$k]['tidu2'] = $v['tidu2'];
$gradient[$k]['price2'] = $v['price2'];
$gradient[$k]['tidu3'] = $v['tidu3'];
$gradient[$k]['price3'] = $v['price3'];
$gradient[$k]['tidu4'] = $v['tidu4'];
$gradient[$k]['price4'] = $v['price4'];
$gradient[$k]['tidu5'] = $v['tidu5'];
$gradient[$k]['price5'] = $v['price5'];
$num = count($gradient[$k]);
for ($i = 0; $i < $num / 2; $i++) {
$n = $i + 1;
$info[$i]['tidu'] = $gradient[$k]['tidu' . $n];
$info[$i]['price'] = $gradient[$k]['price' . $n];
}
}
$i = 0;
foreach ($info as $k => $v) {
$info[$k]['kid'] = $i;
$i++;
}
foreach ($list as $k => $v) {
$list[$k]['avatar'] = cdnurl($v['avatar'], true);
$list[$k]['price'] = round($price, 2);;
$list[$k]['gradient'] = $info;
}
return $list;
}
// 商品信息
function product_arr($product_id)
{
$list = Db::name('product')
->alias('p')
->where(['p.id' => $product_id])
->join('class_con c', 'c.id=p.class_con_id')
->join('logo l', 'l.id=p.logo_id')
->field('p.id,p.avatar,p.name,c.class_con,l.logo,p.fengzhuang,p.con,p.stock')
->select();
$tidu_new = Db::name('product')->where(['id' => $product_id])->select();
foreach ($tidu_new as $k => $v) {
$gradient[$k]['tidu1'] = $v['tidu1'];
$gradient[$k]['price1'] = $v['price1'];
$gradient[$k]['tidu2'] = $v['tidu2'];
$gradient[$k]['price2'] = $v['price2'];
$gradient[$k]['tidu3'] = $v['tidu3'];
$gradient[$k]['price3'] = $v['price3'];
$gradient[$k]['tidu4'] = $v['tidu4'];
$gradient[$k]['price4'] = $v['price4'];
$gradient[$k]['tidu5'] = $v['tidu5'];
$gradient[$k]['price5'] = $v['price5'];
$num = count($gradient[$k]);
for ($i = 0; $i < $num / 2; $i++) {
$n = $i + 1;
$info[$i]['tidu'] = $gradient[$k]['tidu' . $n];
$info[$i]['price'] = $gradient[$k]['price' . $n];
}
}
foreach ($list as $k => $v) {
$list[$k]['avatar'] = cdnurl($v['avatar'], true);
$list[$k]['gradient'] = $info;
}
return $list;
}
//删除购物车
public function DeleteCar($shop_id)
{
if (stristr($shop_id, ',')) {
$shop_id_arr = explode(',', $shop_id);
foreach ($shop_id_arr as $k => $v) {
$res[$k] = Db::name('shopcar')->where(['id' => $v])->delete();
}
} else {
Db::name('shopcar')->where(['id' => $shop_id])->delete();
}
}
//生成订单号
public function order_sn()
{
@date_default_timezone_set("PRC");
$order_id_main = date('YmdHis') . rand(10000000, 99999999);
//订单号码主体长度
$order_id_len = strlen($order_id_main);
$order_id_sum = 0;
for ($i = 0; $i < $order_id_len; $i++) {
$order_id_sum += (int)(substr($order_id_main, $i, 1));
}
//唯一订单号码(YYYYMMDDHHIISSNNNNNNNNCC)
$osn = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT); //生成唯一订单号
return $osn;
}
//去除重复数组
function second_array_unique_bykey($arr, $key)
{
$tmp_arr = array();
foreach ($arr as $k => $v) {
if (in_array($v[$key], $tmp_arr)) //搜索$v[$key]是否在$tmp_arr数组中存在,若存在返回true
{
unset($arr[$k]); //销毁一个变量 如果$tmp_arr中已存在相同的值就删除该值
} else {
$tmp_arr[$k] = $v[$key]; //将不同的值放在该数组中保存
}
}
//ksort($arr); //ksort函数对数组进行排序(保留原键值key) sort为不保留key值
return $arr;
}
/**
* Json方式 查询订单物流轨迹
*/
function getOrderTracesByJson($kgs, $number)
{
$requestData = "{'OrderCode':'','ShipperCode':'$kgs','LogisticCode':'$number'}";
$datas = array(
'EBusinessID' => '1649160',
'RequestType' => '1002',
'RequestData' => urlencode($requestData),
'DataType' => '2',
);
$datas['DataSign'] = $this->encrypt($requestData, 'fdf75944-8e72-4c72-b40f-534b0336b552');
$result = $this->sendPost('http://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx', $datas);
//根据公司业务处理返回的信息......
return $result;
}
/**
* post提交数据
* @param string $url 请求Url
* @param array $datas 提交的数据
* @return url响应返回的html
*/
function sendPost($url, $datas)
{
$temps = array();
foreach ($datas as $key => $value) {
$temps[] = sprintf('%s=%s', $key, $value);
}
$post_data = implode('&', $temps);
$url_info = parse_url($url);
if (empty($url_info['port'])) {
$url_info['port'] = 80;
}
$httpheader = "POST " . $url_info['path'] . " HTTP/1.0\r\n";
$httpheader .= "Host:" . $url_info['host'] . "\r\n";
$httpheader .= "Content-Type:application/x-www-form-urlencoded\r\n";
$httpheader .= "Content-Length:" . strlen($post_data) . "\r\n";
$httpheader .= "Connection:close\r\n\r\n";
$httpheader .= $post_data;
$fd = fsockopen($url_info['host'], $url_info['port']);
fwrite($fd, $httpheader);
$gets = "";
$headerFlag = true;
while (!feof($fd)) {
if (($header = @fgets($fd)) && ($header == "\r\n" || $header == "\n")) {
break;
}
}
while (!feof($fd)) {
$gets .= fread($fd, 128);
}
fclose($fd);
return $gets;
}
/**
* 电商Sign签名生成
* @param data 内容
* @param appkey Appkey
* @return DataSign签名
*/
function encrypt($data, $appkey)
{
return urlencode(base64_encode(md5($data . $appkey)));
}
}