CommonServer.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. <?php
  2. namespace App\Servers\System;
  3. use AlibabaCloud\Client\AlibabaCloud;
  4. use AlibabaCloud\Client\Exception\ClientException;
  5. use AlibabaCloud\Client\Exception\ServerException;
  6. use App\Models\Config;
  7. use App\Models\Region;
  8. use Carbon\Carbon;
  9. use Illuminate\Support\Facades\Storage;
  10. use QCloud\COSSTS\Sts;
  11. /**
  12. * Redis数据缓存类
  13. */
  14. class CommonServer
  15. {
  16. /**
  17. * 错误信息
  18. * @var string
  19. */
  20. private $errorMsg = '';
  21. static private $server = null;
  22. private function __construct()
  23. {
  24. }
  25. /**
  26. * 创建对象
  27. * @return CommonServer
  28. */
  29. static function creatServer()
  30. {
  31. if (empty(self::$server)) self::$server = new CommonServer();
  32. return self::$server;
  33. }
  34. /**
  35. * 验证手机号码格式
  36. * @param $phone
  37. * @return bool
  38. */
  39. public function verifyPhoneNumber($phone)
  40. {
  41. if (empty($phone)) return false;
  42. if (!preg_match('#^[\d]{11,11}$#', $phone)) {
  43. return false;
  44. }
  45. return true;
  46. }
  47. /**
  48. * 字符串去标签过滤及空格过滤
  49. * @param $str_name
  50. * @param $default
  51. * @return string
  52. */
  53. function filtrationStr($str_name, $default = '')
  54. {
  55. $str = request()->input($str_name, $default);
  56. if (empty($str)) return $str;
  57. if (!is_string($str)) {
  58. $str = json_encode($str);
  59. $str = strip_tags($str);
  60. $str = trim($str);
  61. $str = json_decode($str, true);
  62. } else {
  63. $str = strip_tags($str);
  64. $str = trim($str);
  65. }
  66. return $str;
  67. }
  68. /**
  69. * 获取城市名称
  70. * @param string $province_id
  71. * @param string $city_id
  72. * @param string $area_id
  73. * @return string
  74. */
  75. function getCityName($province_id = '', $city_id = '', $area_id = '')
  76. {
  77. $ids = [$province_id, $city_id, $area_id];
  78. $ids = array_filter($ids);
  79. if (empty($ids)) return '';
  80. $city_name = Region::whereIn('id', $ids)->orderBy('id', 'asc')->pluck('name')->toArray();
  81. $city_name = implode(' ', $city_name);
  82. return $city_name;
  83. }
  84. /**
  85. * 字符串屏蔽
  86. * @param $str
  87. * @param int $start_key 开始位置
  88. * @param int $end_key 尾数开始位置
  89. * @param int $start_num 截取位数
  90. * @param int $end_num 倒数截取位数
  91. * @param int $conceal_num 最大填充数量
  92. * @return string
  93. */
  94. function concealStr($str, $start_key = 0, $end_key = 1, $start_num = 1, $end_num = 1, $conceal_num = 3)
  95. {
  96. $str_len = mb_strlen($str);
  97. $start_str = '';
  98. $end_str = '';
  99. if (($str_len - $start_num - $end_num) < $conceal_num) {
  100. $conceal_num = $str_len - $start_num - $end_num;
  101. }
  102. $conceal_str = $this->getRandChar($conceal_num, '*');
  103. if (empty($conceal_str)) $conceal_str = '*';
  104. if ($str_len >= $start_key) {
  105. $start_str = mb_substr($str, $start_key, $start_num);
  106. }
  107. if ($str_len > $end_key) {
  108. $end_str = mb_substr($str, $end_key * -1, $end_num);
  109. }
  110. return $start_str . $conceal_str . $end_str;
  111. }
  112. /**
  113. * 获取随机字符串
  114. * @param int $length
  115. * @param string $strPol
  116. * @return string|null
  117. */
  118. public function getRandChar($length = 6, $strPol = '')
  119. {
  120. if ($length <= 0) $length = 1;
  121. $str = null;
  122. if (empty($strPol)) $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
  123. $max = strlen($strPol) - 1;
  124. for ($i = 0; $i < $length; $i++) {
  125. $str .= $strPol[rand(0, $max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
  126. }
  127. return $str;
  128. }
  129. /**
  130. * 获取数据库配置信息
  131. * @param $key
  132. * @return mixed
  133. */
  134. function getConfigValue($key)
  135. {
  136. return Config::where('key', $key)->value('value');
  137. }
  138. /**
  139. * 创建文件夹
  140. * @param $dir
  141. * @return bool
  142. */
  143. function creatDir($dir)
  144. {
  145. if ($dir == '') return false;
  146. if (!file_exists(public_path($dir))) {
  147. mkdir(public_path($dir), 0777, true);
  148. chmod(public_path($dir), 0777);
  149. }
  150. return true;
  151. }
  152. /**
  153. * 验证是否微信浏览器
  154. * @return bool
  155. */
  156. function isWeixin()
  157. {
  158. $http_user_agent = request()->header('user-agent');
  159. if (strpos($http_user_agent, 'MicroMessenger') !== false) {
  160. return true;
  161. }
  162. return false;
  163. }
  164. /**
  165. * 格式化小数位数
  166. * @param $num
  167. * @param int $digit
  168. * @return string
  169. */
  170. function setFloatNum($num, $digit = 4)
  171. {
  172. return sprintf("%.{$digit}f", $num);
  173. }
  174. /**
  175. * 获取真实IP
  176. * @return mixed
  177. */
  178. function getClientIp()
  179. {
  180. $http_x_forwarded_for = request()->header('x-forwarded-for');
  181. if (empty($http_x_forwarded_for)) {
  182. return request()->getClientIp();
  183. } else {
  184. $http_x_forwarded_for = explode(',', $http_x_forwarded_for);
  185. return $http_x_forwarded_for[0];
  186. }
  187. }
  188. function delDir($dir)
  189. {
  190. //先删除目录下的文件:
  191. $dh = opendir($dir);
  192. while ($file = readdir($dh)) {
  193. if ($file != "." && $file != "..") {
  194. $fullpath = $dir . "/" . $file;
  195. if (!is_dir($fullpath)) {
  196. unlink($fullpath);
  197. } else {
  198. $this->deldir($fullpath);
  199. }
  200. }
  201. }
  202. closedir($dh);
  203. //删除当前文件夹:
  204. if (rmdir($dir)) {
  205. return true;
  206. } else {
  207. return false;
  208. }
  209. }
  210. /**
  211. * 图片base64
  212. * @param $image_file
  213. * @return string
  214. */
  215. function base64EncodeImage($image_file)
  216. {
  217. $image_info = getimagesize($image_file);
  218. $image_data = fread(fopen($image_file, 'r'), filesize($image_file));
  219. $base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data));
  220. return $base64_image;
  221. }
  222. /**
  223. * 获取文件名
  224. * @param $url
  225. * @return string
  226. */
  227. function getFileName($url)
  228. {
  229. $name = basename($url);
  230. return empty($name) ? '' : $name;
  231. }
  232. /**
  233. * @param $url
  234. * @param string $type 请求方式
  235. * @param string $data 数据 数组格式
  236. * @param $head
  237. * @param $retType
  238. * @return mixed
  239. */
  240. function sendRequest($url, $data = '', $type = 'get',$head=[],$retType='json')
  241. {
  242. $ch = curl_init();
  243. if ($type == 'get' && $data) {
  244. $url = $url . '?' . http_build_query($data);
  245. }
  246. // dump(date('Y-m-d H:i:s'));
  247. // dump($url);
  248. curl_setopt($ch, CURLOPT_URL, $url); //设置访问路径
  249. curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); //设置可以返回字符串
  250. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  251. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  252. if(empty($head)){
  253. $head = [
  254. 'User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36',
  255. 'Content-Type: application/json'
  256. ];
  257. }
  258. // curl_setopt($ch, CURLINFO_HEADER_OUT, true);
  259. curl_setopt($ch, CURLOPT_HTTPHEADER, $head);
  260. if ($type == 'post') {
  261. curl_setopt($ch, CURLOPT_POST, TRUE);//post请求
  262. $data = json_encode($data, JSON_UNESCAPED_UNICODE);
  263. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//设置传递的参数
  264. }
  265. $request = curl_exec($ch);
  266. // $header_size = curl_getinfo($ch,);
  267. // dump($request);
  268. if($request){
  269. if($retType=='gzip'){
  270. $request=gzdecode($request);
  271. }
  272. $request=json_decode($request,true);
  273. }
  274. // dump($request);
  275. // dump(date('Y-m-d H:i:s'));
  276. curl_close($ch);
  277. return $request;
  278. }
  279. function lockCapitalRoutes($mId,$routeName,$type){
  280. $routeArr= [
  281. 'withdraw.add',//提现
  282. ];
  283. if(in_array($routeName,$routeArr)){
  284. $redisName=$mId.'lockCapital';
  285. if($type){
  286. $row= RedisDataServer::creatServer()->getData($redisName);
  287. $isOutput= RedisDataServer::creatServer()->getData('dateOutput');
  288. if($row || $isOutput){
  289. return false;
  290. }
  291. RedisDataServer::creatServer()->setData($redisName,time(),'str',3,false);
  292. }else{
  293. RedisDataServer::creatServer()->delData($redisName);
  294. }
  295. }
  296. return true;
  297. }
  298. function getTxySts()
  299. {
  300. $data = RedisDataServer::creatServer()->getData('txy_sts_data');
  301. if ($data) {
  302. $data = json_decode($data, true);
  303. } else {
  304. $sts = new Sts();
  305. $accessKeyId = env('TXY_OSS_ACCESS_ID');
  306. $accessSecret = env('TXY_OSS_ACCESS_KEY');
  307. $config = array(
  308. 'url' => 'https://sts.tencentcloudapi.com/', // url和domain保持一致
  309. 'domain' => 'sts.tencentcloudapi.com', // 域名,非必须,默认为 sts.tencentcloudapi.com
  310. 'proxy' => '',
  311. 'secretId' => $accessKeyId, // 固定密钥,若为明文密钥,请直接以'xxx'形式填入,不要填写到getenv()函数中
  312. 'secretKey' => $accessSecret, // 固定密钥,若为明文密钥,请直接以'xxx'形式填入,不要填写到getenv()函数中
  313. 'bucket' => env('COSV5_BUCKET'), // 换成你的 bucket
  314. 'region' => env('COSV5_REGION'), // 换成 bucket 所在园区
  315. 'durationSeconds' => 1800, // 密钥有效期
  316. 'allowPrefix' => ['/'], // 这里改成允许的路径前缀,可以根据自己网站的用户登录态判断允许上传的具体路径,例子: a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
  317. // 密钥的权限列表。简单上传和分片需要以下的权限,其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
  318. 'allowActions' => array(
  319. // 简单上传
  320. 'name/cos:PutObject',
  321. 'name/cos:PostObject',
  322. // 分片上传
  323. 'name/cos:InitiateMultipartUpload',
  324. 'name/cos:ListMultipartUploads',
  325. 'name/cos:ListParts',
  326. 'name/cos:UploadPart',
  327. 'name/cos:CompleteMultipartUpload'
  328. )
  329. );
  330. try {
  331. $result = $sts->getTempKeys($config);
  332. if (empty($result['credentials'])) {
  333. return ['code' => 0, 'msg' => '权限生成失败'];
  334. }
  335. $data = $result['credentials'];
  336. $data['StartTime'] = time();
  337. $data['ExpiredTime'] = time() + 1700;
  338. RedisDataServer::creatServer()->setData('txy_sts_data', $data, 'json', 800);
  339. } catch (\Exception $e) {
  340. return ['code' => 0, 'msg' => $e->getMessage()];
  341. }
  342. }
  343. return ['code' => 1, 'msg' => '获取信息成功', 'data' => $data];
  344. }
  345. /**
  346. * 微信签名
  347. */
  348. function wxSign($data, $keys)
  349. {
  350. ksort($data);
  351. $str = '';
  352. foreach ($data as $key => $val) {
  353. if ($val) {
  354. if ($str != '') $str .= '&';
  355. $str .= "{$key}={$val}";
  356. }
  357. }
  358. $str .= '&key=' . $keys;
  359. $sign = strtoupper(MD5($str));
  360. return $sign;
  361. }
  362. /**
  363. * 获取阿里云sts临时权限
  364. */
  365. function getAliSts()
  366. {
  367. $data = RedisDataServer::creatServer()->getData('sts_data');
  368. if ($data) {
  369. $data = json_decode($data, true);
  370. } else {
  371. $accessKeyId = env('ALI_OSS_ACCESS_ID');
  372. $accessSecret = env('ALI_OSS_ACCESS_KEY');
  373. AlibabaCloud::accessKeyClient($accessKeyId, $accessSecret)->regionId('cn-hangzhou')->asDefaultClient();
  374. //设置参数,发起请求。
  375. try {
  376. $result = AlibabaCloud::rpc()
  377. ->product('Sts')
  378. ->scheme('https') // https | http
  379. ->version('2015-04-01')
  380. ->action('AssumeRole')
  381. ->method('POST')
  382. ->host('sts.aliyuncs.com')
  383. ->options([
  384. 'query' => [
  385. 'RegionId' => "cn-chengdu",
  386. 'RoleArn' => "acs:ram::1470797691368660:role/oss-js",
  387. 'RoleSessionName' => "js-oss-serve",
  388. 'DurationSeconds' => 900,
  389. ],
  390. ])
  391. ->request();
  392. $result = $result->toArray();
  393. if (empty($result['Credentials'])) {
  394. return ['code' => 0, 'msg' => '获取token信息失败'];
  395. }
  396. $data = $result['Credentials'];
  397. unset($data['Expiration']);
  398. RedisDataServer::creatServer()->setData('sts_data', $data, 'json', 800);
  399. } catch (ClientException $e) {
  400. return ['code' => 0, 'msg' => $e->getErrorMessage()];
  401. } catch (ServerException $e) {
  402. return ['code' => 0, 'msg' => $e->getErrorMessage()];
  403. }
  404. }
  405. return ['code' => 1, 'msg' => '获取信息成功', 'data' => $data];
  406. }
  407. }