- 扩优化代码

v6 v6.0.86
Chaim 4 years ago
parent 19c17933ff
commit 496b4a9ca6

@ -1,3 +1,6 @@
## v6.0.86 / 2020-07-17
- 扩优化代码
## v6.0.85 / 2020-07-17 ## v6.0.85 / 2020-07-17
- 扩展包不再包含数据库文件,允许通过配置文件路径的方式 - 扩展包不再包含数据库文件,允许通过配置文件路径的方式

@ -58,7 +58,9 @@ class ApiController extends stdClass
$this->app = $app; $this->app = $app;
$this->request = $app->request; $this->request = $app->request;
$this->app->bind('DtApp\ThinkLibrary\ApiController', $this); $this->app->bind('DtApp\ThinkLibrary\ApiController', $this);
if (in_array($this->request->action(), get_class_methods(__CLASS__))) $this->error('Access without permission.'); if (in_array($this->request->action(), get_class_methods(__CLASS__))) {
$this->error('Access without permission.');
}
$this->initialize(); $this->initialize();
} }
@ -99,9 +101,10 @@ class ApiController extends stdClass
/** /**
* 返回成功的操作 * 返回成功的操作
* @param mixed $msg 消息内容
* @param mixed $data 返回数据 * @param mixed $data 返回数据
* @param mixed $msg 消息内容
* @param integer $code 返回代码 * @param integer $code 返回代码
* @param string $name 参数名
*/ */
public function aesSuccess($data = [], $msg = 'success', $code = 0, $name = 'sniff_h5') public function aesSuccess($data = [], $msg = 'success', $code = 0, $name = 'sniff_h5')
{ {
@ -133,8 +136,14 @@ class ApiController extends stdClass
*/ */
public function callback($name, &$one = [], &$two = []) public function callback($name, &$one = [], &$two = [])
{ {
if (is_callable($name)) return call_user_func($name, $this, $one, $two); if (is_callable($name)) {
foreach ([$name, "_{$this->app->request->action()}{$name}"] as $method) if (method_exists($this, $method) && false === $this->$method($one, $two)) return false; return call_user_func($name, $this, $one, $two);
}
foreach ([$name, "_{$this->app->request->action()}{$name}"] as $method) {
if (method_exists($this, $method) && false === $this->$method($one, $two)) {
return false;
}
}
return true; return true;
} }
@ -146,10 +155,14 @@ class ApiController extends stdClass
*/ */
public function getAesDecryptData(string $name = '', $default = null) public function getAesDecryptData(string $name = '', $default = null)
{ {
if (empty($name)) return $this->aes_decrypt_data; if (empty($name)) {
return $this->aes_decrypt_data;
}
if (isset($this->aes_decrypt_data[$name])) { if (isset($this->aes_decrypt_data[$name])) {
return $this->aes_decrypt_data[$name]; return $this->aes_decrypt_data[$name];
} else return $default; } else {
return $default;
}
} }
/** /**
@ -158,7 +171,9 @@ class ApiController extends stdClass
*/ */
public function _judgeSign($name = 'sniff_h5') public function _judgeSign($name = 'sniff_h5')
{ {
if (empty($this->request->header('sign', ''))) $this->error('数据未签名!', 104); if (empty($this->request->header('sign', ''))) {
$this->error('数据未签名!', 104);
}
// 加密的数据参数 // 加密的数据参数
$aes = $this->request->post('aes'); $aes = $this->request->post('aes');
@ -166,18 +181,25 @@ class ApiController extends stdClass
$timestamp = $this->request->get('timestamp', 0); $timestamp = $this->request->get('timestamp', 0);
// 判断是否有时间 // 判断是否有时间
if (empty($timestamp)) $this->error('数据异常!', 105); if (empty($timestamp)) {
$this->error('数据异常!', 105);
}
// 解密 // 解密
$aes_decode = $this->decrypt($aes, $name, $timestamp); $aes_decode = $this->decrypt($aes, $name, $timestamp);
if (empty($aes_decode)) $this->error('解密失败', 106); if (empty($aes_decode)) {
$this->error('解密失败', 106);
}
$data = json_decode($aes_decode, true); $data = json_decode($aes_decode, true);
// 判断是不是小于服务器时间 // 判断是不是小于服务器时间
$before = strtotime('-2minute'); $before = strtotime('-2minute');
$rear = strtotime('+2minute'); $rear = strtotime('+2minute');
if ($timestamp <= $rear && $timestamp >= $before) $this->aes_decrypt_data = $data; if ($timestamp <= $rear && $timestamp >= $before) {
else $this->error('已超时,请重新尝试!'); $this->aes_decrypt_data = $data;
} else {
$this->error('已超时,请重新尝试!');
}
} }
/** /**

@ -52,7 +52,9 @@ class Controller extends stdClass
$this->app = $app; $this->app = $app;
$this->request = $app->request; $this->request = $app->request;
$this->app->bind('DtApp\ThinkLibrary\Controller', $this); $this->app->bind('DtApp\ThinkLibrary\Controller', $this);
if (in_array($this->request->action(), get_class_methods(__CLASS__))) $this->error('Access without permission.'); if (in_array($this->request->action(), get_class_methods(__CLASS__))) {
$this->error('Access without permission.');
}
$this->initialize(); $this->initialize();
} }
@ -139,7 +141,9 @@ class Controller extends stdClass
*/ */
public function callback($name, &$one = [], &$two = []) public function callback($name, &$one = [], &$two = [])
{ {
if (is_callable($name)) return call_user_func($name, $this, $one, $two); if (is_callable($name)) {
return call_user_func($name, $this, $one, $two);
}
foreach ([$name, "_{$this->app->request->action()}{$name}"] as $method) { foreach ([$name, "_{$this->app->request->action()}{$name}"] as $method) {
if (method_exists($this, $method) && false === $this->$method($one, $two)) { if (method_exists($this, $method) && false === $this->$method($one, $two)) {
return false; return false;

@ -73,7 +73,9 @@ class Mysql
'cache_value' => $cache_value, 'cache_value' => $cache_value,
'cache_expire' => Times::dateRear("Y-m-d H:i:s", $this->cache_expire) 'cache_expire' => Times::dateRear("Y-m-d H:i:s", $this->cache_expire)
]); ]);
if (empty($result)) return false; if (empty($result)) {
return false;
}
return true; return true;
} }
@ -108,7 +110,9 @@ class Mysql
$result = Db::table($this->table) $result = Db::table($this->table)
->where('cache_name', $this->cache_name) ->where('cache_name', $this->cache_name)
->delete(); ->delete();
if (empty($result)) return false; if (empty($result)) {
return false;
}
return true; return true;
} }
@ -128,7 +132,9 @@ class Mysql
'cache_value' => $cache_value, 'cache_value' => $cache_value,
'cache_expire' => Times::dateRear("Y-m-d H:i:s", $this->cache_expire) 'cache_expire' => Times::dateRear("Y-m-d H:i:s", $this->cache_expire)
]); ]);
if (empty($result)) return false; if (empty($result)) {
return false;
}
return true; return true;
} }
@ -149,7 +155,9 @@ class Mysql
->update([ ->update([
'cache_value' => $cache_value + $int 'cache_value' => $cache_value + $int
]); ]);
if (empty($result)) return false; if (empty($result)) {
return false;
}
return true; return true;
} }
@ -170,7 +178,9 @@ class Mysql
->update([ ->update([
'cache_value' => $cache_value - $int 'cache_value' => $cache_value - $int
]); ]);
if (empty($result)) return false; if (empty($result)) {
return false;
}
return true; return true;
} }
} }

@ -28,7 +28,7 @@ use think\db\exception\ModelNotFoundException;
/** /**
* 定义当前版本 * 定义当前版本
*/ */
const VERSION = '6.0.85'; const VERSION = '6.0.86';
if (!function_exists('get_ip_info')) { if (!function_exists('get_ip_info')) {
/** /**
@ -40,8 +40,9 @@ if (!function_exists('get_ip_info')) {
function get_ip_info($ip = '') function get_ip_info($ip = '')
{ {
if (empty($ip)) { if (empty($ip)) {
if (!isset($_SERVER['HTTP_X_FORWARDED_FOR'])) $ip = $_SERVER['REMOTE_ADDR']; if (!isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
else { $ip = $_SERVER['REMOTE_ADDR'];
} else {
//为了兼容百度的CDN所以转成数组 //为了兼容百度的CDN所以转成数组
$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
$ip = $arr[0]; $ip = $arr[0];
@ -62,7 +63,9 @@ if (!function_exists('get_ip')) {
//为了兼容百度的CDN所以转成数组 //为了兼容百度的CDN所以转成数组
$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
return $arr[0]; return $arr[0];
} else return $_SERVER['REMOTE_ADDR']; } else {
return $_SERVER['REMOTE_ADDR'];
}
} }
} }

@ -47,10 +47,14 @@ class ThinkException extends Handle
public function render($request, Throwable $e): Response public function render($request, Throwable $e): Response
{ {
// 参数验证错误 // 参数验证错误
if ($e instanceof ValidateException) return json($e->getError(), 422); if ($e instanceof ValidateException) {
return json($e->getError(), 422);
}
// 请求异常 // 请求异常
if ($e instanceof HttpException && $request->isAjax()) return response($e->getMessage(), $e->getStatusCode()); if ($e instanceof HttpException && $request->isAjax()) {
return response($e->getMessage(), $e->getStatusCode());
}
$this->show($e->getMessage()); $this->show($e->getMessage());
@ -69,34 +73,42 @@ class ThinkException extends Handle
$nt = config('dtapp.exception.type', ''); $nt = config('dtapp.exception.type', '');
if (!empty($nt) && $nt == 'dingtalk') { if (!empty($nt) && $nt == 'dingtalk') {
$access_token = config('dtapp.exception.dingtalk.access_token', ''); $access_token = config('dtapp.exception.dingtalk.access_token', '');
if (!empty($access_token)) return DingTalkService::instance() if (!empty($access_token)) {
->accessToken($access_token) return DingTalkService::instance()
->text($msg); ->accessToken($access_token)
->text($msg);
}
} }
if (!empty($nt) && $nt == 'qyweixin') { if (!empty($nt) && $nt == 'qyweixin') {
$key = config('dtapp.exception.qyweixin.key', ''); $key = config('dtapp.exception.qyweixin.key', '');
if (!empty($key)) return QyService::instance() if (!empty($key)) {
->key($key) return QyService::instance()
->text($msg); ->key($key)
->text($msg);
}
} }
if (!empty($nt) && $nt === 'wechat') { if (!empty($nt) && $nt === 'wechat') {
$openid = config('dtapp.exception.wechat.openid', ''); $openid = config('dtapp.exception.wechat.openid', '');
$ip = config('dtapp.exception.wechat.ip', '未配置'); $ip = config('dtapp.exception.wechat.ip', '未配置');
$seip = get_ip(); $seip = get_ip();
$ipinfo = QqWryService::instance()->getLocation($seip); $ipinfo = QqWryService::instance()->getLocation($seip);
if (!isset($ipinfo['location_all'])) $ipinfo['location_all'] = ''; if (!isset($ipinfo['location_all'])) {
if (!empty($openid)) return HttpService::instance() $ipinfo['location_all'] = '';
->url("https://api.dtapp.net/v1/wechatmp/tmplmsgWebError/openid/{$openid}") }
->post() if (!empty($openid)) {
->data([ return HttpService::instance()
'domain' => request()->domain(), ->url("https://api.dtapp.net/v1/wechatmp/tmplmsgWebError/openid/{$openid}")
'url' => request()->url(), ->post()
'node' => config('dtapp.exception.wechat.node', ''), ->data([
'info' => "ServerIp" . $ip . "CdnIp" . $_SERVER['REMOTE_ADDR'] . "ClientIp" . get_ip(), 'domain' => request()->domain(),
'ip' => $ipinfo['location_all'], 'url' => request()->url(),
'error' => base64_encode($msg) 'node' => config('dtapp.exception.wechat.node', ''),
]) 'info' => "ServerIp" . $ip . "CdnIp" . $_SERVER['REMOTE_ADDR'] . "ClientIp" . get_ip(),
->toArray(); 'ip' => $ipinfo['location_all'],
'error' => base64_encode($msg)
])
->toArray();
}
} }
return true; return true;
} }

@ -59,11 +59,16 @@ class Arrays
$arrRet = array(); $arrRet = array();
if (!isset($array) || empty($array)) return $arrRet; if (!isset($array) || empty($array)) return $arrRet;
$iCount = count($array) / $num; $iCount = count($array) / $num;
if (!is_int($iCount)) $iCount = ceil($iCount); if (!is_int($iCount)) {
else $iCount += 1; $iCount = ceil($iCount);
} else {
$iCount += 1;
}
for ($i = 0; $i < $iCount; ++$i) { for ($i = 0; $i < $iCount; ++$i) {
$arrInfos = array_slice($array, $i * $num, $num); $arrInfos = array_slice($array, $i * $num, $num);
if (empty($arrInfos)) continue; if (empty($arrInfos)) {
continue;
}
$arrRet[] = $arrInfos; $arrRet[] = $arrInfos;
unset($arrInfos); unset($arrInfos);
} }
@ -78,7 +83,11 @@ class Arrays
public function unique(array $array) public function unique(array $array)
{ {
$out = array(); $out = array();
foreach ($array as $key => $value) if (!in_array($value, $out)) $out[$key] = $value; foreach ($array as $key => $value) {
if (!in_array($value, $out)) {
$out[$key] = $value;
}
}
$out = array_values($out); $out = array_values($out);
return $out; return $out;
} }
@ -96,10 +105,15 @@ class Arrays
$key_arrays = array(); $key_arrays = array();
if (is_array($arrays)) { if (is_array($arrays)) {
foreach ($arrays as $array) { foreach ($arrays as $array) {
if (is_array($array)) $key_arrays[] = $array[$sort_key]; if (is_array($array)) {
else return []; $key_arrays[] = $array[$sort_key];
} else {
return [];
}
} }
} else return []; } else {
return [];
}
array_multisort($key_arrays, $sort_order, $sort_type, $arrays); array_multisort($key_arrays, $sort_order, $sort_type, $arrays);
return $arrays; return $arrays;
} }

@ -39,8 +39,14 @@ class Files
*/ */
public function delete(string $name): bool public function delete(string $name): bool
{ {
if (empty($name)) throw new Exception('请检查需要删除文件夹的名称'); if (empty($name)) {
if (file_exists($name)) if (unlink($name)) return true; throw new Exception('请检查需要删除文件夹的名称');
}
if (file_exists($name)) {
if (unlink($name)) {
return true;
}
}
return false; return false;
} }
@ -58,14 +64,20 @@ class Files
while ($file = readdir($dh)) { while ($file = readdir($dh)) {
if ($file != "." && $file != "..") { if ($file != "." && $file != "..") {
$fullpath = $name . "/" . $file; $fullpath = $name . "/" . $file;
if (!is_dir($fullpath)) unlink($fullpath); if (!is_dir($fullpath)) {
else $this->deletes($fullpath); unlink($fullpath);
} else {
$this->deletes($fullpath);
}
} }
} }
closedir($dh); closedir($dh);
//删除当前文件夹: //删除当前文件夹:
if (rmdir($name)) return true; if (rmdir($name)) {
else return false; return true;
} else {
return false;
}
} }
/** /**
@ -87,7 +99,9 @@ class Files
// 打开压缩包 // 打开压缩包
$zip->open($name, ZipArchive::CREATE); $zip->open($name, ZipArchive::CREATE);
//向压缩包中添加文件 //向压缩包中添加文件
foreach ($fileList as $file) $zip->addFile($file, basename($file)); foreach ($fileList as $file) {
$zip->addFile($file, basename($file));
}
//关闭压缩包 //关闭压缩包
$zip->close(); $zip->close();
return true; return true;
@ -155,7 +169,9 @@ class Files
*/ */
public function judgeFile(string $path): bool public function judgeFile(string $path): bool
{ {
if (file_exists($path)) return true; if (file_exists($path)) {
return true;
}
return false; return false;
} }
@ -166,7 +182,9 @@ class Files
*/ */
public function judgeContents(string $path): bool public function judgeContents(string $path): bool
{ {
if (is_dir($path)) return true; if (is_dir($path)) {
return true;
}
return false; return false;
} }
} }

@ -35,7 +35,9 @@ class Ints
*/ */
public function isEvenNumbers(int $num): bool public function isEvenNumbers(int $num): bool
{ {
if ($num % 2 == 0) return true; if ($num % 2 == 0) {
return true;
}
return false; return false;
} }
@ -46,7 +48,9 @@ class Ints
*/ */
public function isOddNumbers(int $num): bool public function isOddNumbers(int $num): bool
{ {
if ($num % 2 == 0) return false; if ($num % 2 == 0) {
return false;
}
return true; return true;
} }
} }

@ -36,7 +36,9 @@ class Pregs
*/ */
public function isIphone($mobile): bool public function isIphone($mobile): bool
{ {
if (preg_match('/^[1]([3-9])[0-9]{9}$/', $mobile)) return true; if (preg_match('/^[1]([3-9])[0-9]{9}$/', $mobile)) {
return true;
}
return false; return false;
} }
@ -48,7 +50,9 @@ class Pregs
*/ */
public function isIphoneAll($mobile): bool public function isIphoneAll($mobile): bool
{ {
if (preg_match('/^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/', $mobile)) return true; if (preg_match('/^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/', $mobile)) {
return true;
}
return false; return false;
} }
@ -60,7 +64,9 @@ class Pregs
*/ */
public function isTel($tel): bool public function isTel($tel): bool
{ {
if (preg_match("/^(\(\d{3,4}\)|\d{3,4}-)?\d{7,8}$/", $tel)) return true; if (preg_match("/^(\(\d{3,4}\)|\d{3,4}-)?\d{7,8}$/", $tel)) {
return true;
}
return false; return false;
} }
@ -72,7 +78,9 @@ class Pregs
*/ */
public function isIdCard($id): bool public function isIdCard($id): bool
{ {
if (preg_match("/^\d{15}|\d{18}$/", $id)) return true; if (preg_match("/^\d{15}|\d{18}$/", $id)) {
return true;
}
return false; return false;
} }
@ -84,7 +92,9 @@ class Pregs
*/ */
public function isDigit($digit): bool public function isDigit($digit): bool
{ {
if (preg_match("/^\d*$/", $digit)) return true; if (preg_match("/^\d*$/", $digit)) {
return true;
}
return false; return false;
} }
@ -96,7 +106,9 @@ class Pregs
*/ */
public function isNum($num): bool public function isNum($num): bool
{ {
if (is_numeric($num)) return true; if (is_numeric($num)) {
return true;
}
return false; return false;
} }
@ -108,7 +120,9 @@ class Pregs
*/ */
public function isStr($str): bool public function isStr($str): bool
{ {
if (preg_match("/^\w+$/", $str)) return true; if (preg_match("/^\w+$/", $str)) {
return true;
}
return false; return false;
} }
@ -120,7 +134,9 @@ class Pregs
*/ */
public function isPassword($str): bool public function isPassword($str): bool
{ {
if (preg_match("/^[a-zA-Z]\w{5,17}$/", $str)) return true; if (preg_match("/^[a-zA-Z]\w{5,17}$/", $str)) {
return true;
}
return false; return false;
} }
@ -132,7 +148,9 @@ class Pregs
*/ */
public function isChinese($str): bool public function isChinese($str): bool
{ {
if (preg_match("/^[\u4e00-\u9fa5],{0,}$/", $str)) return true; if (preg_match("/^[\u4e00-\u9fa5],{0,}$/", $str)) {
return true;
}
return false; return false;
} }
@ -144,7 +162,9 @@ class Pregs
*/ */
public function isEmail($email): bool public function isEmail($email): bool
{ {
if (preg_match("/^\w+[-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/", $email)) return true; if (preg_match("/^\w+[-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/", $email)) {
return true;
}
return false; return false;
} }
@ -156,7 +176,9 @@ class Pregs
*/ */
public function isLink($url): bool public function isLink($url): bool
{ {
if (preg_match("/http|https:\/\/[\w.]+[\w\/]*[\w.]*\??[\w=&\+\%]*/is", $url)) return true; if (preg_match("/http|https:\/\/[\w.]+[\w\/]*[\w.]*\??[\w=&\+\%]*/is", $url)) {
return true;
}
return false; return false;
} }
@ -168,7 +190,9 @@ class Pregs
*/ */
public function isQq($qq): bool public function isQq($qq): bool
{ {
if (preg_match("/^[1-9][0-9]{4,}$/", $qq)) return true; if (preg_match("/^[1-9][0-9]{4,}$/", $qq)) {
return true;
}
return false; return false;
} }
@ -180,7 +204,9 @@ class Pregs
*/ */
public function isIp($ip): bool public function isIp($ip): bool
{ {
if (preg_match("/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/", $ip)) return true; if (preg_match("/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/", $ip)) {
return true;
}
return false; return false;
} }
} }

@ -36,7 +36,11 @@ class Requests
*/ */
public function isEmpty(array $data, array $arr): array public function isEmpty(array $data, array $arr): array
{ {
foreach ($arr as $k => $v) if (empty(isset($data["$v"]) ? $data["$v"] : '')) return []; foreach ($arr as $k => $v) {
if (empty(isset($data["$v"]) ? $data["$v"] : '')) {
return [];
}
}
return $data; return $data;
} }
@ -48,7 +52,11 @@ class Requests
*/ */
public function isEmptyRet(array $data, array $arr): array public function isEmptyRet(array $data, array $arr): array
{ {
foreach ($arr as $k => $v) if (empty(isset($data["$v"]) ? $data["$v"] : '')) \DtApp\ThinkLibrary\facade\Returns::jsonError('请检查参数', 102); foreach ($arr as $k => $v) {
if (empty(isset($data["$v"]) ? $data["$v"] : '')) {
\DtApp\ThinkLibrary\facade\Returns::jsonError('请检查参数', 102);
}
}
return $data; return $data;
} }
@ -104,10 +112,14 @@ class Requests
public function isMobile(): bool public function isMobile(): bool
{ {
// 如果有HTTP_X_WAP_PROFILE则一定是移动设备 // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
if (isset($_SERVER['HTTP_X_WAP_PROFILE'])) return true; if (isset($_SERVER['HTTP_X_WAP_PROFILE'])) {
return true;
}
//如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息 //如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
//找不到为flase,否则为true //找不到为flase,否则为true
if (isset($_SERVER['HTTP_VIA'])) return stristr(request()->server('HTTP_VIA'), "wap") ? true : false; if (isset($_SERVER['HTTP_VIA'])) {
return stristr(request()->server('HTTP_VIA'), "wap") ? true : false;
}
//判断手机发送的客户端标志 //判断手机发送的客户端标志
if (isset($_SERVER['HTTP_USER_AGENT'])) { if (isset($_SERVER['HTTP_USER_AGENT'])) {
$clientkeywords = [ $clientkeywords = [
@ -117,13 +129,17 @@ class Requests
'openwave', 'nexusone', 'cldc', 'midp', 'wap', 'mobile', 'alipay' 'openwave', 'nexusone', 'cldc', 'midp', 'wap', 'mobile', 'alipay'
]; ];
// 从HTTP_USER_AGENT中查找手机浏览器的关键字 // 从HTTP_USER_AGENT中查找手机浏览器的关键字
if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower(request()->server('HTTP_USER_AGENT')))) return true; if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower(request()->server('HTTP_USER_AGENT')))) {
return true;
}
} }
//协议法,因为有可能不准确,放到最后判断 //协议法,因为有可能不准确,放到最后判断
if (isset($_SERVER['HTTP_ACCEPT'])) { if (isset($_SERVER['HTTP_ACCEPT'])) {
// 如果只支持wml并且不支持html那一定是移动设备 // 如果只支持wml并且不支持html那一定是移动设备
// 如果支持wml和html但是wml在html之前则是移动设备 // 如果支持wml和html但是wml在html之前则是移动设备
if ((strpos(request()->server('HTTP_ACCEPT'), 'vnd.wap.wml') !== false) && (strpos(request()->server('HTTP_ACCEPT'), 'text/html') === false || (strpos(request()->server('HTTP_ACCEPT'), 'vnd.wap.wml') < strpos(request()->server('HTTP_ACCEPT'), 'text/html')))) return true; if ((strpos(request()->server('HTTP_ACCEPT'), 'vnd.wap.wml') !== false) && (strpos(request()->server('HTTP_ACCEPT'), 'text/html') === false || (strpos(request()->server('HTTP_ACCEPT'), 'vnd.wap.wml') < strpos(request()->server('HTTP_ACCEPT'), 'text/html')))) {
return true;
}
} }
return false; return false;
} }
@ -134,7 +150,9 @@ class Requests
*/ */
public function isWeXin(): bool public function isWeXin(): bool
{ {
if (strpos(request()->server('HTTP_USER_AGENT'), 'MicroMessenger') !== false) return true; if (strpos(request()->server('HTTP_USER_AGENT'), 'MicroMessenger') !== false) {
return true;
}
return false; return false;
} }
@ -144,7 +162,9 @@ class Requests
*/ */
public function isWeXinMp(): bool public function isWeXinMp(): bool
{ {
if (strpos(request()->server('HTTP_USER_AGENT'), 'miniProgram') !== false) return true; if (strpos(request()->server('HTTP_USER_AGENT'), 'miniProgram') !== false) {
return true;
}
return false; return false;
} }
@ -154,7 +174,9 @@ class Requests
*/ */
public function isAliPay(): bool public function isAliPay(): bool
{ {
if (strpos(request()->server('HTTP_USER_AGENT'), 'Alipay') !== false) return true; if (strpos(request()->server('HTTP_USER_AGENT'), 'Alipay') !== false) {
return true;
}
return false; return false;
} }
@ -164,7 +186,11 @@ class Requests
*/ */
public function isQQ(): bool public function isQQ(): bool
{ {
if (strpos(request()->server('HTTP_USER_AGENT'), 'QQ') !== false) if (strpos(request()->server('HTTP_USER_AGENT'), '_SQ_') !== false) return true; if (strpos(request()->server('HTTP_USER_AGENT'), 'QQ') !== false) {
if (strpos(request()->server('HTTP_USER_AGENT'), '_SQ_') !== false) {
return true;
}
}
return false; return false;
} }
@ -175,8 +201,11 @@ class Requests
public function isQQBrowser(): bool public function isQQBrowser(): bool
{ {
if (strpos(request()->server('HTTP_USER_AGENT'), 'QQ') !== false) { if (strpos(request()->server('HTTP_USER_AGENT'), 'QQ') !== false) {
if (strpos(request()->server('HTTP_USER_AGENT'), '_SQ_') !== false) return false; if (strpos(request()->server('HTTP_USER_AGENT'), '_SQ_') !== false) {
else return true; return false;
} else {
return true;
}
} }
return false; return false;
} }

@ -41,8 +41,11 @@ class Returns
{ {
date_default_timezone_set('Asia/Shanghai'); date_default_timezone_set('Asia/Shanghai');
header('Content-Type:application/json; charset=utf-8'); header('Content-Type:application/json; charset=utf-8');
if (!empty($ext) && is_array($ext)) throw new HttpResponseException(json(array_merge(['code' => $code, 'msg' => $msg, 'time' => time(), 'data' => $data], $ext))); if (!empty($ext) && is_array($ext)) {
else throw new HttpResponseException(json(['code' => $code, 'msg' => $msg, 'time' => time(), 'data' => $data])); throw new HttpResponseException(json(array_merge(['code' => $code, 'msg' => $msg, 'time' => time(), 'data' => $data], $ext)));
} else {
throw new HttpResponseException(json(['code' => $code, 'msg' => $msg, 'time' => time(), 'data' => $data]));
}
} }
/** /**
@ -56,7 +59,10 @@ class Returns
{ {
date_default_timezone_set('Asia/Shanghai'); date_default_timezone_set('Asia/Shanghai');
header('Content-Type:application/json; charset=utf-8'); header('Content-Type:application/json; charset=utf-8');
if (!empty($ext) && is_array($ext)) throw new HttpResponseException(json(array_merge(['code' => $code, 'msg' => $msg, 'time' => time(), 'data' => $data], $ext))); if (!empty($ext) && is_array($ext)) {
else throw new HttpResponseException(json(['code' => $code, 'msg' => $msg, 'time' => time(), 'data' => $data])); throw new HttpResponseException(json(array_merge(['code' => $code, 'msg' => $msg, 'time' => time(), 'data' => $data], $ext)));
} else {
throw new HttpResponseException(json(['code' => $code, 'msg' => $msg, 'time' => time(), 'data' => $data]));
}
} }
} }

@ -37,7 +37,9 @@ class Strings
*/ */
public function extractBefore(string $str, int $start_num, int $end_num): string public function extractBefore(string $str, int $start_num, int $end_num): string
{ {
if (strlen($str) < $start_num + $end_num) return $str; if (strlen($str) < $start_num + $end_num) {
return $str;
}
return substr($str, $start_num, $end_num); return substr($str, $start_num, $end_num);
} }
@ -50,7 +52,9 @@ class Strings
*/ */
public function extractRear(string $str, int $num): string public function extractRear(string $str, int $num): string
{ {
if (strlen($str) <= $num) return $str; if (strlen($str) <= $num) {
return $str;
}
return substr($str, -$num); return substr($str, -$num);
} }
@ -141,10 +145,16 @@ class Strings
{ {
if (strpos($str, $del) !== false) { if (strpos($str, $del) !== false) {
$var = explode($del, $str); $var = explode($del, $str);
foreach ($var as $v) if ($v == $nee) return true; foreach ($var as $v) {
if ($v == $nee) {
return true;
}
}
return false; return false;
} else { } else {
if ($str == $nee) return true; if ($str == $nee) {
return true;
}
return false; return false;
} }
} }

@ -125,7 +125,9 @@ class Times
$assignTime1 = strtotime($start);//获得指定分钟时间戳00:00 $assignTime1 = strtotime($start);//获得指定分钟时间戳00:00
$assignTime2 = strtotime($end);//获得指定分钟时间戳01:00 $assignTime2 = strtotime($end);//获得指定分钟时间戳01:00
$result = false; $result = false;
if ($curTime > $assignTime1 && $curTime < $assignTime2) $result = true; if ($curTime > $assignTime1 && $curTime < $assignTime2) {
$result = true;
}
return $result; return $result;
} }
} }

@ -39,11 +39,19 @@ class UnIqIds
{ {
$numbs = '0123456789'; $numbs = '0123456789';
$chars = 'abcdefghijklmnopqrstuvwxyz'; $chars = 'abcdefghijklmnopqrstuvwxyz';
if (intval($type) === 1) $chars = $numbs; if (intval($type) === 1) {
if (intval($type) === 2) $chars = "{$chars}"; $chars = $numbs;
if (intval($type) === 3) $chars = "{$numbs}{$chars}"; }
if (intval($type) === 2) {
$chars = "{$chars}";
}
if (intval($type) === 3) {
$chars = "{$numbs}{$chars}";
}
$string = $prefix . $chars[rand(1, strlen($chars) - 1)]; $string = $prefix . $chars[rand(1, strlen($chars) - 1)];
if (isset($chars)) while (strlen($string) < $size) $string .= $chars[rand(0, strlen($chars) - 1)]; if (isset($chars)) {
while (strlen($string) < $size) $string .= $chars[rand(0, strlen($chars) - 1)];
}
return $string; return $string;
} }
@ -55,7 +63,9 @@ class UnIqIds
*/ */
public function date($size = 16, $prefix = ''): string public function date($size = 16, $prefix = ''): string
{ {
if ($size < 14) $size = 14; if ($size < 14) {
$size = 14;
}
$string = $prefix . date('Ymd') . (date('H') + date('i')) . date('s'); $string = $prefix . date('Ymd') . (date('H') + date('i')) . date('s');
while (strlen($string) < $size) $string .= rand(0, 9); while (strlen($string) < $size) $string .= rand(0, 9);
return $string; return $string;
@ -70,7 +80,9 @@ class UnIqIds
public function number($size = 12, $prefix = ''): string public function number($size = 12, $prefix = ''): string
{ {
$time = time() . ''; $time = time() . '';
if ($size < 10) $size = 10; if ($size < 10) {
$size = 10;
}
$string = $prefix . ($time[0] . $time[1]) . substr($time, 2) . rand(0, 9); $string = $prefix . ($time[0] . $time[1]) . substr($time, 2) . rand(0, 9);
while (strlen($string) < $size) $string .= rand(0, 9); while (strlen($string) < $size) $string .= rand(0, 9);
return $string; return $string;

@ -35,7 +35,9 @@ class Urls
*/ */
public function lenCode(string $url): string public function lenCode(string $url): string
{ {
if (empty($url)) return ''; if (empty($url)) {
return '';
}
return urlencode($url); return urlencode($url);
} }
@ -46,7 +48,9 @@ class Urls
*/ */
public function deCode(string $url): string public function deCode(string $url): string
{ {
if (empty($url)) return ''; if (empty($url)) {
return '';
}
return urldecode($url); return urldecode($url);
} }
@ -58,7 +62,11 @@ class Urls
public function toParams(array $data): string public function toParams(array $data): string
{ {
$buff = ""; $buff = "";
foreach ($data as $k => $v) if ($k != "sign" && $v !== "" && !is_array($v)) $buff .= $k . "=" . $v . "&"; foreach ($data as $k => $v) {
if ($k != "sign" && $v !== "" && !is_array($v)) {
$buff .= $k . "=" . $v . "&";
}
}
$buff = trim($buff, "&"); $buff = trim($buff, "&");
return $buff; return $buff;
} }

@ -38,12 +38,18 @@ class Xmls
*/ */
public function toXml(array $values) public function toXml(array $values)
{ {
if (!is_array($values) || count($values) <= 0) throw new Exception('数组数据异常!'); if (!is_array($values) || count($values) <= 0) {
throw new Exception('数组数据异常!');
}
$xml = "<xml>"; $xml = "<xml>";
foreach ($values as $key => $val) { foreach ($values as $key => $val) {
if (is_array($val)) $xml .= "<" . $key . ">" . $this->toXml($val) . "</" . $key . ">"; if (is_array($val)) {
else if (is_numeric($val)) $xml .= "<" . $key . ">" . $val . "</" . $key . ">"; $xml .= "<" . $key . ">" . $this->toXml($val) . "</" . $key . ">";
else $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">"; } else if (is_numeric($val)) {
$xml .= "<" . $key . ">" . $val . "</" . $key . ">";
} else {
$xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
}
} }
$xml .= "</xml>"; $xml .= "</xml>";
return $xml; return $xml;
@ -57,7 +63,9 @@ class Xmls
*/ */
public function toArray(string $xml) public function toArray(string $xml)
{ {
if (!$xml) throw new Exception('xml数据异常'); if (!$xml) {
throw new Exception('xml数据异常');
}
libxml_disable_entity_loader(true); libxml_disable_entity_loader(true);
return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true); return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
} }

@ -55,7 +55,9 @@ class BeAryChatService extends Service
->url($webhook) ->url($webhook)
->data($data) ->data($data)
->toArray(); ->toArray();
if ($result['code'] !== 0) return true; if ($result['code'] !== 0) {
return true;
}
return false; return false;
} }
} }

@ -76,14 +76,20 @@ class DingTalkService extends Service
*/ */
private function sendMsg(array $data) private function sendMsg(array $data)
{ {
if (empty($this->access_token)) throw new DtaException("请检查access_token"); if (empty($this->access_token)) {
if (empty($data['msgtype'])) $data['msgtype'] = $this->msg_type; throw new DtaException("请检查access_token");
}
if (empty($data['msgtype'])) {
$data['msgtype'] = $this->msg_type;
}
$result = HttpService::instance() $result = HttpService::instance()
->url("{$this->oapi_url}robot/send?access_token=" . $this->access_token) ->url("{$this->oapi_url}robot/send?access_token=" . $this->access_token)
->data($data) ->data($data)
->post() ->post()
->toArray(); ->toArray();
if ($result['errcode'] == 0) return $result['errmsg']; if ($result['errcode'] == 0) {
throw new HttpException(404, json_encode($result, JSON_UNESCAPED_UNICODE)); return $result['errmsg'];
}
throw new HttpException(404, json_encode($result, JSON_UNESCAPED_UNICODE));
} }
} }

@ -47,7 +47,9 @@ class IpIpService extends Service
public function __construct(App $app) public function __construct(App $app)
{ {
$this->ipPath = config('dtapp.ip_path', ''); $this->ipPath = config('dtapp.ip_path', '');
if (empty($this->ipPath)) throw new DtaException('请检查配置文件是否配置了IP数据库文件存放位置'); if (empty($this->ipPath)) {
throw new DtaException('请检查配置文件是否配置了IP数据库文件存放位置');
}
$this->reader = new IpIpReader($this->ipPath . 'ipipfree.ipdb'); $this->reader = new IpIpReader($this->ipPath . 'ipipfree.ipdb');
parent::__construct($app); parent::__construct($app);
} }
@ -59,7 +61,9 @@ class IpIpService extends Service
*/ */
public function getFind(string $ip = '', string $language = 'CN') public function getFind(string $ip = '', string $language = 'CN')
{ {
if (empty($ip)) $ip = get_ip(); if (empty($ip)) {
$ip = get_ip();
}
return $this->reader->find($ip, $language); return $this->reader->find($ip, $language);
} }
@ -70,7 +74,9 @@ class IpIpService extends Service
*/ */
public function getFindMap(string $ip = '', string $language = 'CN') public function getFindMap(string $ip = '', string $language = 'CN')
{ {
if (empty($ip)) $ip = get_ip(); if (empty($ip)) {
$ip = get_ip();
}
return $this->reader->findMap($ip, $language); return $this->reader->findMap($ip, $language);
} }
@ -81,9 +87,13 @@ class IpIpService extends Service
*/ */
public function getFindInfo(string $ip = '', string $language = 'CN') public function getFindInfo(string $ip = '', string $language = 'CN')
{ {
if (empty($ip)) $ip = get_ip(); if (empty($ip)) {
$ip = get_ip();
}
$map = $this->getFindMap($ip, $language); $map = $this->getFindMap($ip, $language);
if (NULL === $map) return NUll; if (NULL === $map) {
return NUll;
}
return new IpIpDistrictInfo($map); return new IpIpDistrictInfo($map);
} }
} }

@ -90,10 +90,16 @@ class MapService extends Service
*/ */
public function qq(string $output = 'JSON') public function qq(string $output = 'JSON')
{ {
if (empty($this->key)) throw new DtaException('开发密钥不能为空'); if (empty($this->key)) {
if (empty($this->ip)) $this->ip = get_ip(); throw new DtaException('开发密钥不能为空');
}
if (empty($this->ip)) {
$this->ip = get_ip();
}
$url = "https://apis.map.qq.com/ws/location/v1/ip?key={$this->key}&output={$output}"; $url = "https://apis.map.qq.com/ws/location/v1/ip?key={$this->key}&output={$output}";
if (!empty($this->ip)) $url = "https://apis.map.qq.com/ws/location/v1/ip?key={$this->key}&ip={$this->ip}&output={$output}"; if (!empty($this->ip)) {
$url = "https://apis.map.qq.com/ws/location/v1/ip?key={$this->key}&ip={$this->ip}&output={$output}";
}
return HttpService::instance() return HttpService::instance()
->url($url) ->url($url)
->toArray(); ->toArray();
@ -108,10 +114,16 @@ class MapService extends Service
*/ */
public function baidu(string $coor = 'bd09ll') public function baidu(string $coor = 'bd09ll')
{ {
if (empty($this->ak)) throw new DtaException('开发者密钥不能为空'); if (empty($this->ak)) {
if (empty($this->ip)) $this->ip = get_ip(); throw new DtaException('开发者密钥不能为空');
}
if (empty($this->ip)) {
$this->ip = get_ip();
}
$url = "https://api.map.baidu.com/location/ip?ak={$this->ak}&coor={$coor}"; $url = "https://api.map.baidu.com/location/ip?ak={$this->ak}&coor={$coor}";
if (!empty($this->ip)) $url = "https://api.map.baidu.com/location/ip?ak={$this->ak}&ip={$this->ip}&coor={$coor}"; if (!empty($this->ip)) {
$url = "https://api.map.baidu.com/location/ip?ak={$this->ak}&ip={$this->ip}&coor={$coor}";
}
return HttpService::instance() return HttpService::instance()
->url($url) ->url($url)
->toArray(); ->toArray();
@ -126,10 +138,16 @@ class MapService extends Service
*/ */
public function amap(string $output = 'JSON') public function amap(string $output = 'JSON')
{ {
if (empty($this->key)) throw new DtaException('开发密钥不能为空'); if (empty($this->key)) {
if (empty($this->ip)) $this->ip = get_ip(); throw new DtaException('开发密钥不能为空');
}
if (empty($this->ip)) {
$this->ip = get_ip();
}
$url = "https://restapi.amap.com/v3/ip?parameters&key={$this->key}&output={$output}"; $url = "https://restapi.amap.com/v3/ip?parameters&key={$this->key}&output={$output}";
if (!empty($this->ip)) $url = "https://restapi.amap.com/v3/ip?key={$this->key}&ip={$this->ip}&output={$output}"; if (!empty($this->ip)) {
$url = "https://restapi.amap.com/v3/ip?key={$this->key}&ip={$this->ip}&output={$output}";
}
return HttpService::instance() return HttpService::instance()
->url($url) ->url($url)
->toArray(); ->toArray();

@ -102,7 +102,9 @@ class OnlineService extends Service
*/ */
public function baidu() public function baidu()
{ {
if (empty($this->ip)) $this->ip = get_ip(); if (empty($this->ip)) {
$this->ip = get_ip();
}
$url = "https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query={$this->ip}&co=&resource_id=6006&ie=utf8&oe=utf8&cb=json"; $url = "https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query={$this->ip}&co=&resource_id=6006&ie=utf8&oe=utf8&cb=json";
$res = HttpService::instance() $res = HttpService::instance()
->url($url) ->url($url)
@ -121,7 +123,9 @@ class OnlineService extends Service
public function pConLine() public function pConLine()
{ {
$url = "http://whois.pconline.com.cn/ipJson.jsp?json=true"; $url = "http://whois.pconline.com.cn/ipJson.jsp?json=true";
if (!empty($this->ip)) $url = "http://whois.pconline.com.cn/ipJson.jsp?json=true&ip={$this->ip}"; if (!empty($this->ip)) {
$url = "http://whois.pconline.com.cn/ipJson.jsp?json=true&ip={$this->ip}";
}
$res = HttpService::instance() $res = HttpService::instance()
->url($url) ->url($url)
->toArray(false); ->toArray(false);
@ -137,7 +141,9 @@ class OnlineService extends Service
*/ */
public function siNa() public function siNa()
{ {
if (empty($this->ip)) $this->ip = get_ip(); if (empty($this->ip)) {
$this->ip = get_ip();
}
$url = "http://ip.ws.126.net/ipquery?ip={$this->ip}"; $url = "http://ip.ws.126.net/ipquery?ip={$this->ip}";
$res = HttpService::instance() $res = HttpService::instance()
->url($url) ->url($url)
@ -157,7 +163,9 @@ class OnlineService extends Service
*/ */
public function so() public function so()
{ {
if (empty($this->ip)) $this->ip = get_ip(); if (empty($this->ip)) {
$this->ip = get_ip();
}
$url = "https://open.onebox.so.com/dataApi?type=ip&src=onebox&tpl=0&num=1&query=ip&ip={$this->ip}&url=ip"; $url = "https://open.onebox.so.com/dataApi?type=ip&src=onebox&tpl=0&num=1&query=ip&ip={$this->ip}&url=ip";
return HttpService::instance() return HttpService::instance()
->url($url) ->url($url)
@ -186,7 +194,9 @@ class OnlineService extends Service
*/ */
public function taoBao(string $ip = '') public function taoBao(string $ip = '')
{ {
if (empty($this->ip)) $this->ip = get_ip(); if (empty($this->ip)) {
$this->ip = get_ip();
}
$url = "http://ip.taobao.com/service/getIpInfo.php?ip={$this->ip}"; $url = "http://ip.taobao.com/service/getIpInfo.php?ip={$this->ip}";
return HttpService::instance() return HttpService::instance()
->url($url) ->url($url)
@ -201,11 +211,15 @@ class OnlineService extends Service
*/ */
public function aliYun(string $appcode = '') public function aliYun(string $appcode = '')
{ {
if (empty($this->ip)) $this->ip = get_ip(); if (empty($this->ip)) {
$this->ip = get_ip();
}
$host = "http://iploc.market.alicloudapi.com"; $host = "http://iploc.market.alicloudapi.com";
$path = "/v3/ip"; $path = "/v3/ip";
$method = "GET"; $method = "GET";
if (empty($appcode)) throw new DtaException('请检查阿里-阿里云配置信息 appcode'); if (empty($appcode)) {
throw new DtaException('请检查阿里-阿里云配置信息 appcode');
}
$headers = array(); $headers = array();
array_push($headers, "Authorization:APPCODE " . $appcode); array_push($headers, "Authorization:APPCODE " . $appcode);
$querys = "ip={$this->ip}"; $querys = "ip={$this->ip}";

@ -148,7 +148,9 @@ class QqWryService extends Service
*/ */
public function getLocation(string $ip = '') public function getLocation(string $ip = '')
{ {
if (empty($ip)) $ip = get_ip(); if (empty($ip)) {
$ip = get_ip();
}
if (strpos($ip, 'http://') === 0) { if (strpos($ip, 'http://') === 0) {
$ip = substr($ip, 7); $ip = substr($ip, 7);
$ip = gethostbyname($ip); $ip = gethostbyname($ip);
@ -368,12 +370,16 @@ class QqWryService extends Service
*/ */
protected function getNormalizedIP($ip) protected function getNormalizedIP($ip)
{ {
if (!is_string($ip)) return ''; if (!is_string($ip)) {
return '';
}
if (preg_match('%^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$%', $ip, $match)) { if (preg_match('%^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$%', $ip, $match)) {
$IPParts = array(); $IPParts = array();
for ($i = 1; $i <= 4; $i++) { for ($i = 1; $i <= 4; $i++) {
$IPPart = (int)$match[$i]; $IPPart = (int)$match[$i];
if ($IPPart > 255) return ''; if ($IPPart > 255) {
return '';
}
$IPParts[$i] = str_pad(decHex($IPPart), 2, '0', STR_PAD_LEFT); $IPParts[$i] = str_pad(decHex($IPPart), 2, '0', STR_PAD_LEFT);
} }
return '0000:0000:0000:0000:0000:ffff:' . $IPParts[1] . $IPParts[2] . ':' . $IPParts[3] . $IPParts[4]; return '0000:0000:0000:0000:0000:ffff:' . $IPParts[1] . $IPParts[2] . ':' . $IPParts[3] . $IPParts[4];

@ -36,12 +36,20 @@ class RouteService extends Service
*/ */
public function redirect(string $url = '', int $status = 302, bool $parameter = false) public function redirect(string $url = '', int $status = 302, bool $parameter = false)
{ {
if (empty($url)) $url = request()->scheme() . "://" . request()->host(); if (empty($url)) {
$url = request()->scheme() . "://" . request()->host();
}
$param = http_build_query(request()->param()); $param = http_build_query(request()->param());
if ($status == 301) header('HTTP/1.1 301 Moved Permanently'); if ($status == 301) {
if (empty($parameter)) header("Location: {$url}"); header('HTTP/1.1 301 Moved Permanently');
elseif (empty($parameter) == false && empty($param) == true) header("Location: {$url}"); }
else header("Location: {$url}?{$param}"); if (empty($parameter)) {
header("Location: {$url}");
} elseif (empty($parameter) == false && empty($param) == true) {
header("Location: {$url}");
} else {
header("Location: {$url}?{$param}");
}
exit; exit;
} }
} }

@ -69,7 +69,9 @@ class StorageService extends Service
*/ */
public function save(string $name) public function save(string $name)
{ {
if (empty($this->path)) $this->getConfig(); if (empty($this->path)) {
$this->getConfig();
}
// 判断文件夹是否存在 // 判断文件夹是否存在
is_dir($this->path) or mkdir($this->path, 0777, true); is_dir($this->path) or mkdir($this->path, 0777, true);
$return_content = $this->http_get_data($this->remotely); $return_content = $this->http_get_data($this->remotely);
@ -110,8 +112,14 @@ class StorageService extends Service
*/ */
public function delete(string $name) public function delete(string $name)
{ {
if (empty($this->path)) $this->getConfig(); if (empty($this->path)) {
if (file_exists($name)) if (unlink($name)) return true; $this->getConfig();
}
if (file_exists($name)) {
if (unlink($name)) {
return true;
}
}
return false; return false;
} }
@ -124,10 +132,15 @@ class StorageService extends Service
{ {
if (empty($this->path)) $this->getConfig(); if (empty($this->path)) $this->getConfig();
$bytes = filesize($this->path . $name); $bytes = filesize($this->path . $name);
if ($bytes >= 1073741824) $bytes = round($bytes / 1073741824 * 100) / 100 . 'GB'; if ($bytes >= 1073741824) {
elseif ($bytes >= 1048576) $bytes = round($bytes / 1048576 * 100) / 100 . 'MB'; $bytes = round($bytes / 1073741824 * 100) / 100 . 'GB';
elseif ($bytes >= 1024) $bytes = round($bytes / 1024 * 100) / 100 . 'KB'; } elseif ($bytes >= 1048576) {
else $bytes = $bytes . 'Bytes'; $bytes = round($bytes / 1048576 * 100) / 100 . 'MB';
} elseif ($bytes >= 1024) {
$bytes = round($bytes / 1024 * 100) / 100 . 'KB';
} else {
$bytes = $bytes . 'Bytes';
}
return $bytes; return $bytes;
} }
@ -137,7 +150,9 @@ class StorageService extends Service
*/ */
public function getPath() public function getPath()
{ {
if (empty($this->path)) $this->getConfig(); if (empty($this->path)) {
$this->getConfig();
}
return $this->path; return $this->path;
} }
} }

@ -20,6 +20,7 @@
namespace DtApp\ThinkLibrary\service; namespace DtApp\ThinkLibrary\service;
use DtApp\ThinkLibrary\Service; use DtApp\ThinkLibrary\Service;
use Exception;
/** /**
* 系统服务 * 系统服务
@ -45,13 +46,23 @@ class SystemService extends Service
$url_html_suffix = $this->app->config->get('route.url_html_suffix', 'html'); $url_html_suffix = $this->app->config->get('route.url_html_suffix', 'html');
$pathinfo_depr = $this->app->config->get('route.pathinfo_depr', '/'); $pathinfo_depr = $this->app->config->get('route.pathinfo_depr', '/');
$url_common_param = $this->app->config->get('route.url_common_param', true); $url_common_param = $this->app->config->get('route.url_common_param', true);
if (empty($url)) $url = "{$default_app}/{$default_action}/{$default_controller}"; if (empty($url)) {
$url = "{$default_app}/{$default_action}/{$default_controller}";
}
if (empty($suffix) && !empty($fillSuffix)) { if (empty($suffix) && !empty($fillSuffix)) {
if (empty($url_common_param)) $location = $this->app->route->buildUrl($url, $vars)->suffix($suffix)->domain($domain)->build(); if (empty($url_common_param)) {
else $location = $this->app->route->buildUrl($url, [])->suffix($suffix)->domain($domain)->build(); $location = $this->app->route->buildUrl($url, $vars)->suffix($suffix)->domain($domain)->build();
if (empty($vars)) $location = substr($location . "{$pathinfo_depr}" . $this->arr_to_str($vars, $pathinfo_depr), 0, -1) . ".{$url_html_suffix}"; } else {
else $location = $location . "{$pathinfo_depr}" . $this->arr_to_str($vars, $pathinfo_depr) . ".{$url_html_suffix}"; $location = $this->app->route->buildUrl($url, [])->suffix($suffix)->domain($domain)->build();
} else $location = $this->app->route->buildUrl($url, $vars)->suffix($suffix)->domain($domain)->build(); }
if (empty($vars)) {
$location = substr($location . "{$pathinfo_depr}" . $this->arr_to_str($vars, $pathinfo_depr), 0, -1) . ".{$url_html_suffix}";
} else {
$location = $location . "{$pathinfo_depr}" . $this->arr_to_str($vars, $pathinfo_depr) . ".{$url_html_suffix}";
}
} else {
$location = $this->app->route->buildUrl($url, $vars)->suffix($suffix)->domain($domain)->build();
}
return $location; return $location;
} }
@ -64,7 +75,9 @@ class SystemService extends Service
private function arr_to_str($arr, $glue = "/") private function arr_to_str($arr, $glue = "/")
{ {
$t = ''; $t = '';
foreach ($arr as $k => $v) $t .= $k . $glue . $v . $glue; foreach ($arr as $k => $v) {
$t .= $k . $glue . $v . $glue;
}
$t = substr($t, 0, -1); // 利用字符串截取函数消除最后一个 $t = substr($t, 0, -1); // 利用字符串截取函数消除最后一个
return $t; return $t;
} }
@ -149,7 +162,7 @@ class SystemService extends Service
try { try {
$ip_cmd = "ifconfig eth0 | sed -n '/inet addr/p' | awk '{print $2}' | awk -F ':' '{print $2}'"; $ip_cmd = "ifconfig eth0 | sed -n '/inet addr/p' | awk '{print $2}' | awk -F ':' '{print $2}'";
return trim(exec($ip_cmd)); return trim(exec($ip_cmd));
} catch (\Exception $e) { } catch (Exception $e) {
return "0.0.0.0"; return "0.0.0.0";
} }
} }

@ -56,7 +56,9 @@ class WorkKileService extends Service
->url($webhook) ->url($webhook)
->data($data) ->data($data)
->toArray(); ->toArray();
if ($result['code'] == 200) return true; if ($result['code'] == 200) {
return true;
}
return false; return false;
} }
} }

@ -78,10 +78,9 @@ class OssService extends Service
*/ */
public function upload(string $object, string $filePath) public function upload(string $object, string $filePath)
{ {
if (empty($this->accessKeySecret)) $this->getConfig(); if (empty($this->accessKeySecret) || empty($this->accessKeySecret) || empty($this->endpoint) || empty($this->bucket)) {
if (empty($this->accessKeySecret)) $this->getConfig(); $this->getConfig();
if (empty($this->endpoint)) $this->getConfig(); }
if (empty($this->bucket)) $this->getConfig();
try { try {
$ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint); $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
$ossClient->uploadFile($this->bucket, $object, $filePath); $ossClient->uploadFile($this->bucket, $object, $filePath);

@ -63,8 +63,12 @@ class AmApService extends Service
*/ */
public function weather($city = "110101", $extensions = "base") public function weather($city = "110101", $extensions = "base")
{ {
if (empty($this->key)) $this->getConfig(); if (empty($this->key)) {
if (empty($this->key)) throw new DtaException('请检查key参数'); $this->getConfig();
}
if (empty($this->key)) {
throw new DtaException('请检查key参数');
}
$data = http_build_query([ $data = http_build_query([
"city" => $city, "city" => $city,
"extensions" => $extensions, "extensions" => $extensions,

@ -79,9 +79,9 @@ class BosService extends Service
*/ */
public function upload(string $object, string $filePath) public function upload(string $object, string $filePath)
{ {
if (empty($this->accessKeyId)) $this->getConfig(); if (empty($this->accessKeyId) || empty($this->secretAccessKey) || empty($this->endpoint)) {
if (empty($this->secretAccessKey)) $this->getConfig(); $this->getConfig();
if (empty($this->endpoint)) $this->getConfig(); }
// 设置BosClient的Access Key ID、Secret Access Key和ENDPOINT // 设置BosClient的Access Key ID、Secret Access Key和ENDPOINT
$BOS_TEST_CONFIG = array( $BOS_TEST_CONFIG = array(
'credentials' => array( 'credentials' => array(
@ -92,7 +92,9 @@ class BosService extends Service
); );
$client = new BosClient($BOS_TEST_CONFIG); $client = new BosClient($BOS_TEST_CONFIG);
// 从文件中直接上传Object // 从文件中直接上传Object
if (empty($this->bucket)) $this->getConfig(); if (empty($this->bucket)) {
$this->getConfig();
}
$client->putObjectFromFile($this->bucket, $object, $filePath); $client->putObjectFromFile($this->bucket, $object, $filePath);
return $this->app->config->get('dtapp.baidu.bos.url', '') . $object; return $this->app->config->get('dtapp.baidu.bos.url', '') . $object;
} }

@ -64,8 +64,12 @@ class LbsYunService extends Service
*/ */
public function weather($district_id = 110100, string $coordtype = "bd09ll", string $location = "") public function weather($district_id = 110100, string $coordtype = "bd09ll", string $location = "")
{ {
if (empty($this->ak)) $this->getConfig(); if (empty($this->ak)) {
if (empty($this->ak)) throw new DtaException('请检查ak参数'); $this->getConfig();
}
if (empty($this->ak)) {
throw new DtaException('请检查ak参数');
}
$data = http_build_query([ $data = http_build_query([
"district_id" => $district_id, "district_id" => $district_id,
"coordtype" => $coordtype, "coordtype" => $coordtype,
@ -91,8 +95,12 @@ class LbsYunService extends Service
*/ */
public function weatherAbroad($district_id = 110100, string $coordtype = "bd09ll", string $location = "", string $language = "cn") public function weatherAbroad($district_id = 110100, string $coordtype = "bd09ll", string $location = "", string $language = "cn")
{ {
if (empty($this->ak)) $this->getConfig(); if (empty($this->ak)) {
if (empty($this->ak)) throw new DtaException('请检查ak参数'); $this->getConfig();
}
if (empty($this->ak)) {
throw new DtaException('请检查ak参数');
}
$data = http_build_query([ $data = http_build_query([
"district_id" => $district_id, "district_id" => $district_id,
"coordtype" => $coordtype, "coordtype" => $coordtype,

@ -71,8 +71,12 @@ class ApiService extends Service
*/ */
public function getCpuIoInfo($type = 'GetCpuIo', $start_time = 0, $end_time = 0) public function getCpuIoInfo($type = 'GetCpuIo', $start_time = 0, $end_time = 0)
{ {
if (empty($start_time)) $start_time = strtotime(date('Y-m-d')); if (empty($start_time)) {
if (empty($end_time)) $end_time = time(); $start_time = strtotime(date('Y-m-d'));
}
if (empty($end_time)) {
$end_time = time();
}
$this->url = "/ajax?action={$type}&start={$start_time}&end={$end_time}"; $this->url = "/ajax?action={$type}&start={$start_time}&end={$end_time}";
return $this; return $this;
} }
@ -309,10 +313,16 @@ class ApiService extends Service
*/ */
private function getDataWithCount() private function getDataWithCount()
{ {
if (empty($this->contents['data'])) $this->contents['data'] = []; if (empty($this->contents['data'])) {
if (!is_array($this->contents['data'])) $this->contents['data'] = []; $this->contents['data'] = [];
}
if (!is_array($this->contents['data'])) {
$this->contents['data'] = [];
}
$this->backtrack['data'] = $this->contents; $this->backtrack['data'] = $this->contents;
if (empty($this->contents['page'])) $this->contents['page'] = 0; if (empty($this->contents['page'])) {
$this->contents['page'] = 0;
}
$this->backtrack['count'] = $this->getCountData($this->contents['page']); $this->backtrack['count'] = $this->getCountData($this->contents['page']);
return $this; return $this;
} }
@ -347,10 +357,17 @@ class ApiService extends Service
public function toArray() public function toArray()
{ {
$this->getHttp(); $this->getHttp();
if ($this->where['type'] == 'sites') $this->getDataWithOrderOpt(); if ($this->where['type'] == 'sites') {
else $this->getDataWithCount(); $this->getDataWithOrderOpt();
if (empty($this->backtrack)) return []; } else {
if (is_array($this->backtrack)) return $this->backtrack; $this->getDataWithCount();
}
if (empty($this->backtrack)) {
return [];
}
if (is_array($this->backtrack)) {
return $this->backtrack;
}
return json_decode($this->backtrack, true); return json_decode($this->backtrack, true);
} }
@ -362,7 +379,9 @@ class ApiService extends Service
private function mimes($name): string private function mimes($name): string
{ {
$mimes = include __DIR__ . '/bin/mimes.php'; $mimes = include __DIR__ . '/bin/mimes.php';
if (isset($mimes[$name])) return '/' . $mimes[$name]; if (isset($mimes[$name])) {
return '/' . $mimes[$name];
}
return ''; return '';
} }
@ -376,18 +395,28 @@ class ApiService extends Service
*/ */
protected function HttpPostCookie(string $url, array $data = [], bool $is_json = true) protected function HttpPostCookie(string $url, array $data = [], bool $is_json = true)
{ {
if (empty($this->panel)) $this->getConfig(); if (empty($this->panel)) {
if (empty($this->panel)) throw new DtaException('请检查panel参数'); $this->getConfig();
}
if (empty($this->panel)) {
throw new DtaException('请检查panel参数');
}
//定义cookie保存位置 //定义cookie保存位置
$file = app()->getRootPath() . 'runtime/dtapp/bt/cookie/'; $file = app()->getRootPath() . 'runtime/dtapp/bt/cookie/';
$cookie_file = $file . md5($this->panel) . '.cookie'; $cookie_file = $file . md5($this->panel) . '.cookie';
if (empty(Files::judgeContents($file))) mkdir($file, 0777, true); if (empty(Files::judgeContents($file))) {
mkdir($file, 0777, true);
}
if (!file_exists($cookie_file)) { if (!file_exists($cookie_file)) {
$fp = fopen($cookie_file, 'w+'); $fp = fopen($cookie_file, 'w+');
fclose($fp); fclose($fp);
} }
if (empty($this->key)) $this->getConfig(); if (empty($this->key)) {
if (empty($this->key)) throw new DtaException('请检查key参数'); $this->getConfig();
}
if (empty($this->key)) {
throw new DtaException('请检查key参数');
}
return BtService::instance() return BtService::instance()
->panel($this->panel) ->panel($this->panel)
->key($this->key) ->key($this->key)
@ -407,7 +436,9 @@ class ApiService extends Service
$start = strpos($str, "共"); $start = strpos($str, "共");
$end = strpos($str, "条数据"); $end = strpos($str, "条数据");
$count = substr($str, $start + 3, $end - $start - 3); $count = substr($str, $start + 3, $end - $start - 3);
if (empty($count)) return 0; if (empty($count)) {
return 0;
}
return $count; return $count;
} }
} }

@ -107,11 +107,19 @@ class BtService extends Service
*/ */
public function toArray(bool $is = true) public function toArray(bool $is = true)
{ {
if (empty($this->cookie)) throw new HttpException(404, '请检查cookie内容'); if (empty($this->cookie)) {
if (!extension_loaded("curl")) throw new HttpException(404, '请开启curl模块'); throw new HttpException(404, '请检查cookie内容');
}
if (!extension_loaded("curl")) {
throw new HttpException(404, '请开启curl模块');
}
$this->http(); $this->http();
if (empty($is)) return $this->output; if (empty($is)) {
if (is_array($this->output)) return $this->output; return $this->output;
}
if (is_array($this->output)) {
return $this->output;
}
return json_decode($this->output, true); return json_decode($this->output, true);
} }

@ -52,8 +52,11 @@ class HttpService extends Service
*/ */
public function data($str) public function data($str)
{ {
if (is_array($str)) $this->data = json_encode($str, JSON_UNESCAPED_UNICODE); if (is_array($str)) {
else $this->data = $str; $this->data = json_encode($str, JSON_UNESCAPED_UNICODE);
} else {
$this->data = $str;
}
return $this; return $this;
} }
@ -142,7 +145,9 @@ class HttpService extends Service
public function toArray(bool $is = true) public function toArray(bool $is = true)
{ {
//首先检测是否支持curl //首先检测是否支持curl
if (!extension_loaded("curl")) throw new HttpException(404, '请开启curl模块'); if (!extension_loaded("curl")) {
throw new HttpException(404, '请开启curl模块');
}
if ($this->method === 'GET') { if ($this->method === 'GET') {
$this->httpGet(); $this->httpGet();
} else if ($this->method === 'POST') { } else if ($this->method === 'POST') {
@ -151,9 +156,15 @@ class HttpService extends Service
$this->httpXml(); $this->httpXml();
} else if ($this->method === 'FILE') { } else if ($this->method === 'FILE') {
$this->httpFile(); $this->httpFile();
} else throw new HttpException(404, '请求方式异常'); } else {
if (empty($is)) return $this->output; throw new HttpException(404, '请求方式异常');
if (is_array($this->output)) return $this->output; }
if (empty($is)) {
return $this->output;
}
if (is_array($this->output)) {
return $this->output;
}
return json_decode($this->output, true); return json_decode($this->output, true);
} }

@ -52,12 +52,16 @@ class WatermarkService extends Service
{ {
if (Pregs::isLink($str)) { if (Pregs::isLink($str)) {
$url = $this->judgeUrl($str); $url = $this->judgeUrl($str);
if (empty($url)) throw new DtaException('配置网址内容不正确'); if (empty($url)) {
throw new DtaException('配置网址内容不正确');
}
$this->url = $url; $this->url = $url;
} else { } else {
preg_match_all('#\bhttps?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#', $str, $match); preg_match_all('#\bhttps?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#', $str, $match);
$url = $this->judgeUrl($match[0][0]); $url = $this->judgeUrl($match[0][0]);
if (empty($url)) throw new DtaException('配置网址内容不正确'); if (empty($url)) {
throw new DtaException('配置网址内容不正确');
}
$this->url = $url; $this->url = $url;
} }
$content = $this->getContents($this->url); $content = $this->getContents($this->url);
@ -569,9 +573,13 @@ class WatermarkService extends Service
*/ */
private function judgeUrl($url) private function judgeUrl($url)
{ {
if (strpos($url, 'douyin.com') !== false) return $url; if (strpos($url, 'douyin.com') !== false) {
else if (strpos($url, 'iesdouyin.com') !== false) return $url; return $url;
else return ''; } else if (strpos($url, 'iesdouyin.com') !== false) {
return $url;
} else {
return '';
}
} }
/** /**
@ -583,9 +591,13 @@ class WatermarkService extends Service
private function getItemId($content) private function getItemId($content)
{ {
preg_match('/"(?<=itemId:\s\")\d+"/', $content, $matches); preg_match('/"(?<=itemId:\s\")\d+"/', $content, $matches);
if (!isset($matches[0])) throw new DtaException('视频不存在'); if (!isset($matches[0])) {
throw new DtaException('视频不存在');
}
preg_match("~\"(.*?)\"~", $matches[0], $matches2); preg_match("~\"(.*?)\"~", $matches[0], $matches2);
if (!isset($matches2[1])) throw new DtaException('视频不存在'); if (!isset($matches2[1])) {
throw new DtaException('视频不存在');
}
return $matches2[1]; return $matches2[1];
} }
@ -598,10 +610,14 @@ class WatermarkService extends Service
private function getDyTk($content) private function getDyTk($content)
{ {
preg_match("~dytk(.*?)}~", $content, $matches); preg_match("~dytk(.*?)}~", $content, $matches);
if (!isset($matches[1])) throw new DtaException('视频不存在'); if (!isset($matches[1])) {
throw new DtaException('视频不存在');
}
$Dytk = $matches[1]; $Dytk = $matches[1];
preg_match("~\"(.*?)\"~", $Dytk, $matches2); preg_match("~\"(.*?)\"~", $Dytk, $matches2);
if (!isset($matches2[1])) throw new DtaException('视频不存在'); if (!isset($matches2[1])) {
throw new DtaException('视频不存在');
}
return $matches2[1]; return $matches2[1];
} }
@ -611,8 +627,12 @@ class WatermarkService extends Service
*/ */
public function toArray() public function toArray()
{ {
if (empty($this->backtrack)) return []; if (empty($this->backtrack)) {
if (is_array($this->backtrack)) return $this->backtrack; return [];
}
if (is_array($this->backtrack)) {
return $this->backtrack;
}
return json_decode($this->backtrack, true); return json_decode($this->backtrack, true);
} }
@ -622,10 +642,16 @@ class WatermarkService extends Service
*/ */
public function toObject() public function toObject()
{ {
if (empty($this->backtrack)) return ''; if (empty($this->backtrack)) {
if (is_object($this->backtrack)) return $this->backtrack; return '';
}
if (is_object($this->backtrack)) {
return $this->backtrack;
}
$obj = new StdClass(); $obj = new StdClass();
foreach ($this->backtrack as $key => $val) $obj->$key = $val; foreach ($this->backtrack as $key => $val) {
$obj->$key = $val;
}
return $obj; return $obj;
} }
@ -637,11 +663,17 @@ class WatermarkService extends Service
private function cAuthorAvatar($data) private function cAuthorAvatar($data)
{ {
// 1080x1080 // 1080x1080
if (isset($data['avatar_larger']['url_list'][0])) return $data['avatar_larger']['url_list'][0]; if (isset($data['avatar_larger']['url_list'][0])) {
return $data['avatar_larger']['url_list'][0];
}
// 720x720 // 720x720
if (isset($data['avatar_medium']['url_list'][0])) return $data['avatar_medium']['url_list'][0]; if (isset($data['avatar_medium']['url_list'][0])) {
return $data['avatar_medium']['url_list'][0];
}
// 100x100 // 100x100
if (isset($data['avatar_thumb']['url_list'][0])) return $data['avatar_thumb']['url_list'][0]; if (isset($data['avatar_thumb']['url_list'][0])) {
return $data['avatar_thumb']['url_list'][0];
}
return ''; return '';
} }
@ -653,11 +685,17 @@ class WatermarkService extends Service
private function cMusicAvatar($data) private function cMusicAvatar($data)
{ {
// 1080x1080 // 1080x1080
if (isset($data['cover_hd']['url_list'][0])) return $data['cover_hd']['url_list'][0]; if (isset($data['cover_hd']['url_list'][0])) {
return $data['cover_hd']['url_list'][0];
}
// 720x720 // 720x720
if (isset($data['cover_medium']['url_list'][0])) return $data['cover_medium']['url_list'][0]; if (isset($data['cover_medium']['url_list'][0])) {
return $data['cover_medium']['url_list'][0];
}
// 100x100 // 100x100
if (isset($data['cover_thumb']['url_list'][0])) return $data['cover_thumb']['url_list'][0]; if (isset($data['cover_thumb']['url_list'][0])) {
return $data['cover_thumb']['url_list'][0];
}
return ''; return '';
} }
@ -673,11 +711,17 @@ class WatermarkService extends Service
$array['origin_cover'] = ''; $array['origin_cover'] = '';
$array['cover'] = ''; $array['cover'] = '';
// 动态 // 动态
if (isset($data['dynamic_cover']['url_list'][0])) $array['dynamic'] = substr($data['dynamic_cover']['url_list'][0], 0, strpos($data['dynamic_cover']['url_list'][0], '?from=')); if (isset($data['dynamic_cover']['url_list'][0])) {
$array['dynamic'] = substr($data['dynamic_cover']['url_list'][0], 0, strpos($data['dynamic_cover']['url_list'][0], '?from='));
}
// width封面 // width封面
if (isset($data['origin_cover']['url_list'][0])) $array['origin_cover'] = substr($data['origin_cover']['url_list'][0], 0, strpos($data['origin_cover']['url_list'][0], '?from=')); if (isset($data['origin_cover']['url_list'][0])) {
$array['origin_cover'] = substr($data['origin_cover']['url_list'][0], 0, strpos($data['origin_cover']['url_list'][0], '?from='));
}
// height封面 // height封面
if (isset($data['cover']['url_list'][0])) $array['cover'] = substr($data['cover']['url_list'][0], 0, strpos($data['cover']['url_list'][0], '?from=')); if (isset($data['cover']['url_list'][0])) {
$array['cover'] = substr($data['cover']['url_list'][0], 0, strpos($data['cover']['url_list'][0], '?from='));
}
return $array; return $array;
} }
@ -689,8 +733,11 @@ class WatermarkService extends Service
*/ */
private function cVideoPlayUrl($url, $type) private function cVideoPlayUrl($url, $type)
{ {
if ($type == 'play') $headers = get_headers(str_replace("/playwm/", "/play/", $url), TRUE); if ($type == 'play') {
else $headers = get_headers($url, TRUE); $headers = get_headers(str_replace("/playwm/", "/play/", $url), TRUE);
} else {
$headers = get_headers($url, TRUE);
}
//输出跳转到的网址 //输出跳转到的网址
return $headers['location']; return $headers['location'];
} }

@ -77,16 +77,18 @@ class ObsService extends Service
*/ */
public function upload(string $object, string $filePath) public function upload(string $object, string $filePath)
{ {
if (empty($this->key)) $this->getConfig(); if (empty($this->key) || empty($this->secret) || empty($this->endpoint)) {
if (empty($this->secret)) $this->getConfig(); $this->getConfig();
if (empty($this->endpoint)) $this->getConfig(); }
// 创建ObsClient实例 // 创建ObsClient实例
$obsClient = new ObsClient([ $obsClient = new ObsClient([
'key' => $this->key, 'key' => $this->key,
'secret' => $this->secret, 'secret' => $this->secret,
'endpoint' => $this->endpoint 'endpoint' => $this->endpoint
]); ]);
if (empty($this->bucket)) $this->getConfig(); if (empty($this->bucket)) {
$this->getConfig();
}
$resp = $obsClient->putObject([ $resp = $obsClient->putObject([
'Bucket' => $this->bucket, 'Bucket' => $this->bucket,
'Key' => $object, 'Key' => $object,

@ -269,8 +269,12 @@ class UnionService extends Service
*/ */
public function goodsJIngFenQuery() public function goodsJIngFenQuery()
{ {
if (!isset($this->param['pageIndex'])) $this->param['pageIndex'] = 1; if (!isset($this->param['pageIndex'])) {
if (!isset($this->param['pageSize'])) $this->param['pageSize'] = 20; $this->param['pageIndex'] = 1;
}
if (!isset($this->param['pageSize'])) {
$this->param['pageSize'] = 20;
}
$this->method = 'jd.union.open.goods.jingfen.query'; $this->method = 'jd.union.open.goods.jingfen.query';
return $this; return $this;
} }
@ -327,10 +331,18 @@ class UnionService extends Service
public function toArray() public function toArray()
{ {
//首先检测是否支持curl //首先检测是否支持curl
if (!extension_loaded("curl")) throw new HttpException(404, '请开启curl模块'); if (!extension_loaded("curl")) {
if (empty($this->app_key)) $this->getConfig(); throw new HttpException(404, '请开启curl模块');
if (empty($this->app_key)) throw new DtaException('请检查app_key参数'); }
if (empty($this->method)) throw new DtaException('请检查method参数'); if (empty($this->app_key)) {
$this->getConfig();
}
if (empty($this->app_key)) {
throw new DtaException('请检查app_key参数');
}
if (empty($this->method)) {
throw new DtaException('请检查method参数');
}
$this->params['method'] = $this->method; $this->params['method'] = $this->method;
$this->params['app_key'] = $this->app_key; $this->params['app_key'] = $this->app_key;
$this->params['timestamp'] = date('Y-m-d H:i:s'); $this->params['timestamp'] = date('Y-m-d H:i:s');
@ -341,12 +353,20 @@ class UnionService extends Service
$this->http(); $this->http();
$response = Strings::replace('.', '_', $this->method) . "_response"; $response = Strings::replace('.', '_', $this->method) . "_response";
if (isset($this->output["$response"]['result'])) { if (isset($this->output["$response"]['result'])) {
if (is_array($this->output["$response"]['result'])) return $this->output["$response"]['result']; if (is_array($this->output["$response"]['result'])) {
if (is_object($this->output["$response"]['result'])) $this->output = json_encode($this->output["$response"]['result'], JSON_UNESCAPED_UNICODE); return $this->output["$response"]['result'];
}
if (is_object($this->output["$response"]['result'])) {
$this->output = json_encode($this->output["$response"]['result'], JSON_UNESCAPED_UNICODE);
}
return json_decode($this->output["$response"]['result'], true); return json_decode($this->output["$response"]['result'], true);
} else { } else {
if (is_array($this->output)) return $this->output; if (is_array($this->output)) {
if (is_object($this->output)) $this->output = json_encode($this->output, JSON_UNESCAPED_UNICODE); return $this->output;
}
if (is_object($this->output)) {
$this->output = json_encode($this->output, JSON_UNESCAPED_UNICODE);
}
return json_decode($this->output, true); return json_decode($this->output, true);
} }
} }
@ -358,12 +378,19 @@ class UnionService extends Service
*/ */
private function createSign() private function createSign()
{ {
if (empty($this->secret_key)) $this->getConfig(); if (empty($this->secret_key)) {
if (empty($this->secret_key)) throw new DtaException('请检查secret_key参数'); $this->getConfig();
}
if (empty($this->secret_key)) {
throw new DtaException('请检查secret_key参数');
}
$sign = $this->secret_key; $sign = $this->secret_key;
ksort($this->params); ksort($this->params);
foreach ($this->params as $key => $val) if ($key != '' && $val != '') $sign .= $key . $val; foreach ($this->params as $key => $val) {
if ($key != '' && $val != '') {
$sign .= $key . $val;
}
}
$sign .= $this->secret_key; $sign .= $this->secret_key;
$sign = strtoupper(md5($sign)); $sign = strtoupper(md5($sign));
return $sign; return $sign;
@ -376,7 +403,11 @@ class UnionService extends Service
private function createStrParam() private function createStrParam()
{ {
$strParam = ''; $strParam = '';
foreach ($this->params as $key => $val) if ($key != '' && $val != '') $strParam .= $key . '=' . urlencode($val) . '&'; foreach ($this->params as $key => $val) {
if ($key != '' && $val != '') {
$strParam .= $key . '=' . urlencode($val) . '&';
}
}
return $strParam; return $strParam;
} }

@ -20,6 +20,8 @@
namespace DtApp\ThinkLibrary\service\ksyun; namespace DtApp\ThinkLibrary\service\ksyun;
use DtApp\ThinkLibrary\Service; use DtApp\ThinkLibrary\Service;
use Ks3Client;
use Ks3ServiceException;
/** /**
* 金山云对象存储 * 金山云对象存储
@ -76,12 +78,14 @@ class Ks3Service extends Service
*/ */
public function upload(string $object, string $filePath) public function upload(string $object, string $filePath)
{ {
if (empty($this->accessKeyID)) $this->getConfig(); if (empty($this->accessKeyID) || empty($this->accessKeySecret) || empty($this->endpoint)) {
if (empty($this->accessKeySecret)) $this->getConfig(); $this->getConfig();
if (empty($this->endpoint)) $this->getConfig(); }
require_once(__DIR__ . "/bin/Ks3Client.class.php"); require_once(__DIR__ . "/bin/Ks3Client.class.php");
$client = new \Ks3Client($this->accessKeyID, $this->accessKeySecret, $this->endpoint); $client = new Ks3Client($this->accessKeyID, $this->accessKeySecret, $this->endpoint);
if (empty($this->bucket)) $this->getConfig(); if (empty($this->bucket)) {
$this->getConfig();
}
$content = fopen($filePath, "r"); $content = fopen($filePath, "r");
$args = [ $args = [
"Bucket" => $this->bucket, "Bucket" => $this->bucket,
@ -105,7 +109,7 @@ class Ks3Service extends Service
try { try {
$client->putObjectByFile($args); $client->putObjectByFile($args);
return $this->app->config->get('dtapp.ksyun.ks3.url', '') . $object; return $this->app->config->get('dtapp.ksyun.ks3.url', '') . $object;
} catch (\Ks3ServiceException $e) { } catch (Ks3ServiceException $e) {
return false; return false;
} }
} }

@ -441,9 +441,15 @@ class JinBaoService extends Service
public function toArray() public function toArray()
{ {
//首先检测是否支持curl //首先检测是否支持curl
if (!extension_loaded("curl")) throw new HttpException(404, '请开启curl模块'); if (!extension_loaded("curl")) {
if (empty($this->client_id)) $this->getConfig(); throw new HttpException(404, '请开启curl模块');
if (empty($this->client_id)) throw new DtaException('请检查client_id参数'); }
if (empty($this->client_id)) {
$this->getConfig();
}
if (empty($this->client_id)) {
throw new DtaException('请检查client_id参数');
}
$this->param['type'] = $this->type; $this->param['type'] = $this->type;
$this->param['client_id'] = $this->client_id; $this->param['client_id'] = $this->client_id;
$this->param['timestamp'] = time(); $this->param['timestamp'] = time();
@ -452,22 +458,32 @@ class JinBaoService extends Service
$this->http(); $this->http();
if (isset($this->output['error_response'])) { if (isset($this->output['error_response'])) {
// 错误 // 错误
if (is_array($this->output)) return $this->output; if (is_array($this->output)) {
if (is_object($this->output)) return $this->object2array($this->output); return $this->output;
}
if (is_object($this->output)) {
return $this->object2array($this->output);
}
return json_decode($this->output, true); return json_decode($this->output, true);
} else { } else {
// 正常 // 正常
if (is_array($this->output)) { if (is_array($this->output)) {
if (isset($this->output["{$this->response}"])) return $this->output["{$this->response}"]; if (isset($this->output["{$this->response}"])) {
return $this->output["{$this->response}"];
}
return $this->output; return $this->output;
} }
if (is_object($this->output)) { if (is_object($this->output)) {
$this->output = $this->object2array($this->output); $this->output = $this->object2array($this->output);
if (isset($this->output["$this->response"])) return $this->output["$this->response"]; if (isset($this->output["$this->response"])) {
return $this->output["$this->response"];
}
return $this->output; return $this->output;
} }
$this->output = json_decode($this->output, true); $this->output = json_decode($this->output, true);
if (isset($this->output["$this->response"])) return $this->output["$this->response"]; if (isset($this->output["$this->response"])) {
return $this->output["$this->response"];
}
return $this->output; return $this->output;
} }
} }
@ -480,7 +496,11 @@ class JinBaoService extends Service
{ {
if (is_object($object)) $arr = (array)($object); if (is_object($object)) $arr = (array)($object);
else $arr = &$object; else $arr = &$object;
if (is_array($arr)) foreach ($arr as $varName => $varValue) $arr[$varName] = $this->object2array($varValue); if (is_array($arr)) {
foreach ($arr as $varName => $varValue) {
$arr[$varName] = $this->object2array($varValue);
}
}
return $arr; return $arr;
} }
@ -491,12 +511,19 @@ class JinBaoService extends Service
*/ */
private function createSign() private function createSign()
{ {
if (empty($this->client_secret)) $this->getConfig(); if (empty($this->client_secret)) {
if (empty($this->client_secret)) throw new DtaException('请检查client_secret参数'); $this->getConfig();
}
if (empty($this->client_secret)) {
throw new DtaException('请检查client_secret参数}');
}
$sign = $this->client_secret; $sign = $this->client_secret;
ksort($this->param); ksort($this->param);
foreach ($this->param as $key => $val) if ($key != '' && $val != '') $sign .= $key . $val; foreach ($this->param as $key => $val) {
if ($key != '' && $val != '') {
$sign .= $key . $val;
}
}
$sign .= $this->client_secret; $sign .= $this->client_secret;
$sign = strtoupper(md5($sign)); $sign = strtoupper(md5($sign));
return $sign; return $sign;
@ -509,7 +536,11 @@ class JinBaoService extends Service
private function createStrParam() private function createStrParam()
{ {
$strParam = ''; $strParam = '';
foreach ($this->param as $key => $val) if ($key != '' && $val != '' && !is_array($val)) $strParam .= $key . '=' . urlencode($val) . '&'; foreach ($this->param as $key => $val) {
if ($key != '' && $val != '' && !is_array($val)) {
$strParam .= $key . '=' . urlencode($val) . '&';
}
}
return $strParam; return $strParam;
} }

@ -73,9 +73,9 @@ class KodoService extends Service
*/ */
public function upload(string $object, string $filePath) public function upload(string $object, string $filePath)
{ {
if (empty($this->accessKey)) $this->getConfig(); if (empty($this->accessKey) || empty($this->secretKey) || empty($this->bucket)) {
if (empty($this->secretKey)) $this->getConfig(); $this->getConfig();
if (empty($this->bucket)) $this->getConfig(); }
// 初始化签权对象 // 初始化签权对象
$auth = new Auth($this->accessKey, $this->secretKey); $auth = new Auth($this->accessKey, $this->secretKey);
// 生成上传Token // 生成上传Token
@ -84,7 +84,10 @@ class KodoService extends Service
$uploadMgr = new UploadManager(); $uploadMgr = new UploadManager();
// 调用 UploadManager 的 putFile 方法进行文件的上传。 // 调用 UploadManager 的 putFile 方法进行文件的上传。
list($ret, $err) = $uploadMgr->putFile($token, $object, $filePath); list($ret, $err) = $uploadMgr->putFile($token, $object, $filePath);
if ($err !== null) return false; if ($err !== null) {
else return $this->app->config->get('dtapp.qiniu.kodo.url', '') . $object; return false;
} else {
return $this->app->config->get('dtapp.qiniu.kodo.url', '') . $object;
}
} }
} }

@ -21,6 +21,7 @@ namespace DtApp\ThinkLibrary\service\taobao;
use DtApp\ThinkLibrary\exception\DtaException; use DtApp\ThinkLibrary\exception\DtaException;
use DtApp\ThinkLibrary\facade\Strings; use DtApp\ThinkLibrary\facade\Strings;
use DtApp\ThinkLibrary\facade\Times;
use DtApp\ThinkLibrary\Service; use DtApp\ThinkLibrary\Service;
use think\exception\HttpException; use think\exception\HttpException;
@ -247,7 +248,9 @@ class TbkService extends Service
*/ */
public function tpWdCreate() public function tpWdCreate()
{ {
if (isset($this->param['text'])) if (strlen($this->param['text']) < 5) throw new DtaException('text'); if (isset($this->param['text']) && strlen($this->param['text']) < 5) {
throw new DtaException('请检查text参数长度');
}
$this->method = 'taobao.tbk.tpwd.create'; $this->method = 'taobao.tbk.tpwd.create';
return $this; return $this;
} }
@ -281,7 +284,9 @@ class TbkService extends Service
*/ */
public function juTqgGet() public function juTqgGet()
{ {
if (!isset($this->param['fields'])) $this->param['fields'] = "click_url,pic_url,reserve_price,zk_final_price,total_amount,sold_num,title,category_name,start_time,end_time"; if (!isset($this->param['fields'])) {
$this->param['fields'] = "click_url,pic_url,reserve_price,zk_final_price,total_amount,sold_num,title,category_name,start_time,end_time";
}
$this->method = 'taobao.tbk.ju.tqg.get'; $this->method = 'taobao.tbk.ju.tqg.get';
return $this; return $this;
} }
@ -385,7 +390,9 @@ class TbkService extends Service
*/ */
public function shopGet() public function shopGet()
{ {
if (!isset($this->param['fields'])) $this->param['fields'] = "user_id,shop_title,shop_type,seller_nick,pict_url,shop_url"; if (!isset($this->param['fields'])) {
$this->param['fields'] = "user_id,shop_title,shop_type,seller_nick,pict_url,shop_url";
}
$this->method = 'taobao.tbk.shop.get'; $this->method = 'taobao.tbk.shop.get';
return $this; return $this;
} }
@ -446,7 +453,9 @@ class TbkService extends Service
*/ */
public function itemConvert() public function itemConvert()
{ {
if (!isset($this->param['fields'])) $this->param['fields'] = "num_iid,click_url"; if (!isset($this->param['fields'])) {
$this->param['fields'] = "num_iid,click_url";
}
$this->method = 'taobao.tbk.item.convert'; $this->method = 'taobao.tbk.item.convert';
return $this; return $this;
} }
@ -525,34 +534,53 @@ class TbkService extends Service
public function toArray() public function toArray()
{ {
//首先检测是否支持curl //首先检测是否支持curl
if (!extension_loaded("curl")) throw new HttpException(404, '请开启curl模块'); if (!extension_loaded("curl")) {
throw new HttpException(404, '请开启curl模块');
}
$this->format = "json"; $this->format = "json";
if (empty($this->app_key)) $this->getConfig(); if (empty($this->app_key)) {
if (empty($this->app_key)) throw new DtaException('请检查app_key参数'); $this->getConfig();
if (empty($this->method)) throw new DtaException('请检查method参数'); }
if (empty($this->app_key)) {
throw new DtaException('请检查app_key参数');
}
if (empty($this->method)) {
throw new DtaException('请检查method参数');
}
$this->param['app_key'] = $this->app_key; $this->param['app_key'] = $this->app_key;
$this->param['method'] = $this->method; $this->param['method'] = $this->method;
$this->param['format'] = $this->format; $this->param['format'] = $this->format;
$this->param['v'] = $this->v; $this->param['v'] = $this->v;
$this->param['sign_method'] = $this->sign_method; $this->param['sign_method'] = $this->sign_method;
$this->param['timestamp'] = date('Y-m-d H:i:s'); $this->param['timestamp'] = Times::getData();
$this->http(); $this->http();
if (isset($this->output['error_response'])) { if (isset($this->output['error_response'])) {
// 错误 // 错误
if (is_array($this->output)) return $this->output; if (is_array($this->output)) {
if (is_object($this->output)) $this->output = json_encode($this->output, JSON_UNESCAPED_UNICODE); return $this->output;
}
if (is_object($this->output)) {
$this->output = json_encode($this->output, JSON_UNESCAPED_UNICODE);
}
return json_decode($this->output, true); return json_decode($this->output, true);
} else { } else {
// 正常 // 正常
$response = substr(Strings::replace('.', '_', $this->method), 7) . "_response"; $response = substr(Strings::replace('.', '_', $this->method), 7) . "_response";
if (is_array($this->output)) { if (is_array($this->output)) {
if (isset($this->output["$response"])) return $this->output["$response"]; if (isset($this->output["$response"])) {
return $this->output["$response"];
}
return $this->output; return $this->output;
}; };
if (is_object($this->output)) $this->output = json_encode($this->output, JSON_UNESCAPED_UNICODE); if (is_object($this->output)) {
$this->output = json_encode($this->output, JSON_UNESCAPED_UNICODE);
}
$this->output = json_decode($this->output, true); $this->output = json_decode($this->output, true);
if (isset($this->output["$response"])) return $this->output["$response"]; if (isset($this->output["$response"])) {
else return $this->output; return $this->output["$response"];
} else {
return $this->output;
}
} }
} }
@ -564,7 +592,9 @@ class TbkService extends Service
public function toXml() public function toXml()
{ {
//首先检测是否支持curl //首先检测是否支持curl
if (!extension_loaded("curl")) throw new HttpException('请开启curl模块', E_USER_DEPRECATED); if (!extension_loaded("curl")) {
throw new HttpException('请开启curl模块', E_USER_DEPRECATED);
}
$this->format = "xml"; $this->format = "xml";
$this->http(); $this->http();
return $this->output; return $this->output;
@ -582,8 +612,11 @@ class TbkService extends Service
$strParam = $this->createStrParam(); $strParam = $this->createStrParam();
$strParam .= 'sign=' . $sign; $strParam .= 'sign=' . $sign;
//访问服务 //访问服务
if (empty($this->sandbox)) $url = 'http://gw.api.taobao.com/router/rest?' . $strParam; if (empty($this->sandbox)) {
else $url = 'http://gw.api.tbsandbox.com/router/rest?' . $strParam; $url = 'http://gw.api.taobao.com/router/rest?' . $strParam;
} else {
$url = 'http://gw.api.tbsandbox.com/router/rest?' . $strParam;
}
$result = file_get_contents($url); $result = file_get_contents($url);
$result = json_decode($result, true); $result = json_decode($result, true);
$this->output = $result; $this->output = $result;
@ -596,12 +629,19 @@ class TbkService extends Service
*/ */
private function createSign() private function createSign()
{ {
if (empty($this->app_secret)) $this->getConfig(); if (empty($this->app_secret)) {
if (empty($this->app_secret)) throw new DtaException('请检查app_secret参数'); $this->getConfig();
}
if (empty($this->app_secret)) {
throw new DtaException('请检查app_secret参数');
}
$sign = $this->app_secret; $sign = $this->app_secret;
ksort($this->param); ksort($this->param);
foreach ($this->param as $key => $val) if ($key != '' && $val != '') $sign .= $key . $val; foreach ($this->param as $key => $val) {
if ($key != '' && $val != '') {
$sign .= $key . $val;
}
}
$sign .= $this->app_secret; $sign .= $this->app_secret;
$sign = strtoupper(md5($sign)); $sign = strtoupper(md5($sign));
return $sign; return $sign;
@ -614,7 +654,11 @@ class TbkService extends Service
private function createStrParam() private function createStrParam()
{ {
$strParam = ''; $strParam = '';
foreach ($this->param as $key => $val) if ($key != '' && $val != '') $strParam .= $key . '=' . urlencode($val) . '&'; foreach ($this->param as $key => $val) {
if ($key != '' && $val != '') {
$strParam .= $key . '=' . urlencode($val) . '&';
}
}
return $strParam; return $strParam;
} }

@ -79,9 +79,9 @@ class CosService extends Service
*/ */
public function upload(string $object, string $filePath) public function upload(string $object, string $filePath)
{ {
if (empty($this->secretId)) $this->getConfig(); if (empty($this->secretId) || empty($this->secretKey) || empty($this->region)) {
if (empty($this->secretKey)) $this->getConfig(); $this->getConfig();
if (empty($this->region)) $this->getConfig(); }
$cosClient = new Client( $cosClient = new Client(
array( array(
'region' => $this->region, 'region' => $this->region,
@ -95,13 +95,15 @@ class CosService extends Service
$key = $object; $key = $object;
$file = fopen($filePath, "rb"); $file = fopen($filePath, "rb");
if ($file) { if ($file) {
if (empty($this->bucket)) $this->getConfig(); if (empty($this->bucket)) {
$result = $cosClient->putObject( $this->getConfig();
array( $result = $cosClient->putObject(
'Bucket' => $this->bucket, array(
'Key' => $key, 'Bucket' => $this->bucket,
'Body' => $file) 'Key' => $key,
); 'Body' => $file)
);
}
} }
return $this->app->config->get('dtapp.tencent.cos.url', '') . $object; return $this->app->config->get('dtapp.tencent.cos.url', '') . $object;
} }

@ -73,9 +73,9 @@ class UssService extends Service
*/ */
public function upload(string $object, string $filePath) public function upload(string $object, string $filePath)
{ {
if (empty($this->serviceName)) $this->getConfig(); if (empty($this->serviceName) || empty($this->operatorName) || empty($this->operatorPassword)) {
if (empty($this->operatorName)) $this->getConfig(); $this->getConfig();
if (empty($this->operatorPassword)) $this->getConfig(); }
$serviceConfig = new Config($this->serviceName, $this->operatorName, $this->operatorPassword); $serviceConfig = new Config($this->serviceName, $this->operatorName, $this->operatorPassword);
$client = new Upyun($serviceConfig); $client = new Upyun($serviceConfig);
$file = fopen($filePath, 'r'); $file = fopen($filePath, 'r');

@ -332,10 +332,15 @@ class MiniService extends Service
*/ */
public function code2Session(string $js_code) public function code2Session(string $js_code)
{ {
if (empty($this->app_id)) $this->getConfig(); if (empty($this->app_id) || empty($this->app_secret)) {
if (empty($this->app_secret)) $this->getConfig(); $this->getConfig();
if (empty($this->app_id)) throw new DtaException('请检查app_id参数'); }
if (empty($this->app_secret)) throw new DtaException('请检查app_secret参数'); if (empty($this->app_id)) {
throw new DtaException('请检查app_id参数');
}
if (empty($this->app_secret)) {
throw new DtaException('请检查app_secret参数');
}
$this->grant_type = "authorization_code"; $this->grant_type = "authorization_code";
$url = "{$this->api_url}sns/jscode2session?appid={$this->app_id}&secret={$this->app_secret}&js_code={$js_code}&grant_type={$this->grant_type}"; $url = "{$this->api_url}sns/jscode2session?appid={$this->app_id}&secret={$this->app_secret}&js_code={$js_code}&grant_type={$this->grant_type}";
return HttpService::instance() return HttpService::instance()
@ -354,7 +359,9 @@ class MiniService extends Service
public function userInfo(string $js_code, string $encrypted_data, string $iv) public function userInfo(string $js_code, string $encrypted_data, string $iv)
{ {
$session = $this->code2Session($js_code); $session = $this->code2Session($js_code);
if (!isset($session['openid'])) return false; if (!isset($session['openid'])) {
return false;
}
$result = openssl_decrypt(base64_decode($encrypted_data), "AES-128-CBC", base64_decode($session['session_key']), 1, base64_decode($iv)); $result = openssl_decrypt(base64_decode($encrypted_data), "AES-128-CBC", base64_decode($session['session_key']), 1, base64_decode($iv));
return json_decode($result, true); return json_decode($result, true);
} }
@ -370,7 +377,9 @@ class MiniService extends Service
public function userPhone(string $js_code, string $encrypted_data, string $iv) public function userPhone(string $js_code, string $encrypted_data, string $iv)
{ {
$session = $this->code2Session($js_code); $session = $this->code2Session($js_code);
if (!isset($session['openid'])) return false; if (!isset($session['openid'])) {
return false;
}
$result = openssl_decrypt(base64_decode($encrypted_data), "AES-128-CBC", base64_decode($session['session_key']), 1, base64_decode($iv)); $result = openssl_decrypt(base64_decode($encrypted_data), "AES-128-CBC", base64_decode($session['session_key']), 1, base64_decode($iv));
return json_decode($result, true); return json_decode($result, true);
} }
@ -413,12 +422,18 @@ class MiniService extends Service
*/ */
private function getAccessToken() private function getAccessToken()
{ {
if (empty($this->cache)) $this->getConfig(); if (empty($this->cache) || empty($this->app_id) || empty($this->app_secret)) {
if (empty($this->app_id)) $this->getConfig(); $this->getConfig();
if (empty($this->app_secret)) $this->getConfig(); }
if (empty($this->cache)) throw new DtaException('请检查cache参数'); if (empty($this->cache)) {
if (empty($this->app_id)) throw new DtaException('请检查app_id参数'); throw new DtaException('请检查cache参数');
if (empty($this->app_secret)) throw new DtaException('请检查app_secret参数'); }
if (empty($this->app_id)) {
throw new DtaException('请检查app_id参数');
}
if (empty($this->app_secret)) {
throw new DtaException('请检查app_secret参数');
}
$this->grant_type = "client_credential"; $this->grant_type = "client_credential";
if ($this->cache == "file") { if ($this->cache == "file") {
// 文件名 // 文件名
@ -469,6 +484,8 @@ class MiniService extends Service
$access_token['access_token'] = $accessToken_res['access_token']; $access_token['access_token'] = $accessToken_res['access_token'];
} }
return $access_token; return $access_token;
} else throw new DtaException("驱动方式错误"); } else {
throw new DtaException("驱动方式错误");
}
} }
} }

@ -89,13 +89,19 @@ class QyService extends Service
*/ */
private function sendMsg(array $data) private function sendMsg(array $data)
{ {
if (empty($this->key)) throw new DtaException("请检查KEY"); if (empty($this->key)) {
if (empty($data['msgtype'])) $data['msgtype'] = $this->msgType; throw new DtaException("请检查KEY");
}
if (empty($data['msgtype'])) {
$data['msgtype'] = $this->msgType;
}
$result = HttpService::instance() $result = HttpService::instance()
->url("{$this->url}cgi-bin/webhook/send?key=" . $this->key) ->url("{$this->url}cgi-bin/webhook/send?key=" . $this->key)
->data($data) ->data($data)
->toArray(); ->toArray();
if ($result['errcode'] == 0) return true; if ($result['errcode'] == 0) {
return true;
}
return false; return false;
} }
} }

@ -148,7 +148,9 @@ class WebAppService extends Service
*/ */
public function redirectUri(string $redirectUri) public function redirectUri(string $redirectUri)
{ {
if (empty(Pregs::isLink($redirectUri))) throw new DtaException("请检查redirectUri是否正确"); if (empty(Pregs::isLink($redirectUri))) {
throw new DtaException("请检查redirectUri是否正确");
}
$this->redirect_uri = Urls::lenCode($redirectUri); $this->redirect_uri = Urls::lenCode($redirectUri);
return $this; return $this;
} }
@ -161,9 +163,13 @@ class WebAppService extends Service
*/ */
public function scope(string $scope) public function scope(string $scope)
{ {
if ($scope === "snsapi_base") $this->scope = $scope; if ($scope === "snsapi_base") {
elseif ($scope === "snsapi_userinfo") $this->scope = $scope; $this->scope = $scope;
else throw new DtaException("请检查scope参数"); } elseif ($scope === "snsapi_userinfo") {
$this->scope = $scope;
} else {
throw new DtaException("请检查scope参数");
}
return $this; return $this;
} }
@ -197,8 +203,12 @@ class WebAppService extends Service
*/ */
public function oauth2() public function oauth2()
{ {
if (empty($this->app_id)) $this->getConfig(); if (empty($this->app_id)) {
if (strlen($this->state) > 128) throw new DtaException("请检查state参数最多128字节"); $this->getConfig();
}
if (strlen($this->state) > 128) {
throw new DtaException("请检查state参数最多128字节");
}
$params = Urls::toParams([ $params = Urls::toParams([
'appid' => $this->app_id, 'appid' => $this->app_id,
'redirect_uri' => $this->redirect_uri, 'redirect_uri' => $this->redirect_uri,
@ -218,10 +228,15 @@ class WebAppService extends Service
*/ */
public function accessToken(string $code, bool $is = true) public function accessToken(string $code, bool $is = true)
{ {
if (empty($this->app_id)) $this->getConfig(); if (empty($this->app_id) || empty($this->app_secret)) {
if (empty($this->app_secret)) $this->getConfig(); $this->getConfig();
if (empty($this->app_id)) throw new DtaException('请检查app_id参数'); }
if (empty($this->app_secret)) throw new DtaException('请检查app_secret参数'); if (empty($this->app_id)) {
throw new DtaException('请检查app_id参数');
}
if (empty($this->app_secret)) {
throw new DtaException('请检查app_secret参数');
}
return HttpService::instance() return HttpService::instance()
->url("{$this->api_url}sns/oauth2/access_token?appid={$this->app_id}&secret={$this->app_secret}&code={$code}&grant_type={$this->grant_type}") ->url("{$this->api_url}sns/oauth2/access_token?appid={$this->app_id}&secret={$this->app_secret}&code={$code}&grant_type={$this->grant_type}")
->toArray($is); ->toArray($is);
@ -236,8 +251,12 @@ class WebAppService extends Service
*/ */
public function refreshToken(string $refreshToken, bool $is = true) public function refreshToken(string $refreshToken, bool $is = true)
{ {
if (empty($this->app_id)) $this->getConfig(); if (empty($this->app_id)) {
if (empty($this->app_id)) throw new DtaException('请检查app_id参数'); $this->getConfig();
}
if (empty($this->app_id)) {
throw new DtaException('请检查app_id参数');
}
$this->grant_type = "refresh_token"; $this->grant_type = "refresh_token";
return HttpService::instance() return HttpService::instance()
->url("{$this->api_url}sns/oauth2/refresh_token?appid={$this->app_id}&grant_type={$this->grant_type}&refresh_token={$refreshToken}") ->url("{$this->api_url}sns/oauth2/refresh_token?appid={$this->app_id}&grant_type={$this->grant_type}&refresh_token={$refreshToken}")
@ -254,8 +273,9 @@ class WebAppService extends Service
*/ */
public function useInfo(string $accessToken, string $openid, $lang = "zh_CN", bool $is = true) public function useInfo(string $accessToken, string $openid, $lang = "zh_CN", bool $is = true)
{ {
if (empty($this->app_id)) $this->getConfig(); if (empty($this->app_id) || empty($this->app_secret)) {
if (empty($this->app_secret)) $this->getConfig(); $this->getConfig();
}
return HttpService::instance() return HttpService::instance()
->url("{$this->api_url}sns/userinfo?access_token={$accessToken}&openid={$openid}&lang={$lang}") ->url("{$this->api_url}sns/userinfo?access_token={$accessToken}&openid={$openid}&lang={$lang}")
->toArray($is); ->toArray($is);
@ -270,8 +290,9 @@ class WebAppService extends Service
*/ */
public function auth(string $accessToken, string $openid, bool $is = true) public function auth(string $accessToken, string $openid, bool $is = true)
{ {
if (empty($this->app_id)) $this->getConfig(); if (empty($this->app_id) || empty($this->app_secret)) {
if (empty($this->app_secret)) $this->getConfig(); $this->getConfig();
}
return HttpService::instance() return HttpService::instance()
->url("{$this->api_url}sns/auth?access_token={$accessToken}&openid={$openid}") ->url("{$this->api_url}sns/auth?access_token={$accessToken}&openid={$openid}")
->toArray($is); ->toArray($is);
@ -287,8 +308,12 @@ class WebAppService extends Service
*/ */
public function share() public function share()
{ {
if (empty($this->app_id)) $this->getConfig(); if (empty($this->app_id)) {
if (empty($this->app_id)) throw new DtaException('请检查app_id参数'); $this->getConfig();
}
if (empty($this->app_id)) {
throw new DtaException('请检查app_id参数');
}
// 获取数据 // 获取数据
$accessToken = $this->getAccessToken(); $accessToken = $this->getAccessToken();
if (!isset($accessToken['access_token'])) throw new DtaException("获取access_token错误" . $accessToken['errmsg']); if (!isset($accessToken['access_token'])) throw new DtaException("获取access_token错误" . $accessToken['errmsg']);
@ -298,11 +323,15 @@ class WebAppService extends Service
if (!empty($res['errcode'])) { if (!empty($res['errcode'])) {
// 获取数据 // 获取数据
$accessToken = $this->getAccessToken(); $accessToken = $this->getAccessToken();
if (!isset($accessToken['access_token'])) throw new DtaException("获取access_token错误" . $accessToken['errmsg']); if (!isset($accessToken['access_token'])) {
throw new DtaException("获取access_token错误" . $accessToken['errmsg']);
}
$res = HttpService::instance() $res = HttpService::instance()
->url("{$this->api_url}cgi-bin/ticket/getticket?access_token={$accessToken['access_token']}&type=jsapi") ->url("{$this->api_url}cgi-bin/ticket/getticket?access_token={$accessToken['access_token']}&type=jsapi")
->toArray(); ->toArray();
if (!empty($res['errcode'])) throw new DtaException('accessToken已过期'); if (!empty($res['errcode'])) {
throw new DtaException('accessToken已过期');
}
} }
// 注意 URL 一定要动态获取,不能 hardcode. // 注意 URL 一定要动态获取,不能 hardcode.
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://"; $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
@ -327,7 +356,9 @@ class WebAppService extends Service
{ {
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$str = ""; $str = "";
for ($i = 0; $i < $length; $i++) $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1); for ($i = 0; $i < $length; $i++) {
$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
}
return $str; return $str;
} }
@ -593,12 +624,18 @@ class WebAppService extends Service
*/ */
private function getAccessToken() private function getAccessToken()
{ {
if (empty($this->cache)) $this->getConfig(); if (empty($this->cache) || empty($this->app_id) || empty($this->app_secret)) {
if (empty($this->app_id)) $this->getConfig(); $this->getConfig();
if (empty($this->app_secret)) $this->getConfig(); }
if (empty($this->cache)) throw new DtaException('请检查cache参数'); if (empty($this->cache)) {
if (empty($this->app_id)) throw new DtaException('请检查app_id参数'); throw new DtaException('请检查cache参数');
if (empty($this->app_secret)) throw new DtaException('请检查app_secret参数'); }
if (empty($this->app_id)) {
throw new DtaException('请检查app_id参数');
}
if (empty($this->app_secret)) {
throw new DtaException('请检查app_secret参数');
}
$this->grant_type = "client_credential"; $this->grant_type = "client_credential";
if ($this->cache == "file") { if ($this->cache == "file") {
@ -673,7 +710,9 @@ class WebAppService extends Service
$access_token['access_token'] = $accessToken_res['access_token']; $access_token['access_token'] = $accessToken_res['access_token'];
} }
return $access_token; return $access_token;
} else throw new DtaException("驱动方式错误"); } else {
throw new DtaException("驱动方式错误");
}
} }
/** /**
@ -724,8 +763,11 @@ class WebAppService extends Service
// 在字符串接商户支付秘钥 // 在字符串接商户支付秘钥
$stringSignTemp = "{$stringA}&key=" . $this->mch_key; $stringSignTemp = "{$stringA}&key=" . $this->mch_key;
//步骤四MD5或HMAC-SHA256C加密 //步骤四MD5或HMAC-SHA256C加密
if ($hmacsha256) $str = hash_hmac("sha256", $stringSignTemp, $this->mch_key); if ($hmacsha256) {
else $str = md5($stringSignTemp); $str = hash_hmac("sha256", $stringSignTemp, $this->mch_key);
} else {
$str = md5($stringSignTemp);
}
//符转大写 //符转大写
return strtoupper($str); return strtoupper($str);
} }

Loading…
Cancel
Save