PingAn.php
3.2 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
<?php
namespace app\serviceapi\controller;
use app\serviceapi\model\TripartToken as TripartTokenModel;
use think\Cache;
/**
* 功能描述 平安接口
* Class PingAn
* @package app\commapi\controller\products
* Date: 2020/7/13
* Time: 14:44
* @author gxd
*/
class PingAn extends Controller
{
protected $token_url = 'https://test-api.pingan.com.cn:20443/oauth/oauth2/access_token?client_id=%s&grant_type=client_credentials&client_secret=%s';
protected $client_id = '';
protected $client_secret = '';
protected $token_key = "pingan_token_";
/**
* 函数功能描述 获取第三方token
* Date: 2020/7/13
* Time: 11:47
* @author gxd
*/
public function getToken($type, $refresh = 0)
{
$token = Cache::get($this->token_key.$type);
//不存在或者需要强制刷新缓存则进行刷新
if (!$token || $refresh) {
//首先查询数据库,如果数据库token未过期则缓存数据库token,否则重新获取
$tripart_token_model = new TripartTokenModel();
$list = $tripart_token_model->getTokenByType($type);
if($list && $list["start_time"] > time()) {
Cache::set($this->token_key.$type, $list["token"], $list["start_time"]-time());
return $list["token"];
} else {
$url = sprintf($this->token_url, $this->client_id, $this->client_secret);
$data = json_decode(file_get_contents($url), true);
if($data['ret']!=0){
return false;
}
//数据库存在数据直接更新并缓存
if($list) {
$list['token'] = $data['data']['access_token'];
$list['start_time'] = time()+$data["data"]["expires_in"]-60;
$res = $tripart_token_model->updateToken($list);
if ($res) {
Cache::set($this->token_key.$type, $data['data']['access_token'],$data["data"]["expires_in"]-60);
return $list->token;
} else {
return false;
}
} else {
//数据库不存在添加并缓存
$token_data = [
'token' => $data['data']['access_token'],
'token_type' => $type,
'start_time' => time()+$data["data"]["expires_in"]-60,
];
$res = $tripart_token_model->addToken($token_data);
if ($res) {
Cache::set($this->token_key.$type, $data['data']['access_token'],$data["data"]["expires_in"]-60);
return $token_data["token"];
} else {
return false;
}
}
}
} else {
return $token;
}
}
/**
* 函数功能描述 生成微妙
* @return float
* Date: 2020/7/13
* Time: 15:42
* @author gxd
*/
protected function microsecond()
{
$t = explode(" ", microtime());
$microsecond = round(round($t[1] . substr($t[0], 2, 3)));
return $microsecond;
}
}