| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466 |
- <?php
- namespace App\Servers\System;
- use AlibabaCloud\Client\AlibabaCloud;
- use AlibabaCloud\Client\Exception\ClientException;
- use AlibabaCloud\Client\Exception\ServerException;
- use App\Models\Config;
- use App\Models\Region;
- use Carbon\Carbon;
- use Illuminate\Support\Facades\Storage;
- use QCloud\COSSTS\Sts;
- /**
- * Redis数据缓存类
- */
- class CommonServer
- {
- /**
- * 错误信息
- * @var string
- */
- private $errorMsg = '';
- static private $server = null;
- private function __construct()
- {
- }
- /**
- * 创建对象
- * @return CommonServer
- */
- static function creatServer()
- {
- if (empty(self::$server)) self::$server = new CommonServer();
- return self::$server;
- }
- /**
- * 验证手机号码格式
- * @param $phone
- * @return bool
- */
- public function verifyPhoneNumber($phone)
- {
- if (empty($phone)) return false;
- if (!preg_match('#^[\d]{11,11}$#', $phone)) {
- return false;
- }
- return true;
- }
- /**
- * 字符串去标签过滤及空格过滤
- * @param $str_name
- * @param $default
- * @return string
- */
- function filtrationStr($str_name, $default = '')
- {
- $str = request()->input($str_name, $default);
- if (empty($str)) return $str;
- if (!is_string($str)) {
- $str = json_encode($str);
- $str = strip_tags($str);
- $str = trim($str);
- $str = json_decode($str, true);
- } else {
- $str = strip_tags($str);
- $str = trim($str);
- }
- return $str;
- }
- /**
- * 获取城市名称
- * @param string $province_id
- * @param string $city_id
- * @param string $area_id
- * @return string
- */
- function getCityName($province_id = '', $city_id = '', $area_id = '')
- {
- $ids = [$province_id, $city_id, $area_id];
- $ids = array_filter($ids);
- if (empty($ids)) return '';
- $city_name = Region::whereIn('id', $ids)->orderBy('id', 'asc')->pluck('name')->toArray();
- $city_name = implode(' ', $city_name);
- return $city_name;
- }
- /**
- * 字符串屏蔽
- * @param $str
- * @param int $start_key 开始位置
- * @param int $end_key 尾数开始位置
- * @param int $start_num 截取位数
- * @param int $end_num 倒数截取位数
- * @param int $conceal_num 最大填充数量
- * @return string
- */
- function concealStr($str, $start_key = 0, $end_key = 1, $start_num = 1, $end_num = 1, $conceal_num = 3)
- {
- $str_len = mb_strlen($str);
- $start_str = '';
- $end_str = '';
- if (($str_len - $start_num - $end_num) < $conceal_num) {
- $conceal_num = $str_len - $start_num - $end_num;
- }
- $conceal_str = $this->getRandChar($conceal_num, '*');
- if (empty($conceal_str)) $conceal_str = '*';
- if ($str_len >= $start_key) {
- $start_str = mb_substr($str, $start_key, $start_num);
- }
- if ($str_len > $end_key) {
- $end_str = mb_substr($str, $end_key * -1, $end_num);
- }
- return $start_str . $conceal_str . $end_str;
- }
- /**
- * 获取随机字符串
- * @param int $length
- * @param string $strPol
- * @return string|null
- */
- public function getRandChar($length = 6, $strPol = '')
- {
- if ($length <= 0) $length = 1;
- $str = null;
- if (empty($strPol)) $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
- $max = strlen($strPol) - 1;
- for ($i = 0; $i < $length; $i++) {
- $str .= $strPol[rand(0, $max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
- }
- return $str;
- }
- /**
- * 获取数据库配置信息
- * @param $key
- * @return mixed
- */
- function getConfigValue($key)
- {
- return Config::where('key', $key)->value('value');
- }
- /**
- * 创建文件夹
- * @param $dir
- * @return bool
- */
- function creatDir($dir)
- {
- if ($dir == '') return false;
- if (!file_exists(public_path($dir))) {
- mkdir(public_path($dir), 0777, true);
- chmod(public_path($dir), 0777);
- }
- return true;
- }
- /**
- * 验证是否微信浏览器
- * @return bool
- */
- function isWeixin()
- {
- $http_user_agent = request()->header('user-agent');
- if (strpos($http_user_agent, 'MicroMessenger') !== false) {
- return true;
- }
- return false;
- }
- /**
- * 格式化小数位数
- * @param $num
- * @param int $digit
- * @return string
- */
- function setFloatNum($num, $digit = 4)
- {
- return sprintf("%.{$digit}f", $num);
- }
- /**
- * 获取真实IP
- * @return mixed
- */
- function getClientIp()
- {
- $http_x_forwarded_for = request()->header('x-forwarded-for');
- if (empty($http_x_forwarded_for)) {
- return request()->getClientIp();
- } else {
- $http_x_forwarded_for = explode(',', $http_x_forwarded_for);
- return $http_x_forwarded_for[0];
- }
- }
- function delDir($dir)
- {
- //先删除目录下的文件:
- $dh = opendir($dir);
- while ($file = readdir($dh)) {
- if ($file != "." && $file != "..") {
- $fullpath = $dir . "/" . $file;
- if (!is_dir($fullpath)) {
- unlink($fullpath);
- } else {
- $this->deldir($fullpath);
- }
- }
- }
- closedir($dh);
- //删除当前文件夹:
- if (rmdir($dir)) {
- return true;
- } else {
- return false;
- }
- }
- /**
- * 图片base64
- * @param $image_file
- * @return string
- */
- function base64EncodeImage($image_file)
- {
- $image_info = getimagesize($image_file);
- $image_data = fread(fopen($image_file, 'r'), filesize($image_file));
- $base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data));
- return $base64_image;
- }
- /**
- * 获取文件名
- * @param $url
- * @return string
- */
- function getFileName($url)
- {
- $name = basename($url);
- return empty($name) ? '' : $name;
- }
- /**
- * @param $url
- * @param string $type 请求方式
- * @param string $data 数据 数组格式
- * @param $head
- * @param $retType
- * @return mixed
- */
- function sendRequest($url, $data = '', $type = 'get',$head=[],$retType='json')
- {
- $ch = curl_init();
- if ($type == 'get' && $data) {
- $url = $url . '?' . http_build_query($data);
- }
- // dump(date('Y-m-d H:i:s'));
- // dump($url);
- curl_setopt($ch, CURLOPT_URL, $url); //设置访问路径
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); //设置可以返回字符串
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
- if(empty($head)){
- $head = [
- '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',
- 'Content-Type: application/json'
- ];
- }
- // curl_setopt($ch, CURLINFO_HEADER_OUT, true);
- curl_setopt($ch, CURLOPT_HTTPHEADER, $head);
- if ($type == 'post') {
- curl_setopt($ch, CURLOPT_POST, TRUE);//post请求
- $data = json_encode($data, JSON_UNESCAPED_UNICODE);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//设置传递的参数
- }
- $request = curl_exec($ch);
- // $header_size = curl_getinfo($ch,);
- // dump($request);
- if($request){
- if($retType=='gzip'){
- $request=gzdecode($request);
- }
- $request=json_decode($request,true);
- }
- // dump($request);
- // dump(date('Y-m-d H:i:s'));
- curl_close($ch);
- return $request;
- }
- function lockCapitalRoutes($mId,$routeName,$type){
- $routeArr= [
- 'withdraw.add',//提现
- ];
- if(in_array($routeName,$routeArr)){
- $redisName=$mId.'lockCapital';
- if($type){
- $row= RedisDataServer::creatServer()->getData($redisName);
- $isOutput= RedisDataServer::creatServer()->getData('dateOutput');
- if($row || $isOutput){
- return false;
- }
- RedisDataServer::creatServer()->setData($redisName,time(),'str',3,false);
- }else{
- RedisDataServer::creatServer()->delData($redisName);
- }
- }
- return true;
- }
- function getTxySts()
- {
- $data = RedisDataServer::creatServer()->getData('txy_sts_data');
- if ($data) {
- $data = json_decode($data, true);
- } else {
- $sts = new Sts();
- $accessKeyId = env('TXY_OSS_ACCESS_ID');
- $accessSecret = env('TXY_OSS_ACCESS_KEY');
- $config = array(
- 'url' => 'https://sts.tencentcloudapi.com/', // url和domain保持一致
- 'domain' => 'sts.tencentcloudapi.com', // 域名,非必须,默认为 sts.tencentcloudapi.com
- 'proxy' => '',
- 'secretId' => $accessKeyId, // 固定密钥,若为明文密钥,请直接以'xxx'形式填入,不要填写到getenv()函数中
- 'secretKey' => $accessSecret, // 固定密钥,若为明文密钥,请直接以'xxx'形式填入,不要填写到getenv()函数中
- 'bucket' => env('COSV5_BUCKET'), // 换成你的 bucket
- 'region' => env('COSV5_REGION'), // 换成 bucket 所在园区
- 'durationSeconds' => 1800, // 密钥有效期
- 'allowPrefix' => ['/'], // 这里改成允许的路径前缀,可以根据自己网站的用户登录态判断允许上传的具体路径,例子: a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
- // 密钥的权限列表。简单上传和分片需要以下的权限,其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
- 'allowActions' => array(
- // 简单上传
- 'name/cos:PutObject',
- 'name/cos:PostObject',
- // 分片上传
- 'name/cos:InitiateMultipartUpload',
- 'name/cos:ListMultipartUploads',
- 'name/cos:ListParts',
- 'name/cos:UploadPart',
- 'name/cos:CompleteMultipartUpload'
- )
- );
- try {
- $result = $sts->getTempKeys($config);
- if (empty($result['credentials'])) {
- return ['code' => 0, 'msg' => '权限生成失败'];
- }
- $data = $result['credentials'];
- $data['StartTime'] = time();
- $data['ExpiredTime'] = time() + 1700;
- RedisDataServer::creatServer()->setData('txy_sts_data', $data, 'json', 800);
- } catch (\Exception $e) {
- return ['code' => 0, 'msg' => $e->getMessage()];
- }
- }
- return ['code' => 1, 'msg' => '获取信息成功', 'data' => $data];
- }
- /**
- * 微信签名
- */
- function wxSign($data, $keys)
- {
- ksort($data);
- $str = '';
- foreach ($data as $key => $val) {
- if ($val) {
- if ($str != '') $str .= '&';
- $str .= "{$key}={$val}";
- }
- }
- $str .= '&key=' . $keys;
- $sign = strtoupper(MD5($str));
- return $sign;
- }
- /**
- * 获取阿里云sts临时权限
- */
- function getAliSts()
- {
- $data = RedisDataServer::creatServer()->getData('sts_data');
- if ($data) {
- $data = json_decode($data, true);
- } else {
- $accessKeyId = env('ALI_OSS_ACCESS_ID');
- $accessSecret = env('ALI_OSS_ACCESS_KEY');
- AlibabaCloud::accessKeyClient($accessKeyId, $accessSecret)->regionId('cn-hangzhou')->asDefaultClient();
- //设置参数,发起请求。
- try {
- $result = AlibabaCloud::rpc()
- ->product('Sts')
- ->scheme('https') // https | http
- ->version('2015-04-01')
- ->action('AssumeRole')
- ->method('POST')
- ->host('sts.aliyuncs.com')
- ->options([
- 'query' => [
- 'RegionId' => "cn-chengdu",
- 'RoleArn' => "acs:ram::1470797691368660:role/oss-js",
- 'RoleSessionName' => "js-oss-serve",
- 'DurationSeconds' => 900,
- ],
- ])
- ->request();
- $result = $result->toArray();
- if (empty($result['Credentials'])) {
- return ['code' => 0, 'msg' => '获取token信息失败'];
- }
- $data = $result['Credentials'];
- unset($data['Expiration']);
- RedisDataServer::creatServer()->setData('sts_data', $data, 'json', 800);
- } catch (ClientException $e) {
- return ['code' => 0, 'msg' => $e->getErrorMessage()];
- } catch (ServerException $e) {
- return ['code' => 0, 'msg' => $e->getErrorMessage()];
- }
- }
- return ['code' => 1, 'msg' => '获取信息成功', 'data' => $data];
- }
- }
|