OpenApi.php
2.5 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
<?php
namespace addons\facrm\library;
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\Validate;
/**
* 开放API控制器基类
*/
class OpenApi extends \app\common\controller\Api
{
/**
* 应用配置
* @var array
*/
protected $setting = array();
/**
* 初始化操作
* @access protected
*/
protected function _initialize()
{
parent::_initialize();
$appid = intval($this->request->server('HTTP_APPID', $this->request->request('appid')));
$timestamp = $this->request->server('HTTP_TIMESTAMP', $this->request->request('timestamp'));
$sign = $this->request->request('sign');//通信加密
if ((time() - $timestamp) > 600) {
$this->error(__("请求过期"));
}
if (!$sign) {
$this->error(__("签名不能为空"));
}
if (!$appid) {
$this->error(__("应用不存在"));
}
$this->setting = \app\admin\model\facrm\Setting::where('key', 'apps_setting_lists')->cache($appid . "apps_setting_lists")->find($appid);
if (!$this->setting) $this->error(__("应用不存在"));
$this->setting['values'] = json_decode($this->setting['values'], true);//获取器失效?TODO
if (!isset($this->setting['status']) || $this->setting['status'] != 1) {
$this->error(__("应用已被禁用"));
}
//IP认证
if (isset($this->setting['values']['white_list']) && $this->setting['values']['white_list']) {
$white_list_arr = explode(PHP_EOL, $this->setting['values']['white_list']);
if (!in_array(\request()->ip(),$white_list_arr))
$this->error(__("不允许访问IP"));
}
//echo md5($this->setting['id'] . $this->setting['values']['secret'] . $timestamp);
//签名认证
if (!$this->checkSign($sign, $timestamp)) {
$this->error(__('签名有误'), null, 403);
}
}
/**
* 认证签名 md5(appid+secret+timestamp) 如果要更加安全一点可以把IP也加进去
* @param $sign
* @param $timestamp
* @return bool|int
*/
private function checkSign($sign, $timestamp)
{
return md5($this->setting['id'] . $this->setting['values']['secret'] . $timestamp) == $sign ?? 0;
}
}