123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156 |
- <?php
- namespace service;
- use think\exception\ValidateException;
- use app\admin\model\system\SmsAccessToken;
- class AccessTokenServeService extends HttpService
- {
-
- protected $account;
-
- protected $secret;
-
- protected $accessToken;
-
- protected $cacheTokenPrefix = "_crmeb_plat";
-
- protected $apiHost = 'http://sms.crmeb.net/api/';
- const USER_LOGIN = "user/login";
-
- public function __construct($account,$secret)
- {
- $this->account = $account;
- $this->secret = $secret;
- }
-
- public function getToken()
- {
- $accessTokenKey = md5($this->account . '_' . $this->secret . $this->cacheTokenPrefix);
- $cacheToken = CacheService::get($accessTokenKey,'');
- if (!$cacheToken) {
- $getToken = $this->getTokenFromServer();
- if (!is_array($getToken)) {
- return false;
- }
- CacheService::set($accessTokenKey, $getToken['access_token'], $getToken['expires_in'] - time() - 300);
- $cacheToken = $getToken['access_token'];
- }
- $this->accessToken = $cacheToken;
- return $cacheToken;
- }
-
- public function destroyToken()
- {
- $accessTokenKey = md5($this->account . '_' . $this->secret . $this->cacheTokenPrefix);
- return CacheService::rm($accessTokenKey);
- }
-
- public function getTokenFromServer()
- {
- $params = [
- 'account' => $this->account,
- 'secret' => md5($this->account . md5($this->secret)),
- ];
- $response = $this->postRequest($this->get(self::USER_LOGIN), $params);
- $response = json_decode($response, true);
- if (!$response) {
- throw new ValidateException('获取token失败');
- }
- if ($response['status'] === 200) {
- return $response['data'];
- } else {
- return $response['msg'];
- }
- }
-
- public function httpRequest($url,$data = [], $method = 'POST',$isHeader = true)
- {
- $header = [];
- if ($isHeader) {
- $this->getToken();
- if (!$this->accessToken) {
- throw new ValidateException('配置已更改或token已失效');
- }
- $header = ['Authorization:Bearer-' . $this->accessToken];
- }
- try {
- $res = $this->request($this->get($url), $method, $data, $header);
- if (!$res) {
- exception('发生异常,请稍后重试');
- }
- $result = json_decode($res, true) ?: false;
- return $result;
- } catch (\Throwable $e) {
- return $e->getMessage();
- }
- }
-
- public function get($apiUrl = '')
- {
- return $this->apiHost . $apiUrl;
- }
- }
|