sifangpay/app/Http/Helpers.php

864 lines
23 KiB
PHP

<?php
/**
* 后台引入样式路径,4个_
* @param $filename
*/
function is_mobile_client()
{
// 如果有HTTP_X_WAP_PROFILE则一定是移动设备
if (isset ($_SERVER['HTTP_X_WAP_PROFILE'])) {
return true;
}
// 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
if (isset ($_SERVER['HTTP_VIA'])) {
// 找不到为flase,否则为true
return true;
}
// 判断手机发送的客户端标志,兼容性有待提高,把常见的类型放到前面
if (isset ($_SERVER['HTTP_USER_AGENT'])) {
$clientkeywords = [
'android',
'iphone',
'samsung',
'ucweb',
'wap',
'mobile',
'nokia',
'sony',
'ericsson',
'mot',
'htc',
'sgh',
'lg',
'sharp',
'sie-',
'philips',
'panasonic',
'alcatel',
'lenovo',
'ipod',
'blackberry',
'meizu',
'netfront',
'symbian',
'windowsce',
'palm',
'operamini',
'operamobi',
'openwave',
'nexusone',
'cldc',
'midp'
];
// 从HTTP_USER_AGENT中查找手机浏览器的关键字
if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
return true;
}
}
// 协议法,因为有可能不准确,放到最后判断
if (isset ($_SERVER['HTTP_ACCEPT'])) {
// 如果只支持wml并且不支持html那一定是移动设备
// 如果支持wml和html但是wml在html之前则是移动设备
if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
return true;
}
}
return false;
}
function ____($file = '', $default = 'layuiadmin')
{
$path = '/style/admin/' . $default . '/' . $file;
return asset($path);
}
/**
* 图片地址设置,
* @param $str
* @param array $option 控制图片的大小一写配置
* @return mixed
*/
function picurl($str, $option = [])
{
if (count($option) <= 0) return $str;
return $str;
}
function parse_css($urls)
{
$path = str_replace('\\', '/', public_path());
$css_url = $path . $urls . '.css';
$app_css_url = $path . '/style/admin/style/app.css';
if (!file_exists($app_css_url)) {
if (!file_exists(dirname($app_css_url)))
mkdir(dirname($app_css_url), 0777);
$css_content = '';
foreach ($urls as $url) {
$css_content .= file_get_contents($url);
}
$css_content = str_replace("\r\n", '', $css_content); //清除换行符
$css_content = str_replace("\n", '', $css_content); //清除换行符
$css_content = str_replace("\t", '', $css_content); //清除制表符
$css_content = str_replace("../images/", "./../common/images/", $css_content);
@file_put_contents($css_url, $css_content);
}
$css_url = str_replace(FCPATH, '', $css_url);
return $css_url;
}
/**
* 链接设置,可以是控制器,也可以路径
* @param $path
* @param $method
* @param $option
*/
function admin_url($path, $method = 'index', $option = [])
{
//$url=strtolower($path).'/'.strtolower($method).'/?'.http_build_query($option);
$controller = 'Admin\\' . ucwords($path) . 'Controller@' . lcfirst(ucwords($method));
try {
$url = action($controller, $option);
} catch (Exception $e) {
return '<br/>提示:' . $controller . ' 这个路由没用定义<br/>';
}
return $url;
}
/**
* 链接设置,可以是控制器,也可以路径
* @param $path
* @param $method
* @param $option
*/
function admin_merchant_url($path, $method = 'index', $option = [])
{
//$url=strtolower($path).'/'.strtolower($method).'/?'.http_build_query($option);
$controller = 'Merchant\\' . ucwords($path) . 'Controller@' . lcfirst(ucwords($method));
try {
$url = action($controller, $option);
} catch (Exception $e) {
return '<br/>提示:' . $controller . ' 这个路由没用定义<br/>';
}
return $url;
}
function admin($field = '')
{
$info = \Illuminate\Support\Facades\Auth::guard('admin')->user();
return $field ? $info[$field] : $info;
}
function merchant($field = '')
{
$info = \Illuminate\Support\Facades\Auth::guard('merchant')->user();
return $field ? $info[$field] : $info;
}
function user($field = '')
{
$info = \Illuminate\Support\Facades\Auth::guard('web')->user();
return $field ? $info[$field] : $info;
}
function to_linux_path($str)
{
return str_replace("\\", '/', $str);
}
function config_cache_default($key, $default = '')
{
$str = config_cache($key);
if (!$str) {
$str = $default ?? '';
}
return $str;
}
/**
* 配置缓存,永久,不更新则永久
* @param $config_key
* @param array $data
* @return \Illuminate\Cache\CacheManager|mixed|string
* @throws Exception
*/
function config_cache($config_key, $data = [])
{
$param = explode('.', $config_key);
//\Illuminate\Support\Facades\Cache::forget($param[0]);
if (empty($data)) {
$config = cache($param[0]);
$config = unserialize($config);
if (empty($config)) {
//缓存文件不存在就读取数据库
$res = \App\Models\Config::get()->toArray();
if ($res) {
foreach ($res as $k => $val) {
$config[$val['ename']] = $val['content'];
}
//存入缓存
\Illuminate\Support\Facades\Cache::forever($param[0], serialize($config));
}
}
if (count($param) > 1) {
if (array_key_exists($param[1], $config)) {
return $config[$param[1]];
}
return false;
} else {
return $config;
}
} else {
//更新缓存
$result = \App\Models\Config::get()->toArray();
if (count($result) > 0) {
foreach ($result as $val) {
$temp[$val['ename']] = $val['content'];
}
foreach ($data as $k => $v) {
$newArr = ['ename' => $k, 'content' => trim($v)];
if (!isset($temp[$k])) {
\App\Models\Config::create($newArr);//新key数据插入数据库
} else {
if ($v != $temp[$k])
\App\Models\Config::where("ename", $k)->update($newArr);//缓存key存在且值有变更新此项
}
}
//更新后的数据库记录
$newRes = \App\Models\Config::get()->toArray();
foreach ($newRes as $rs) {
$newData[$rs['ename']] = $rs['content'];
}
} else {
foreach ($data as $k => $v) {
$newArr[] = ['ename' => $k, 'content' => trim($v)];
}
\App\Models\Config::insert($newArr);
$newData = $data;
}
$newData = serialize($newData);
\Illuminate\Support\Facades\Cache::forever($param[0], $newData);
}
}
/**
* 显示css
* @param $where
* @return string
*/
function show($where)
{
if ($where) {
return "display:block;";
} else {
return 'display:none;';
}
}
/**
* 隐藏css
* @param $where
* @return string
*/
function hide($where)
{
if ($where) {
return "display:none;";
} else {
return 'display:show;';
}
}
/**
* 表单状态
* @param $str
* @param $value
* @param string $type
* @return string
*/
function status_form($str, $value, $type = 'checked')
{
if ($str == $value) {
return $type;
}
}
/**
* 数组转键值
* @param $data
* @param $key
* @return array
*/
function data_to_key($data, $key)
{
if (count($data) <= 0) return [];
$narr = [];
foreach ($data as $k => $v) {
$narr[$v[$key]] = $v;
}
return $narr;
}
function make_card($num, $id, $start = 1, $config = [])
{
$ym = date('Ymd');
if ($num == 0) return;
$num = $num + $start; //卡的张数,即记录数
$row = [];
for ($i = $start; $i < $num; $i++) {
$seek = mt_rand(0, 9999) . mt_rand(0, 9999) . mt_rand(0, 9999); //12位
$start = mt_rand(0, 20);
$str = strtoupper(substr(md5($seek), $start, 12));
$str = str_replace("O", chr(mt_rand(65, 78)), $str);
$str = str_replace("0", chr(mt_rand(65, 78)), $str);
$row[] = [
'number' => $str,
'active_id' => $id,
'user_id' => 0,
'created_at' => date('Y-m-d H:i:s'),
'create_user_type' => $config['create_user_type'],
'create_user_id' => $config['create_user_id']
];
}
return $row;
}
function number_chunk($number, $size)
{
$data = [];
if ($number < $size) {
$data = [
'time' => 0,
'number' => $number,
'ys' => 0
];
} else {
$time = floor($number / $size);
$yushu = $number % $size;
$data = [
'time' => $time,
'number' => $size,
'ys' => $yushu
];
}
return $data;
}
/**
* 发送短信验证码
* @param $mobiles 手机
* @param string $tpl_id 短信模板id
* @param array $params 短信参数
* @param string $sms_sign 前面
* @return array|\Illuminate\Http\JsonResponse|string
* @throws Exception
*/
function send_sms($mobiles, $tpl_id = '', $params = [], $return = 0, $sms_sign = '婚礼之恋')
{
//测试期间关闭发送
// return '发送成功';
$appid = config_cache('config.sms_appid');
$appkey = config_cache('config.sms_appkey');
//根据手机多少,判断时群发还是单挑
if (is_string($mobiles)) {
$ssender = new \Qcloud\Sms\SmsSingleSender($appid, $appkey);
$result = $ssender->sendWithParam("86", $mobiles, $tpl_id,
$params, $sms_sign, "", ""); // 签名参数未提供或者为空时,会使用默认签名发送短信
$rsp = json_decode($result, true);
}
if (is_array($mobiles)) {
$msender = new \Qcloud\Sms\SmsMultiSender($appid, $appkey);
$result = $msender->sendWithParam("86", $mobiles, $tpl_id, $params, $sms_sign, "", ""); // 签名参数未提供或者为空时,会使用默认签名发送短信
$rsp = json_decode($result, true);
}
\Illuminate\Support\Facades\Log::info($result);
if ($rsp['result'] == 0) {
if ($return) {
return ['error' => 0, 'msg' => '发送成功'];
}
if (request()->ajax() || request()->wantsJson()) {
return response()->json(['error' => 0, 'msg' => '发送成功']);
}
//return '发送成功';
} else {
if ($return) {
return ['error' => 1, 'msg' => '发送失败'];
}
if (request()->ajax() || request()->wantsJson()) {
return response()->json(['error' => 1, 'msg' => '发送失败']);
}
//return '发送失败';
}
}
function get_arr_index($arr, $index = 'first')
{
$arr = array_flip($arr);
if ($index == 'first') {
return current($arr);
}
if ($index == 'last') {
return end($arr);
}
}
function in_arr_value($key, $arr, $default = '', $type = 'text')
{
if (array_key_exists($key, $arr)) {
switch ($type) {
case 'text':
return $arr[$key];
break;
case 'radio':
if ($default == $arr[$key]) {
return 'checked';
}
break;
case 'select':
if ($default == $arr[$key]) {
return 'selected';
}
break;
case 'checkbox':
$arr_c = json_decode($arr[$key], true);
if (in_array($default, $arr_c)) {
return 'checked';
}
break;
case 'more_upload':
$arr_c = json_decode(urldecode($arr[$key]), true);
$arr_c = $arr_c ? $arr_c : [];
return $arr_c;
break;
}
} else {
if (in_array($type, ['more_upload'])) {
return [];
}
return $default;
}
}
function thumbs($str, $type = 1, $class_name = '')
{
if (!$str) return false;
$thumb_arr = json_decode($str, true);
if (count($thumb_arr) <= 0) return false;
$html_str = '';
foreach ($thumb_arr as $v) {
if ($type == 1) {
$html_str .= '<div class="layui-upload-img item layui-inline " data-type="' . $v['type'] . '" data-tmpname="' . $v['tmpname'] . '" data-size="' . $v['size'] . '" data-path="' . $v['path'] . '">
<img src="' . $v['path'] . '" class="" title="" layadmin-event="viewpic" alt="">
<p class="layui-"></p>
<a href="javascript:" class="upload-close layui-icon layui-icon-close " data-obj=".insert_upload_more .layui-upload-list .item"
data-input_obj="' . $class_name . ' .upload_input"></a> </div>';
}
}
return $html_str;
}
function api_thumbs($str, $path)
{
if (!$str) return false;
$thumb_arr = json_decode($str, true);
if (count($thumb_arr) <= 0) return false;
$arr = [];
foreach ($thumb_arr as $v) {
$v['path'] = $path . $v['path'];
$arr[] = $v;
}
return $arr;
}
//签名验证
function check_sign($data)
{
$str = $data->input('str', '');
$time = $data->input('time', '');
$appkey = 'xcxhllove';
$signature = $data->input('signature', '');
//排序,然后连接成字符串
$arr = [
'str' => $str,
'time' => $time,
'appkey' => $appkey
];
ksort($arr);
$strkey = http_build_query($arr, '&');
$app_signature = md5('abc123321' . $strkey);
if ($app_signature != $signature) {
return false;
} else {
return true;
}
}
function api_res()
{
return config('host.res_api_host');
}
function only_day($end_at)
{
$now = time();
$end_at = strtotime($end_at);
$diff = $end_at - $now;
if ($diff <= 0) {
return false;
} else {
// $day = floor($diff/(3600*24));
$day = ceil($diff / 86400);
return $day;
}
}
function download($url, $filename, $path = '')
{
$filename = $filename . '.jpg';
$path = $path ? $path : '/upload/user/' . $filename;
$path = to_linux_path(public_path()) . $path;
if (!is_dir(dirname($path))) {
mkdir(dirname($path), 0755);
}
$response = \Ixudra\Curl\Facades\Curl::to($url)
->withContentType('image/jpg')
->download($path);
}
/**
* 返回成功请求
*
* @param string $data
* @param string $msg
* @param string $header
* @param string $value
* @return mixed
*/
function responseSuccess($data = '', $msg = '成功', $url = '', $header = 'Content-Type', $value = 'application/json')
{
$msg = is_array($msg) ? json_encode($msg) : json_encode([$msg ?: trans('response.success')]);
$res['status'] = ['errorCode' => 0, 'msg' => trans($msg) ? trans($msg) : $msg];
$res['data'] = $data;
$res['url'] = $url;
return response($content = $res, $status = 200)->header($header, $value);
}
/**
* 返回错误的请求
*
* @param string $msg
* @param int $code
* @param string $data
* @param string $header
* @param string $value
* @return mixed
*/
function json_wrong($msg = '失败')
{
$msg = is_array($msg) ? json_encode($msg) : json_encode([$msg ?: trans('response.fail')]);
$res['error_data'] = $msg;
$res['msg'] = '请求失败';
$res['error'] = 1;
return response()->json($res);
}
function order_sn()
{
return date('YmdHis') . mt_rand(100000, 999999);
}
function format_date($str, $format = "Y-m-d")
{
$datetime = strtotime($str);
return date($format, $datetime);
}
function get_month($date = '', $time = 1, $field = '')
{
if (!$date) {
$date = date('Y-m-d', time());
}
$firstday = date('Y-m-01', strtotime($date));
$lastday = date('Y-m-d', strtotime($firstday . " +1 month -1 day"));
if ($time) {
$firstday = $firstday . " 00:00:00";
$lastday = $lastday . " 23:59:59";
}
$arr = [$firstday, $lastday];
if ($field) {
return $arr[$field];
}
return $arr;
}
function get_year($date = '')
{
if (!$date) {
$date = date('Y-m-d', time());
}
$firstday = date('Y-01-01', strtotime($date));
$lastday = date('Y-12-d', strtotime("$firstday +1 year -1 day"));
return [$firstday, $lastday];
}
//支付签名方式
function pay_sign($uid, $price, $paytype, $notify_url, $return_url, $user_order_no, $token)
{
$sign = md5($uid . $price . $paytype . $notify_url . $return_url . $user_order_no . $token);
return $sign;
}
function money_str($number, $decimals = 2, $dec = ".", $sep = ",")
{
if (is_array($number)) {
$arr = [];
foreach ($number as $k => $v) {
$arr[] = number_format($v, $decimals, $dec, $sep);
}
return $arr;
}
return number_format($number, $decimals, $dec, $sep);
}
//通道写入文件
function write_gateway()
{
$config = \App\Models\Gateway::where('is_checked', 1)->get()->toArray();
$arr = [];
if (count($config) > 0) {
foreach ($config as $k => $v) {
$client = $v['client_type'];
if ($client == 'webm') {
$arr[$v['ename']]['web'][] = $v;
$arr[$v['ename']]['wap'][] = $v;
} else {
$arr[$v['ename']][$client][] = $v;
}
}
if(config_cache_default('config.ma_to_share',0))
{
if (isset($arr['tr_wxal'])) {
foreach ($arr['tr_wxal'] as $k => $v) {
if (isset($arr['tr_alipay'][$k])) {
$arr['tr_alipay'][$k] = array_merge($arr['tr_alipay'][$k], $v);
}else
{
$arr['tr_alipay'][$k] = $v;
}
if (isset($arr['tr_weixin'][$k])) {
$arr['tr_weixin'][$k] = array_merge($arr['tr_weixin'][$k], $v);
}else
{
$arr['tr_weixin'][$k] = $v;
}
}
}
if (isset($arr['tr_wxalbank'])) {
foreach ($arr['tr_wxalbank'] as $k => $v) {
if (isset($arr['tr_alipay'][$k])) {
$arr['tr_alipay'][$k] = array_merge($arr['tr_alipay'][$k], $v);
}else
{
$arr['tr_alipay'][$k] = $v;
}
if (isset($arr['tr_weixin'][$k])) {
$arr['tr_weixin'][$k] = array_merge($arr['tr_weixin'][$k], $v);
}else
{
$arr['tr_weixin'][$k] = $v;
}
if (isset($arr['tr_bank'][$k])) {
$arr['tr_bank'][$k] = array_merge($arr['tr_bank'][$k], $v);
}else
{
$arr['tr_bank'][$k] = $v;
}
}
}
}
}
$config2 = \App\Models\Gateway::get()->toArray();
$config2 = data_to_key($config2, 'id');
$data['config'] = $config2;
$data = $data + $arr;
$file = to_linux_path(config_path()) . '/gateway.php';
$content = "<?php\n return " . var_export($data, true) . "\n?>";
file_put_contents($file, $content);
}
//商户写入文件
function write_merchant()
{
$config = \App\Models\Merchant::where('check_status', 1)->select(['id', 'name', 'app_key', 'host', 'token', 'next_ratio', 'min_money', 'ratio', 'from_id', 'is_proxy', 'is_checked', 'email', 'gateways_id', 'min_price', 'max_price'])->get();
$arr = [];
$arr2 = [];
if (count($config) > 0) {
foreach ($config as $k => $v) {
$arr[$v->app_key] = serialize($v);
$arr2[$v->id] = serialize($v);
}
}
$file = to_linux_path(config_path()) . '/merchant.php';
$content = "<?php\n return " . var_export($arr, true) . "\n?>";
file_put_contents($file, $content);
// $file2=to_linux_path(config_path()).'/merchant_id.php';
/* $content2="<?php\n return ".var_export($arr2,true)."\n?>";*/
// file_put_contents($file2,$content2);
}
//商户费率写入文件
function write_merchant_ratio()
{
$config = \App\Models\MerchantRatio::with(['froms' => function ($query) {
$query->with('froms');
}])->where('is_self', 1)->groupBy('merchant_id')->get();
// dump($config->toArray());
$arr = [];
if (count($config) > 0) {
foreach ($config as $k => $v) {
$arr[$v->merchant_id] = [
'ratio' => $v->ratio,
'up_level' => $v->froms['level'] ? $v->froms['level'] : 0,//上级身份是股东还是代理
'up_level_name' => $v->froms['level'] ? config('adconfig.merchant_level')[$v->froms['level']] : '',
'up_id' => $v->parent_id,
'up_ratio' => $v->parent_id != 0 ? $v->froms['ratio'] : 0,//上级费率,
'top_id' => $v->froms['ratio'] ? $v->froms['parent_id'] : 0,//股东ID如果没有都是0
'top_ratio' => $v->froms['froms']['ratio'] ? $v->froms['froms']['ratio'] : 0//股东费率
];
}
}
$file2 = to_linux_path(config_path()) . '/merchant_ratio.php';
$content2 = "<?php \n return " . var_export($arr, true) . "\n?>";
file_put_contents($file2, $content2);
}
//组合url
function arr_to_url($url, $data)
{
//判断$url里面是否含有参数?
if (strpos($url, '?') != -1) {
return $url . '?' . http_build_query($data);
} else {
return $url . '&' . http_build_query($data);
}
}
//取得商户
function get_merchant($app_key)
{
if (!$app_key) return false;
$merchant = config('merchant.' . $app_key);
if ($merchant) {
return unserialize($merchant);
}
//查找数据库
$merchant = \App\Models\Merchant::where('app_key', $app_key)->first();
return $merchant ? $merchant : false;
}
//取得所有商户
function get_all_merchant()
{
//查找数据库
$merchant = \App\Models\Merchant::all();
return $merchant ? $merchant : false;
}
//字符串转换驼峰语法
function convert_under_line($str, $ucfirst = true)
{
while (($pos = strpos($str, '_')) !== false)
$str = substr($str, 0, $pos) . ucfirst(substr($str, $pos + 1));
return $ucfirst ? ucfirst($str) : $str;
}
/**
*返回字符串的毫秒数时间戳
*/
function get_total_millisecond()
{
$time = explode (" ", microtime () );
$time = $time [1] . ($time [0] * 1000);
$time2 = explode ( ".", $time );
$time = $time2 [0];
return $time;
}