格式化代码

This commit is contained in:
liaofei 2019-11-19 14:31:53 +08:00
parent 42f74a3c79
commit 84f81ab7e4
37 changed files with 1149 additions and 1084 deletions

View File

@ -15,8 +15,6 @@ use crmeb\services\MiniProgramService;
use crmeb\services\UtilService; use crmeb\services\UtilService;
use crmeb\services\WechatService; use crmeb\services\WechatService;
use crmeb\services\FormBuilder as Form; use crmeb\services\FormBuilder as Form;
use crmeb\services\HookService;
use crmeb\subscribes\OrderSubscribe;
use app\admin\model\order\StoreOrderStatus; use app\admin\model\order\StoreOrderStatus;
use app\admin\model\ump\StorePink; use app\admin\model\ump\StorePink;
use app\admin\model\user\User; use app\admin\model\user\User;

View File

@ -9,7 +9,6 @@ namespace app\admin\model\wechat;
use app\admin\model\system\SystemConfig; use app\admin\model\system\SystemConfig;
use crmeb\traits\ModelTrait; use crmeb\traits\ModelTrait;
use crmeb\basic\BaseModel; use crmeb\basic\BaseModel;
use crmeb\services\HookService;
use crmeb\services\UtilService; use crmeb\services\UtilService;
use crmeb\services\WechatService; use crmeb\services\WechatService;
use think\facade\Route as Url; use think\facade\Route as Url;

View File

@ -4,6 +4,7 @@
* User: xurongyao <763569752@qq.com> * User: xurongyao <763569752@qq.com>
* Date: 2019/11/13 4:52 PM * Date: 2019/11/13 4:52 PM
*/ */
namespace crmeb\repositories; namespace crmeb\repositories;
use app\models\user\WechatUser; use app\models\user\WechatUser;
@ -26,59 +27,60 @@ class NoticeRepositories
* @param $order * @param $order
* @param $formId * @param $formId
*/ */
public static function noticeOrderPaySuccess($order,$formId) public static function noticeOrderPaySuccess($order, $formId)
{ {
$wechatUser = WechatUser::where('uid',$order['uid'])->field('openid','routine_openid')->find(); $wechatUser = WechatUser::where('uid', $order['uid'])->field('openid', 'routine_openid')->find();
if($wechatUser){ if ($wechatUser) {
$openid = $wechatUser['openid']; $openid = $wechatUser['openid'];
$routineOpenid = $wechatUser['routine_openid']; $routineOpenid = $wechatUser['routine_openid'];
try{ try {
if($openid){//公众号发送模板消息 if ($openid) {//公众号发送模板消息
WechatTemplateService::sendTemplate($openid,WechatTemplateService::ORDER_PAY_SUCCESS, [ WechatTemplateService::sendTemplate($openid, WechatTemplateService::ORDER_PAY_SUCCESS, [
'first'=>'亲,您购买的商品已支付成功', 'first' => '亲,您购买的商品已支付成功',
'keyword1'=>$order['order_id'], 'keyword1' => $order['order_id'],
'keyword2'=>$order['pay_price'], 'keyword2' => $order['pay_price'],
'remark'=>'点击查看订单详情' 'remark' => '点击查看订单详情'
],Route::buildUrl('order/detail/'.$order['order_id'])->suffix('')->domain(true)->build()); ], Route::buildUrl('order/detail/' . $order['order_id'])->suffix('')->domain(true)->build());
//订单支付成功后给客服发送模版消息 //订单支付成功后给客服发送模版消息
WechatTemplateService::sendAdminNoticeTemplate([ WechatTemplateService::sendAdminNoticeTemplate([
'first'=>"亲,您有一个新订单 \n订单号:{$order['order_id']}", 'first' => "亲,您有一个新订单 \n订单号:{$order['order_id']}",
'keyword1'=>'新订单', 'keyword1' => '新订单',
'keyword2'=>'已支付', 'keyword2' => '已支付',
'keyword3'=>date('Y/m/d H:i',time()), 'keyword3' => date('Y/m/d H:i', time()),
'remark'=>'请及时处理' 'remark' => '请及时处理'
]); ]);
//订单支付成功后给客服发送客服消息 //订单支付成功后给客服发送客服消息
CustomerRepository::sendOrderPaySuccessCustomerService($order, 1); CustomerRepository::sendOrderPaySuccessCustomerService($order, 1);
}else if($routineOpenid){//小程序发送模板消息 } else if ($routineOpenid) {//小程序发送模板消息
RoutineTemplate::sendOrderSuccess($formId, $order['order_id']); RoutineTemplate::sendOrderSuccess($formId, $order['order_id']);
//订单支付成功后给客服发送客服消息 //订单支付成功后给客服发送客服消息
CustomerRepository::sendOrderPaySuccessCustomerService($order, 0); CustomerRepository::sendOrderPaySuccessCustomerService($order, 0);
} }
}catch (\Exception $e){} } catch (\Exception $e) {
}
} }
//打印小票 //打印小票
$switch = sysConfig('pay_success_printing_switch') ? true : false ; $switch = sysConfig('pay_success_printing_switch') ? true : false;
if($switch){ if ($switch) {
try{ try {
$order['cart_id'] = is_string($order['cart_id']) ? json_decode($order['cart_id'],true) : $order['cart_id']; $order['cart_id'] = is_string($order['cart_id']) ? json_decode($order['cart_id'], true) : $order['cart_id'];
$cartInfo = StoreOrderCartInfo::whereIn('cart_id',$order['cart_id'])->field('cart_info')->select(); $cartInfo = StoreOrderCartInfo::whereIn('cart_id', $order['cart_id'])->field('cart_info')->select();
$cartInfo = count($cartInfo) ? $cartInfo->toArray() : []; $cartInfo = count($cartInfo) ? $cartInfo->toArray() : [];
$product = []; $product = [];
foreach ($cartInfo as $item){ foreach ($cartInfo as $item) {
$value = is_string($item['cart_info']) ? json_decode($item['cart_info']) : $item['cart_info']; $value = is_string($item['cart_info']) ? json_decode($item['cart_info']) : $item['cart_info'];
$value['productInfo']['store_name'] = $value['productInfo']['store_name'] ?? ""; $value['productInfo']['store_name'] = $value['productInfo']['store_name'] ?? "";
$value['productInfo']['store_name'] = StoreOrderCartInfo::getSubstrUTf8($value['productInfo']['store_name'],10,'UTF-8',''); $value['productInfo']['store_name'] = StoreOrderCartInfo::getSubstrUTf8($value['productInfo']['store_name'], 10, 'UTF-8', '');
$product[] = $value; $product[] = $value;
} }
YLYService::getInstance()->setContent(sysConfig('site_name'),is_object($order) ? $order->toArray() : $order,$product)->orderPrinting(); YLYService::instance()->setContent(sysConfig('site_name'), is_object($order) ? $order->toArray() : $order, $product)->orderPrinting();
}catch (\Exception $e){ } catch (\Exception $e) {
Log::error('小票打印出现错误,错误原因:'.$e->getMessage()); Log::error('小票打印出现错误,错误原因:' . $e->getMessage());
} }
} }
//短信通知 下发用户支付成功 下发管理员支付通知 //短信通知 下发用户支付成功 下发管理员支付通知
event('ShortMssageSend',[$order['order_id'],['PaySuccess','AdminPaySuccess']]); event('ShortMssageSend', [$order['order_id'], ['PaySuccess', 'AdminPaySuccess']]);
} }
} }

View File

@ -8,7 +8,6 @@
namespace crmeb\services; namespace crmeb\services;
/** /**
* 错误码统一存放类 * 错误码统一存放类
* Class ApiErrorCode * Class ApiErrorCode
@ -17,10 +16,10 @@ namespace crmeb\services;
class ApiErrorCode class ApiErrorCode
{ {
const SUCCESS = [200,'SUCCESS']; const SUCCESS = [200, 'SUCCESS'];
const ERROR = [400,'操作失败']; const ERROR = [400, '操作失败'];
const ERR_LOGIN = [40010,'登陆过期']; const ERR_LOGIN = [40010, '登陆过期'];
} }

View File

@ -29,13 +29,13 @@ class CacheService
* @param int $expire 缓存时间为0读取系统缓存时间 * @param int $expire 缓存时间为0读取系统缓存时间
* @return bool * @return bool
*/ */
public static function set(string $name, $value, int $expire = 0):bool public static function set(string $name, $value, int $expire = 0): bool
{ {
//这里不要去读取缓存配置,会导致死循环 //这里不要去读取缓存配置,会导致死循环
$expire = $expire ? : SystemConfigService::get('cache_config',null,true); $expire = $expire ?: SystemConfigService::get('cache_config', null, true);
if(!is_int($expire)) if (!is_int($expire))
$expire = (int)$expire; $expire = (int)$expire;
return self::handler()->set($name,$value,$expire); return self::handler()->set($name, $value, $expire);
} }
/** /**
@ -44,9 +44,9 @@ class CacheService
* @param bool $default * @param bool $default
* @return mixed * @return mixed
*/ */
public static function get(string $name,$default = false) public static function get(string $name, $default = false)
{ {
return self::handler()->remember($name,$default); return self::handler()->remember($name, $default);
} }
/** /**
@ -56,7 +56,7 @@ class CacheService
*/ */
public static function rm(string $name) public static function rm(string $name)
{ {
return self::handler()->remember($name,''); return self::handler()->remember($name, '');
} }
/** /**

View File

@ -1,4 +1,5 @@
<?php <?php
namespace crmeb\services; namespace crmeb\services;
use app\models\store\StoreBargain; use app\models\store\StoreBargain;
@ -24,37 +25,37 @@ class CustomerService
* @param int $type 1 公众号 0 小程序 * @param int $type 1 公众号 0 小程序
* @return string * @return string
*/ */
public static function sendOrderPaySuccessCustomerService($order,$type = 0) public static function sendOrderPaySuccessCustomerService($order, $type = 0)
{ {
$serviceOrderNotice = StoreService::getStoreServiceOrderNotice(); $serviceOrderNotice = StoreService::getStoreServiceOrderNotice();
if(count($serviceOrderNotice)){ if (count($serviceOrderNotice)) {
foreach ($serviceOrderNotice as $key=>&$item){ foreach ($serviceOrderNotice as $key => &$item) {
$userInfo = WechatUser::get($item); $userInfo = WechatUser::get($item);
if($userInfo){ if ($userInfo) {
$userInfo = $userInfo->toArray(); $userInfo = $userInfo->toArray();
if($userInfo['subscribe'] && $userInfo['openid']){ if ($userInfo['subscribe'] && $userInfo['openid']) {
$orderStatus = StoreService::orderServiceStatus($userInfo['uid']); $orderStatus = StoreService::orderServiceStatus($userInfo['uid']);
if($orderStatus){ if ($orderStatus) {
// 统计管理开启 推送图文消息 // 统计管理开启 推送图文消息
$head = '订单提醒 订单号:'.$order['order_id']; $head = '订单提醒 订单号:' . $order['order_id'];
$url = SystemConfigService::get('site_url') . '/customer/orderdetail/'.$order['order_id']; $url = SystemConfigService::get('site_url') . '/customer/orderdetail/' . $order['order_id'];
$description = ''; $description = '';
$image = SystemConfigService::get('site_logo'); $image = SystemConfigService::get('site_logo');
if(isset($order['seckill_id']) && $order['seckill_id'] > 0){ if (isset($order['seckill_id']) && $order['seckill_id'] > 0) {
$description .= '秒杀产品:'.StoreSeckill::getProductField($order['seckill_id'], 'title'); $description .= '秒杀产品:' . StoreSeckill::getProductField($order['seckill_id'], 'title');
$image = StoreSeckill::getProductField($order['seckill_id'], 'image'); $image = StoreSeckill::getProductField($order['seckill_id'], 'image');
}else if(isset($order['combination_id']) && $order['combination_id'] > 0){ } else if (isset($order['combination_id']) && $order['combination_id'] > 0) {
$description .= '拼团产品:'.StoreCombination::getCombinationField($order['combination_id'], 'title'); $description .= '拼团产品:' . StoreCombination::getCombinationField($order['combination_id'], 'title');
$image = StoreCombination::getCombinationField($order['combination_id'], 'image'); $image = StoreCombination::getCombinationField($order['combination_id'], 'image');
}else if(isset($order['bargain_id']) && $order['bargain_id'] > 0){ } else if (isset($order['bargain_id']) && $order['bargain_id'] > 0) {
$description .= '砍价产品:'.StoreBargain::getBargainField($order['bargain_id'], 'title'); $description .= '砍价产品:' . StoreBargain::getBargainField($order['bargain_id'], 'title');
$image = StoreBargain::getBargainField($order['bargain_id'], 'image'); $image = StoreBargain::getBargainField($order['bargain_id'], 'image');
}else{ } else {
$productIds = StoreCart::getCartIdsProduct((array)$order['cart_id']); $productIds = StoreCart::getCartIdsProduct((array)$order['cart_id']);
$storeProduct = StoreProduct::getProductStoreNameOrImage($productIds); $storeProduct = StoreProduct::getProductStoreNameOrImage($productIds);
if(count($storeProduct)){ if (count($storeProduct)) {
foreach ($storeProduct as $value){ foreach ($storeProduct as $value) {
$description .= $value['store_name'].' '; $description .= $value['store_name'] . ' ';
$image = $value['image']; $image = $value['image'];
} }
} }
@ -65,10 +66,10 @@ class CustomerService
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error($userInfo['nickname'] . '发送失败' . $e->getMessage()); Log::error($userInfo['nickname'] . '发送失败' . $e->getMessage());
} }
}else{ } else {
// 推送文字消息 // 推送文字消息
$head = "客服提醒:亲,您有一个新订单 \r\n订单单号:{$order['order_id']}\r\n支付金额:¥{$order['pay_price']}\r\n备注信息:{$order['mark']}\r\n订单来源:小程序"; $head = "客服提醒:亲,您有一个新订单 \r\n订单单号:{$order['order_id']}\r\n支付金额:¥{$order['pay_price']}\r\n备注信息:{$order['mark']}\r\n订单来源:小程序";
if($type) $head = "客服提醒:亲,您有一个新订单 \r\n订单单号:{$order['order_id']}\r\n支付金额:¥{$order['pay_price']}\r\n备注信息:{$order['mark']}\r\n订单来源:公众号"; if ($type) $head = "客服提醒:亲,您有一个新订单 \r\n订单单号:{$order['order_id']}\r\n支付金额:¥{$order['pay_price']}\r\n备注信息:{$order['mark']}\r\n订单来源:公众号";
try { try {
WechatService::staffService()->message($head)->to($userInfo['openid'])->send(); WechatService::staffService()->message($head)->to($userInfo['openid'])->send();
} catch (\Exception $e) { } catch (\Exception $e) {

View File

@ -10,46 +10,47 @@ namespace crmeb\services;
class ExportService class ExportService
{ {
public static function exportCsv($list,$filename,$header = [],$br = '_'){ public static function exportCsv($list, $filename, $header = [], $br = '_')
$tableStr = count($header) > 0 ? '"'.implode('","',$header).'"'.PHP_EOL : ''; {
$tableStr .= self::tidyCsvStr($list,str_repeat($br,99)); $tableStr = count($header) > 0 ? '"' . implode('","', $header) . '"' . PHP_EOL : '';
$tableStr .= self::tidyCsvStr($list, str_repeat($br, 99));
ob_end_clean(); ob_end_clean();
ob_start(); ob_start();
header("Content-type:application/vnd.ms-excel"); header("Content-type:application/vnd.ms-excel");
header("Content-Disposition:filename=".$filename.".csv"); header("Content-Disposition:filename=" . $filename . ".csv");
header('Content-Type:application/download'); header('Content-Type:application/download');
exit(iconv('UTF-8',"GB2312//IGNORE",$tableStr)); exit(iconv('UTF-8', "GB2312//IGNORE", $tableStr));
} }
private static function tidyCsvStr($list,$br = '') private static function tidyCsvStr($list, $br = '')
{ {
$tableStr = ''; $tableStr = '';
foreach ($list as $row){ foreach ($list as $row) {
if(is_array($row)){ if (is_array($row)) {
$max = 1; $max = 1;
foreach ($row as $k=>$item){ foreach ($row as $k => $item) {
if(is_array($item)){ if (is_array($item)) {
if($max < ($l = count($item))) $max = $l; if ($max < ($l = count($item))) $max = $l;
} else } else
$row[$k] = [$item]; $row[$k] = [$item];
} }
for($i = 0; $i<=$max; $i++){ for ($i = 0; $i <= $max; $i++) {
$exportRow = []; $exportRow = [];
if($max == $i){ if ($max == $i) {
if($br == '') if ($br == '')
continue; continue;
else else
$exportRow = array_fill(0,count($row),$br); $exportRow = array_fill(0, count($row), $br);
}else{ } else {
foreach ($row as $item){ foreach ($row as $item) {
$exportRow[] = isset($item[$i]) && !empty($item[$i]) ? $item[$i] : ' '; $exportRow[] = isset($item[$i]) && !empty($item[$i]) ? $item[$i] : ' ';
} }
} }
$tableStr .= '"'.implode('","',$exportRow).'"," "'.PHP_EOL; $tableStr .= '"' . implode('","', $exportRow) . '"," "' . PHP_EOL;
} }
$tableStr = rtrim($tableStr,PHP_EOL); $tableStr = rtrim($tableStr, PHP_EOL);
}else{ } else {
$tableStr .= implode('',['"',$row,'"',',']); $tableStr .= implode('', ['"', $row, '"', ',']);
} }
$tableStr .= PHP_EOL; $tableStr .= PHP_EOL;
} }

View File

@ -506,6 +506,8 @@ class FileService
{ {
$handle = @opendir($dir);//打开指定目录 $handle = @opendir($dir);//打开指定目录
$directory_count = 0; $directory_count = 0;
$total_size = 0;
$file_cout = 0;
while (FALSE !== ($file_path = readdir($handle))) while (FALSE !== ($file_path = readdir($handle)))
{ {
if($file_path != "." && $file_path != "..") if($file_path != "." && $file_path != "..")

View File

@ -27,13 +27,14 @@ class FormBuilder extends Form
* str 自定义 * str 自定义
* @return $this * @return $this
*/ */
public static function make_post_form($title,array $field,$url,$jscallback = 2){ public static function make_post_form($title, array $field, $url, $jscallback = 2)
{
$form = Form::create($url);//提交地址 $form = Form::create($url);//提交地址
$form->setMethod('POST');//提交方式 $form->setMethod('POST');//提交方式
$form->components($field);//表单字段 $form->components($field);//表单字段
$form->setTitle($title);//表单标题 $form->setTitle($title);//表单标题
$js = '';//提交成功不执行任何动作 $js = '';//提交成功不执行任何动作
switch ($jscallback){ switch ($jscallback) {
case 1: case 1:
$js = 'parent.$(".J_iframe:visible")[0].contentWindow.location.reload();';//提交成功父级页面刷新 $js = 'parent.$(".J_iframe:visible")[0].contentWindow.location.reload();';//提交成功父级页面刷新
break; break;

View File

@ -21,12 +21,12 @@ class GroupDataService
* @param bool $isCaChe 是否读取缓存 * @param bool $isCaChe 是否读取缓存
* @return array * @return array
*/ */
public static function getGroupData(string $config_name, $limit = 0,bool $isCaChe = false):array public static function getGroupData(string $config_name, $limit = 0, bool $isCaChe = false): array
{ {
try{ try {
$cacheName = $limit ? "group_data_{$config_name}_{$limit}" : "data_{$config_name}"; $cacheName = $limit ? "group_data_{$config_name}_{$limit}" : "data_{$config_name}";
$callable = function () use ($config_name,$limit) { $callable = function () use ($config_name, $limit) {
$data = SystemGroupData::getGroupData($config_name, $limit); $data = SystemGroupData::getGroupData($config_name, $limit);
if (is_object($data)) if (is_object($data))
$data = $data->toArray(); $data = $data->toArray();
@ -36,9 +36,9 @@ class GroupDataService
if ($isCaChe) if ($isCaChe)
return $callable(); return $callable();
return CacheService::get($cacheName,$callable); return CacheService::get($cacheName, $callable);
}catch (\Throwable $e){ } catch (\Throwable $e) {
return []; return [];
} }
} }
@ -50,24 +50,24 @@ class GroupDataService
* @param bool $isCaChe 是否读取缓存 * @param bool $isCaChe 是否读取缓存
* @return array * @return array
*/ */
public static function getData(string $config_name,int $limit = 0,bool $isCaChe = false):array public static function getData(string $config_name, int $limit = 0, bool $isCaChe = false): array
{ {
try{ try {
$cacheName = $limit ? "data_{$config_name}_{$limit}" : "data_{$config_name}"; $cacheName = $limit ? "data_{$config_name}_{$limit}" : "data_{$config_name}";
$callable = function () use ($config_name,$limit) { $callable = function () use ($config_name, $limit) {
$data = SystemGroupData::getAllValue($config_name, $limit); $data = SystemGroupData::getAllValue($config_name, $limit);
if(is_object($data)) if (is_object($data))
$data = $data->toArray(); $data = $data->toArray();
return $data; return $data;
}; };
if($isCaChe) if ($isCaChe)
return $callable(); return $callable();
return CacheService::get($cacheName,$callable); return CacheService::get($cacheName, $callable);
}catch (\Throwable $e){ } catch (\Throwable $e) {
return []; return [];
} }
} }
@ -78,9 +78,9 @@ class GroupDataService
* @param bool $isCaChe 是否读取缓存 * @param bool $isCaChe 是否读取缓存
* @return array * @return array
*/ */
public static function getDataNumber(int $id,bool $isCaChe = false):array public static function getDataNumber(int $id, bool $isCaChe = false): array
{ {
try{ try {
$cacheName = "data_number_{$id}"; $cacheName = "data_number_{$id}";
$callable = function () use ($id) { $callable = function () use ($id) {
@ -90,12 +90,12 @@ class GroupDataService
return $data; return $data;
}; };
if($isCaChe) if ($isCaChe)
return $callable(); return $callable();
return CacheService::get($cacheName,$callable); return CacheService::get($cacheName, $callable);
}catch (\Throwable $e){ } catch (\Throwable $e) {
return []; return [];
} }
} }

View File

@ -4,6 +4,7 @@
* @author: xaboy<365615158@qq.com> * @author: xaboy<365615158@qq.com>
* @day: 2017/11/23 * @day: 2017/11/23
*/ */
namespace crmeb\services; namespace crmeb\services;
class HttpService class HttpService

View File

@ -13,57 +13,59 @@ class JsonService
private static $FAIL_DEFAULT_MSG = 'no'; private static $FAIL_DEFAULT_MSG = 'no';
public static function result($code,$msg='',$data=[],$count=0) public static function result($code, $msg = '', $data = [], $count = 0)
{ {
exit(json_encode(compact('code','msg','data','count'))); exit(json_encode(compact('code', 'msg', 'data', 'count')));
}
public static function successlayui($count=0,$data=[],$msg='')
{
if(is_array($count)){
if(isset($count['data'])) $data=$count['data'];
if(isset($count['count'])) $count=$count['count'];
}
if(false == is_string($msg)){
$data = $msg;
$msg = self::$SUCCESSFUL_DEFAULT_MSG;
}
return self::result(0,$msg,$data,$count);
}
public static function successful($msg = 'ok',$data=[],$status=200)
{
if(false == is_string($msg)){
$data = $msg;
$msg = self::$SUCCESSFUL_DEFAULT_MSG;
}
return self::result($status,$msg,$data);
} }
public static function status($status,$msg,$result = []) public static function successlayui($count = 0, $data = [], $msg = '')
{
if (is_array($count)) {
if (isset($count['data'])) $data = $count['data'];
if (isset($count['count'])) $count = $count['count'];
}
if (false == is_string($msg)) {
$data = $msg;
$msg = self::$SUCCESSFUL_DEFAULT_MSG;
}
return self::result(0, $msg, $data, $count);
}
public static function successful($msg = 'ok', $data = [], $status = 200)
{
if (false == is_string($msg)) {
$data = $msg;
$msg = self::$SUCCESSFUL_DEFAULT_MSG;
}
return self::result($status, $msg, $data);
}
public static function status($status, $msg, $result = [])
{ {
$status = strtoupper($status); $status = strtoupper($status);
if(true == is_array($msg)){ if (true == is_array($msg)) {
$result = $msg; $result = $msg;
$msg = self::$SUCCESSFUL_DEFAULT_MSG; $msg = self::$SUCCESSFUL_DEFAULT_MSG;
} }
return self::result(200,$msg,compact('status','result')); return self::result(200, $msg, compact('status', 'result'));
} }
public static function fail($msg,$data=[],$code=400) public static function fail($msg, $data = [], $code = 400)
{ {
if(true == is_array($msg)){ if (true == is_array($msg)) {
$data = $msg; $data = $msg;
$msg = self::$FAIL_DEFAULT_MSG; $msg = self::$FAIL_DEFAULT_MSG;
} }
return self::result($code,$msg,$data); return self::result($code, $msg, $data);
} }
public static function success($msg,$data=[]) public static function success($msg, $data = [])
{ {
if(true == is_array($msg)){ if (true == is_array($msg)) {
$data = $msg; $data = $msg;
$msg = self::$SUCCESSFUL_DEFAULT_MSG; $msg = self::$SUCCESSFUL_DEFAULT_MSG;
} }
return self::result(200,$msg,$data); return self::result(200, $msg, $data);
} }
/* /*
@ -73,9 +75,9 @@ class JsonService
* @param array $data 返回数据 * @param array $data 返回数据
* @return array * @return array
* */ * */
public static function returnData($code,$msg='',$data=[]) public static function returnData($code, $msg = '', $data = [])
{ {
return compact('code','msg','data'); return compact('code', 'msg', 'data');
} }
} }

View File

@ -11,7 +11,6 @@ use crmeb\repositories\PaymentRepositories;
use EasyWeChat\Foundation\Application; use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order; use EasyWeChat\Payment\Order;
use think\facade\Route as Url; use think\facade\Route as Url;
use crmeb\services\HookService;
use crmeb\interfaces\ProviderInterface; use crmeb\interfaces\ProviderInterface;
use app\models\store\StoreOrder as StoreOrderRoutineModel; use app\models\store\StoreOrder as StoreOrderRoutineModel;
use app\models\user\UserRecharge; use app\models\user\UserRecharge;
@ -324,7 +323,6 @@ class MiniProgramService implements ProviderInterface
$staff = self::staffService(); $staff = self::staffService();
$staff = is_callable($message) ? $staff->message($message()) : $staff->message($message); $staff = is_callable($message) ? $staff->message($message()) : $staff->message($message);
$res = $staff->to($to)->send(); $res = $staff->to($to)->send();
HookService::afterListen('wechat_staff_to',compact('to','message'),$res);
return $res; return $res;
} }

View File

@ -1,4 +1,5 @@
<?php <?php
namespace crmeb\services; namespace crmeb\services;
use crmeb\services\JsonService as Json; use crmeb\services\JsonService as Json;
@ -6,7 +7,7 @@ use crmeb\services\JsonService as Json;
class PHPExcelService class PHPExcelService
{ {
//PHPExcel实例化对象 //PHPExcel实例化对象
private static $PHPExcel=null; private static $PHPExcel = null;
//表头计数 //表头计数
protected static $count; protected static $count;
//表头占行数 //表头占行数
@ -14,19 +15,19 @@ class PHPExcelService
//表能占据表行的字母对应self::$cellkey //表能占据表行的字母对应self::$cellkey
protected static $cells; protected static $cells;
//表头数据 //表头数据
protected static $data=[]; protected static $data = [];
//文件名 //文件名
protected static $title='订单导出'; protected static $title = '订单导出';
//行宽 //行宽
protected static $where=20; protected static $where = 20;
//行高 //行高
protected static $height=50; protected static $height = 50;
//表行名 //表行名
private static $cellKey = array( private static $cellKey = array(
'A','B','C','D','E','F','G','H','I','J','K','L','M', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N','O','P','Q','R','S','T','U','V','W','X','Y','Z', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM',
'AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ' 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ'
); );
//设置style //设置style
private static $styleArray = array( private static $styleArray = array(
@ -43,36 +44,41 @@ class PHPExcelService
//'color' => array('argb' => 'FFFF0000'), //'color' => array('argb' => 'FFFF0000'),
), ),
), ),
'font'=>[ 'font' => [
'bold'=>true 'bold' => true
], ],
'alignment'=>[ 'alignment' => [
'horizontal'=>\PHPExcel_Style_Alignment::HORIZONTAL_CENTER, 'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
'vertical'=>\PHPExcel_Style_Alignment::VERTICAL_CENTER 'vertical' => \PHPExcel_Style_Alignment::VERTICAL_CENTER
] ]
); );
/** /**
*初始化PHPExcel类 *初始化PHPExcel类
*@param $data array() * @param $data array()
*@param $fun function() * @param $fun function()
* return * return
*/ */
private static function initialize($data,$fun){ private static function initialize($data, $fun)
self::$PHPExcel= new \PHPExcel(); {
if($fun!==null && is_callable($fun)){ self::$PHPExcel = new \PHPExcel();
self::$styleArray=$fun(); if ($fun !== null && is_callable($fun)) {
self::$styleArray = $fun();
} }
if(!is_array($data)) exit(Json::fail('data 为数组')); if (!is_array($data)) exit(Json::fail('data 为数组'));
self::$data=$data; self::$data = $data;
} }
/** /**
*设置字体格式 *设置字体格式
*@param $title string 必选 * @param $title string 必选
* return string * return string
*/ */
public static function setUtf8($title){ public static function setUtf8($title)
{
return iconv('utf-8', 'gb2312', $title); return iconv('utf-8', 'gb2312', $title);
} }
/** /**
* *
* execl数据导出 * execl数据导出
@ -81,48 +87,50 @@ class PHPExcelService
* *
* 特殊处理:合并单元格需要先对数据进行处理 * 特殊处理:合并单元格需要先对数据进行处理
*/ */
public function setExcelContent($list=null) public function setExcelContent($list = null)
{ {
$sheet=self::$PHPExcel->getActiveSheet(); $sheet = self::$PHPExcel->getActiveSheet();
foreach(self::$data as $key=>$val){ foreach (self::$data as $key => $val) {
$row=self::$cellKey[$key]; $row = self::$cellKey[$key];
$sheet->getColumnDimension($row)->setWidth(isset($val['w'])?$val['w']:self::$where); $sheet->getColumnDimension($row)->setWidth(isset($val['w']) ? $val['w'] : self::$where);
$sheet->setCellValue($row.self::$topNumber,isset($val['name'])?$val['name']:$val); $sheet->setCellValue($row . self::$topNumber, isset($val['name']) ? $val['name'] : $val);
} }
$cellkey=array_slice(self::$cellKey,0,self::$count); $cellkey = array_slice(self::$cellKey, 0, self::$count);
if($list!==null && is_array($list)){ if ($list !== null && is_array($list)) {
foreach ($cellkey as $k=>$v){ foreach ($cellkey as $k => $v) {
foreach ($list as $key=>$val){ foreach ($list as $key => $val) {
if(isset($val[$k]) && !is_array($val[$k])){ if (isset($val[$k]) && !is_array($val[$k])) {
$sheet->setCellValue($v.(self::$topNumber+1+$key),$val[$k]); $sheet->setCellValue($v . (self::$topNumber + 1 + $key), $val[$k]);
}else if(isset($val[$k]) && is_array($val[$k])){ } else if (isset($val[$k]) && is_array($val[$k])) {
$str=''; $str = '';
foreach ($val[$k] as $value){ foreach ($val[$k] as $value) {
$str.=$value.chr(10); $str .= $value . chr(10);
} }
$sheet->setCellValue($v.(self::$topNumber+1+$key),$str); $sheet->setCellValue($v . (self::$topNumber + 1 + $key), $str);
} }
} }
} }
$sheet->getDefaultRowDimension()->setRowHeight(self::$height); $sheet->getDefaultRowDimension()->setRowHeight(self::$height);
//设置边框 //设置边框
$sheet->getStyle('A1:'.self::$cells.(count($list)+self::$topNumber))->applyFromArray(self::$styleArray); $sheet->getStyle('A1:' . self::$cells . (count($list) + self::$topNumber))->applyFromArray(self::$styleArray);
//设置自动换行 //设置自动换行
$sheet->getStyle('A4:'.self::$cells.(count($list)+self::$topNumber))->getAlignment()->setWrapText(true); $sheet->getStyle('A4:' . self::$cells . (count($list) + self::$topNumber))->getAlignment()->setWrapText(true);
}else if($list!==null && is_callable($list)){ } else if ($list !== null && is_callable($list)) {
$list($sheet,self::$topNumber,$cellkey,self::$cells)->applyFromArray(self::$styleArray); $list($sheet, self::$topNumber, $cellkey, self::$cells)->applyFromArray(self::$styleArray);
} }
return $this; return $this;
} }
/** /**
* 保存表格数据,并下载 * 保存表格数据,并下载
* @param * @param
* @return * @return
*/ */
public function ExcelSave(){ public function ExcelSave()
$objWriter=\PHPExcel_IOFactory::createWriter(self::$PHPExcel,'Excel2007'); {
$filename=self::$title.'--'.time().'.xlsx'; $objWriter = \PHPExcel_IOFactory::createWriter(self::$PHPExcel, 'Excel2007');
$filename = self::$title . '--' . time() . '.xlsx';
ob_end_clean(); ob_end_clean();
header('Content-Type: application/vnd.ms-excel'); header('Content-Type: application/vnd.ms-excel');
header('Content-Type: application/octet-stream'); header('Content-Type: application/octet-stream');
@ -138,20 +146,21 @@ class PHPExcelService
* @param $fun function() 主要设置边框的粗细 * @param $fun function() 主要设置边框的粗细
* @return $this * @return $this
*/ */
public static function setExcelHeader($data,$fun=null) public static function setExcelHeader($data, $fun = null)
{ {
self::initialize($data,$fun); self::initialize($data, $fun);
if(self::$count=count(self::$data)){ if (self::$count = count(self::$data)) {
if(self::$count>count(self::$cellKey)){ if (self::$count > count(self::$cellKey)) {
return Json::fail('表头长度过长'); return Json::fail('表头长度过长');
} }
self::$cells=self::$cellKey[self::$count-1]; self::$cells = self::$cellKey[self::$count - 1];
}else{ } else {
return Json::fail('data 参数二不能为空'); return Json::fail('data 参数二不能为空');
} }
return new self; return new self;
} }
/** /**
* 设置标题 * 设置标题
* @param $title string || array ['title'=>'','name'=>'','info'=>[]] * @param $title string || array ['title'=>'','name'=>'','info'=>[]]
@ -160,20 +169,21 @@ class PHPExcelService
* @param $funName function($style,$A,$A2) 自定义设置头部样式 * @param $funName function($style,$A,$A2) 自定义设置头部样式
* @return $this * @return $this
*/ */
public function setExcelTile($title='',$Name='',$info=[],$funName=null){ public function setExcelTile($title = '', $Name = '', $info = [], $funName = null)
{
//设置参数 //设置参数
if(is_array($title)){ if (is_array($title)) {
if(isset($title['title'])) $title=$title['title']; if (isset($title['title'])) $title = $title['title'];
if(isset($title['name'])) $Name=$title['name']; if (isset($title['name'])) $Name = $title['name'];
if(isset($title['info'])) $info=$title['info']; if (isset($title['info'])) $info = $title['info'];
} }
if(empty($title)) if (empty($title))
$title=self::$title; $title = self::$title;
else else
self::$title=$title; self::$title = $title;
if(empty($Name)) $Name=time(); if (empty($Name)) $Name = time();
//设置Excel属性 //设置Excel属性
self::$PHPExcel ->getProperties() self::$PHPExcel->getProperties()
->setCreator("Neo") ->setCreator("Neo")
->setLastModifiedBy("Neo") ->setLastModifiedBy("Neo")
->setTitle(self::setUtf8($title)) ->setTitle(self::setUtf8($title))
@ -181,25 +191,25 @@ class PHPExcelService
->setDescription("") ->setDescription("")
->setKeywords($Name) ->setKeywords($Name)
->setCategory(""); ->setCategory("");
self::$PHPExcel ->getActiveSheet()->setCellValue('A1', $title); self::$PHPExcel->getActiveSheet()->setCellValue('A1', $title);
//文字居中 //文字居中
self::$PHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER); self::$PHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
self::$PHPExcel->getActiveSheet()->getStyle('A2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER); self::$PHPExcel->getActiveSheet()->getStyle('A2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
self::$PHPExcel->setActiveSheetIndex(0); self::$PHPExcel->setActiveSheetIndex(0);
self::$PHPExcel->getActiveSheet()->setTitle($Name); self::$PHPExcel->getActiveSheet()->setTitle($Name);
self::$PHPExcel->getActiveSheet()->setCellValue('A2',self::setCellInfo($info)); self::$PHPExcel->getActiveSheet()->setCellValue('A2', self::setCellInfo($info));
//合并表头单元格 //合并表头单元格
self::$PHPExcel->getActiveSheet()->mergeCells('A1:'.self::$cells.'1'); self::$PHPExcel->getActiveSheet()->mergeCells('A1:' . self::$cells . '1');
self::$PHPExcel->getActiveSheet()->mergeCells('A2:'.self::$cells.'2'); self::$PHPExcel->getActiveSheet()->mergeCells('A2:' . self::$cells . '2');
self::$PHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(40); self::$PHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(40);
self::$PHPExcel->getActiveSheet()->getRowDimension(2)->setRowHeight(20); self::$PHPExcel->getActiveSheet()->getRowDimension(2)->setRowHeight(20);
//设置表头行高 //设置表头行高
if($funName!==null && is_callable($funName)){ if ($funName !== null && is_callable($funName)) {
$fontstyle=self::$PHPExcel->getActiveSheet(); $fontstyle = self::$PHPExcel->getActiveSheet();
$funName($fontstyle,'A1','A2'); $funName($fontstyle, 'A1', 'A2');
}else{ } else {
//设置表头字体 //设置表头字体
self::$PHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setName('黑体'); self::$PHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setName('黑体');
self::$PHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(20); self::$PHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(20);
@ -207,36 +217,38 @@ class PHPExcelService
self::$PHPExcel->getActiveSheet()->getStyle('A2')->getFont()->setName('宋体'); self::$PHPExcel->getActiveSheet()->getStyle('A2')->getFont()->setName('宋体');
self::$PHPExcel->getActiveSheet()->getStyle('A2')->getFont()->setSize(14); self::$PHPExcel->getActiveSheet()->getStyle('A2')->getFont()->setSize(14);
} }
self::$PHPExcel->getActiveSheet()->getStyle('A3:'.self::$cells.'3')->getFont()->setBold(true); self::$PHPExcel->getActiveSheet()->getStyle('A3:' . self::$cells . '3')->getFont()->setBold(true);
return $this; return $this;
} }
/** /**
* 设置第二行标题内容 * 设置第二行标题内容
* @param $info array (['name'=>'','site'=>'','phone'=>123] || ['我是表名','我是地址','我是手机号码'] ) || string 自定义 * @param $info array (['name'=>'','site'=>'','phone'=>123] || ['我是表名','我是地址','我是手机号码'] ) || string 自定义
* @return string * @return string
*/ */
private static function setCellInfo($info){ private static function setCellInfo($info)
$content=['操作者:','导出日期:'.date('Y-m-d',time()),'地址:','电话:']; {
if(is_array($info) && !empty($info)){ $content = ['操作者:', '导出日期:' . date('Y-m-d', time()), '地址:', '电话:'];
if(isset($info['name'])){ if (is_array($info) && !empty($info)) {
$content[0].=$info['name']; if (isset($info['name'])) {
}else{ $content[0] .= $info['name'];
$content[0].=isset($info[0])?$info[0]:''; } else {
$content[0] .= isset($info[0]) ? $info[0] : '';
} }
if(isset($info['site'])){ if (isset($info['site'])) {
$content[2].=$info['site']; $content[2] .= $info['site'];
}else{ } else {
$content[2].=isset($info[1])?$info[1]:''; $content[2] .= isset($info[1]) ? $info[1] : '';
} }
if(isset($info['phone'])){ if (isset($info['phone'])) {
$content[3].=$info['phone']; $content[3] .= $info['phone'];
}else{ } else {
$content[3].=isset($info[2])?$info[2]:''; $content[3] .= isset($info[2]) ? $info[2] : '';
} }
return implode(' ',$content); return implode(' ', $content);
}else if(is_string($info)){ } else if (is_string($info)) {
return empty($info)?implode(' ',$content):$info; return empty($info) ? implode(' ', $content) : $info;
} }
} }
} }

View File

@ -10,8 +10,8 @@ namespace crmeb\services;
* @Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) * @Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
* @updated 2015-08-26 * @updated 2015-08-26
*/ */
class PHPTreeService{ class PHPTreeService
{
protected static $config = array( protected static $config = array(
/* 主键 */ /* 主键 */
'primary_key' => 'id', 'primary_key' => 'id',
@ -32,33 +32,37 @@ class PHPTreeService{
/* 层次暂存 */ /* 层次暂存 */
protected static $level = array(); protected static $level = array();
/** /**
* @name 生成树形结构 * @name 生成树形结构
* @param array 二维数组 * @param array 二维数组
* @return mixed 多维数组 * @return mixed 多维数组
*/ */
public static function makeTree($data,$options=array() ){ public static function makeTree($data, $options = array())
$dataset = self::buildData($data,$options); {
$r = self::makeTreeCore(0,$dataset,'normal'); $dataset = self::buildData($data, $options);
$r = self::makeTreeCore(0, $dataset, 'normal');
return $r; return $r;
} }
/* 生成线性结构, 便于HTML输出, 参数同上 */ /* 生成线性结构, 便于HTML输出, 参数同上 */
public static function makeTreeForHtml($data,$options=array()){ public static function makeTreeForHtml($data, $options = array())
{
$dataset = self::buildData($data,$options); $dataset = self::buildData($data, $options);
$r = self::makeTreeCore(0,$dataset,'linear'); $r = self::makeTreeCore(0, $dataset, 'linear');
return $r; return $r;
} }
/* 格式化数据, 私有方法 */ /* 格式化数据, 私有方法 */
private static function buildData($data,$options){ private static function buildData($data, $options)
$config = array_merge(self::$config,$options); {
$config = array_merge(self::$config, $options);
self::$config = $config; self::$config = $config;
extract($config); extract($config);
$r = array(); $r = array();
foreach($data as $item){ foreach ($data as $item) {
$id = $item[$primary_key]; $id = $item[$primary_key];
$parent_id = $item[$parent_key]; $parent_id = $item[$parent_key];
$r[$parent_id][$id] = $item; $r[$parent_id][$id] = $item;
@ -68,29 +72,25 @@ class PHPTreeService{
} }
/* 生成树核心, 私有方法 */ /* 生成树核心, 私有方法 */
private static function makeTreeCore($index,$data,$type='linear') private static function makeTreeCore($index, $data, $type = 'linear')
{ {
extract(self::$config); extract(self::$config);
foreach($data[$index] as $id=>$item) foreach ($data[$index] as $id => $item) {
{ if ($type == 'normal') {
if($type=='normal'){ if (isset($data[$id])) {
if(isset($data[$id])) $item[$expanded_key] = self::$config['expanded'];
{ $item[$children_key] = self::makeTreeCore($id, $data, $type);
$item[$expanded_key]= self::$config['expanded']; } else {
$item[$children_key]= self::makeTreeCore($id,$data,$type); $item[$leaf_key] = true;
}
else
{
$item[$leaf_key]= true;
} }
$r[] = $item; $r[] = $item;
}else if($type=='linear'){ } else if ($type == 'linear') {
$parent_id = $item[$parent_key]; $parent_id = $item[$parent_key];
self::$level[$id] = $index==0?0:self::$level[$parent_id]+1; self::$level[$id] = $index == 0 ? 0 : self::$level[$parent_id] + 1;
$item['level'] = self::$level[$id]; $item['level'] = self::$level[$id];
self::$result[] = $item; self::$result[] = $item;
if(isset($data[$id])){ if (isset($data[$id])) {
self::makeTreeCore($id,$data,$type); self::makeTreeCore($id, $data, $type);
} }
$r = self::$result; $r = self::$result;

View File

@ -15,22 +15,26 @@ class QrcodeService
/** /**
* 获取临时二维码 单个 * 获取临时二维码 单个
* */ * */
public static function getTemporaryQrcode($type,$id){ public static function getTemporaryQrcode($type, $id)
return QrcodeModel::getTemporaryQrcode($type,$id)->toArray(); {
}/** return QrcodeModel::getTemporaryQrcode($type, $id)->toArray();
}
/**
* 获取永久二维码 单个 * 获取永久二维码 单个
* */ * */
public static function getForeverQrcode($type,$id){ public static function getForeverQrcode($type, $id)
return QrcodeModel::getForeverQrcode($type,$id)->toArray(); {
return QrcodeModel::getForeverQrcode($type, $id)->toArray();
} }
public static function getQrcode($id,$type = 'id') public static function getQrcode($id, $type = 'id')
{ {
return QrcodeModel::getQrcode($id,$type); return QrcodeModel::getQrcode($id, $type);
} }
public static function scanQrcode($id,$type = 'id') public static function scanQrcode($id, $type = 'id')
{ {
return QrcodeModel::scanQrcode($id,$type); return QrcodeModel::scanQrcode($id, $type);
} }
} }

View File

@ -1,4 +1,5 @@
<?php <?php
namespace crmeb\services; namespace crmeb\services;
/** /**
@ -55,8 +56,8 @@ class SMSService
private static function auto() private static function auto()
{ {
self::$SMSAccount = sysConfig('sms_account'); self::$SMSAccount = sysConfig('sms_account');
self::$SMSToken = md5(self::$SMSAccount.md5(sysConfig('sms_token'))); self::$SMSToken = md5(self::$SMSAccount . md5(sysConfig('sms_token')));
self::$payNotify = sysConfig('site_url').'/api/sms/pay/notify'; self::$payNotify = sysConfig('site_url') . '/api/sms/pay/notify';
} }
/** /**
@ -65,7 +66,7 @@ class SMSService
*/ */
public static function code() public static function code()
{ {
return self::$SMSUrl.'sms/captcha'; return self::$SMSUrl . 'sms/captcha';
} }
@ -88,7 +89,7 @@ class SMSService
$data['phone'] = $phone; $data['phone'] = $phone;
$data['sign'] = $sign; $data['sign'] = $sign;
$data['code'] = $code; $data['code'] = $code;
return json_decode(HttpService::postRequest(self::$SMSUrl.'sms/register', $data), true); return json_decode(HttpService::postRequest(self::$SMSUrl . 'sms/register', $data), true);
} }
/** /**
@ -101,7 +102,7 @@ class SMSService
self::auto(); self::auto();
$data['account'] = self::$SMSAccount; $data['account'] = self::$SMSAccount;
$data['token'] = self::$SMSToken; $data['token'] = self::$SMSToken;
return json_decode(HttpService::postRequest(self::$SMSUrl.'sms/publictemp', $data), true); return json_decode(HttpService::postRequest(self::$SMSUrl . 'sms/publictemp', $data), true);
} }
/** /**
@ -117,7 +118,7 @@ class SMSService
$data['token'] = self::$SMSToken; $data['token'] = self::$SMSToken;
$data['id'] = $id; $data['id'] = $id;
$data['tempId'] = $tempId; $data['tempId'] = $tempId;
return json_decode(HttpService::postRequest(self::$SMSUrl.'sms/use', $data), true); return json_decode(HttpService::postRequest(self::$SMSUrl . 'sms/use', $data), true);
} }
/** /**
@ -135,7 +136,7 @@ class SMSService
$data['mobile'] = $phone; $data['mobile'] = $phone;
$data['template'] = $template; $data['template'] = $template;
$data['param'] = json_encode($param); $data['param'] = json_encode($param);
return json_decode(HttpService::postRequest(self::$SMSUrl.'sms/send', $data), true); return json_decode(HttpService::postRequest(self::$SMSUrl . 'sms/send', $data), true);
} }
/** /**
@ -147,7 +148,7 @@ class SMSService
self::auto(); self::auto();
$data['account'] = self::$SMSAccount; $data['account'] = self::$SMSAccount;
$data['token'] = self::$SMSToken; $data['token'] = self::$SMSToken;
return json_decode(HttpService::postRequest(self::$SMSUrl.'sms/userinfo', $data), true); return json_decode(HttpService::postRequest(self::$SMSUrl . 'sms/userinfo', $data), true);
} }
/** /**
@ -160,7 +161,7 @@ class SMSService
{ {
$data['page'] = $page; $data['page'] = $page;
$data['limit'] = $limit; $data['limit'] = $limit;
return json_decode(HttpService::getRequest(self::$SMSUrl.'sms/meal', $data), true); return json_decode(HttpService::getRequest(self::$SMSUrl . 'sms/meal', $data), true);
} }
/** /**
@ -181,7 +182,7 @@ class SMSService
$data['notify'] = self::$payNotify; $data['notify'] = self::$payNotify;
$data['price'] = $price; $data['price'] = $price;
$data['attach'] = $attach; $data['attach'] = $attach;
return json_decode(HttpService::postRequest(self::$SMSUrl.'sms/mealpay', $data), true); return json_decode(HttpService::postRequest(self::$SMSUrl . 'sms/mealpay', $data), true);
} }
/** /**
@ -199,7 +200,7 @@ class SMSService
$data['title'] = $title; $data['title'] = $title;
$data['content'] = $content; $data['content'] = $content;
$data['type'] = $type; $data['type'] = $type;
return json_decode(HttpService::postRequest(self::$SMSUrl.'sms/apply', $data), true); return json_decode(HttpService::postRequest(self::$SMSUrl . 'sms/apply', $data), true);
} }
/** /**
@ -212,6 +213,6 @@ class SMSService
self::auto(); self::auto();
$data['account'] = self::$SMSAccount; $data['account'] = self::$SMSAccount;
$data['token'] = self::$SMSToken; $data['token'] = self::$SMSToken;
return json_decode(HttpService::postRequest(self::$SMSUrl.'sms/template', $data), true); return json_decode(HttpService::postRequest(self::$SMSUrl . 'sms/template', $data), true);
} }
} }

View File

@ -20,13 +20,6 @@ class SystemConfigService
const CACHE_SYSTEM = 'system_config'; const CACHE_SYSTEM = 'system_config';
public static $ProtectedKey = [
'wechat_appid', 'wechat_appsecret', 'wechat_token', 'wechat_encodingaeskey', 'wechat_encode',
'pay_weixin_mchid', 'pay_weixin_client_cert', 'pay_weixin_client_key', 'pay_weixin_key', 'pay_weixin_open',
'routine_appId', 'routine_appsecret',
'pay_routine_mchid', 'pay_routine_key', 'pay_routine_client_cert', 'pay_routine_client_key', 'pay_weixin_open'
];
/** /**
* 初始化 * 初始化
*/ */

View File

@ -1,132 +1,147 @@
<?php <?php
namespace crmeb\services; namespace crmeb\services;
class UpgradeService extends FileService class UpgradeService extends FileService
{ {
//请求域名 //请求域名
public static $domain='http://shop.crmeb.net/'; public static $domain = 'http://shop.crmeb.net/';
//及时更新网址信息 //及时更新网址信息
public static $updatewebinfourl ='index.php/admin/server.upgrade_api/updatewebinfo.html'; public static $updatewebinfourl = 'index.php/admin/server.upgrade_api/updatewebinfo.html';
//公共接口地址 获取版本号 //公共接口地址 获取版本号
public static $isNowVersionUrl='index.php/admin/server.upgrade_api/now_version.html'; public static $isNowVersionUrl = 'index.php/admin/server.upgrade_api/now_version.html';
//公共接口地址 获取版本详情 //公共接口地址 获取版本详情
public static $isVersionInfo='index.php/admin/server.upgrade_api/version_info.html'; public static $isVersionInfo = 'index.php/admin/server.upgrade_api/version_info.html';
//公共接口地址 获取历史版本列表 //公共接口地址 获取历史版本列表
public static $isList='index.php/admin/server.upgrade_api/get_version_list.html'; public static $isList = 'index.php/admin/server.upgrade_api/get_version_list.html';
//公共接口地址 写入更新版本信息 //公共接口地址 写入更新版本信息
public static $isInsertLog='index.php/admin/server.upgrade_api/set_upgrade_info.html'; public static $isInsertLog = 'index.php/admin/server.upgrade_api/set_upgrade_info.html';
//公共接口地址 获取大于当前版本的所有版本 //公共接口地址 获取大于当前版本的所有版本
public static $isNowVersion='index.php/admin/server.upgrade_api/get_now_version.html'; public static $isNowVersion = 'index.php/admin/server.upgrade_api/get_now_version.html';
//公共接口地址 更新网址信息 //公共接口地址 更新网址信息
protected static $UpdateWeBinfo='index.php/admin/server.upgrade_api/updatewebinfo.html'; protected static $UpdateWeBinfo = 'index.php/admin/server.upgrade_api/updatewebinfo.html';
//公共接口地址 获取多少版本未更新 //公共接口地址 获取多少版本未更新
public static $NewVersionCount='index.php/admin/server.upgrade_api/new_version_count.html'; public static $NewVersionCount = 'index.php/admin/server.upgrade_api/new_version_count.html';
//公共接口地址 判断是否有权限 返回1有权限0无权限 //公共接口地址 判断是否有权限 返回1有权限0无权限
protected static $Isauth='index.php/admin/server.upgrade_api/isauth.html'; protected static $Isauth = 'index.php/admin/server.upgrade_api/isauth.html';
//相隔付 //相隔付
private static $seperater = "{&&}"; private static $seperater = "{&&}";
//更新网址信息 //更新网址信息
public function snyweninfo($serverweb){ public function snyweninfo($serverweb)
return self::request_post(self::$UpdateWeBinfo,$serverweb); {
return self::request_post(self::$UpdateWeBinfo, $serverweb);
} }
//判断是否有权限 返回1有权限0无权限 //判断是否有权限 返回1有权限0无权限
public function isauth(){ public function isauth()
{
return self::request_post(self::$Isauth); return self::request_post(self::$Isauth);
} }
/* /*
*获取ip token 生成当前时间和过期时间 *获取ip token 生成当前时间和过期时间
* @param string ip * @param string ip
* @param int $valid_peroid 过期周期 15 * @param int $valid_peroid 过期周期 15
*/ */
public static function get_token($ip='',$valid_peroid=1296000){ public static function get_token($ip = '', $valid_peroid = 1296000)
$request=app('request'); {
if(empty($ip)) $ip=$request->ip(); $request = app('request');
$to_ken=$request->domain().self::$seperater.$ip.self::$seperater.time().self::$seperater.(time()+$valid_peroid).self::$seperater; if (empty($ip)) $ip = $request->ip();
$token=self::enCode($to_ken); $to_ken = $request->domain() . self::$seperater . $ip . self::$seperater . time() . self::$seperater . (time() + $valid_peroid) . self::$seperater;
$token = self::enCode($to_ken);
return $token; return $token;
} }
private static function getRet($msg,$code=400){
return ['msg'=>$msg,'code'=>$code]; private static function getRet($msg, $code = 400)
{
return ['msg' => $msg, 'code' => $code];
} }
/** /**
* *
* @param string $url * @param string $url
* @param array $post_data * @param array $post_data
*/ */
public static function start(){ public static function start()
$pach = app()->getRootPath().'version'; {
$pach = app()->getRootPath() . 'version';
$request = app('request'); $request = app('request');
if(!file_exists($pach)) return self::getRet($pach.'升级文件丢失,请联系管理员'); if (!file_exists($pach)) return self::getRet($pach . '升级文件丢失,请联系管理员');
$version=@file($pach); $version = @file($pach);
if(!isset($version[0])) return self::getRet('获取失败'); if (!isset($version[0])) return self::getRet('获取失败');
$lv=self::request_post(self::$isNowVersionUrl,['token'=>self::get_token($request->ip())]); $lv = self::request_post(self::$isNowVersionUrl, ['token' => self::get_token($request->ip())]);
if(isset($lv['code']) && $lv['code']==200) if (isset($lv['code']) && $lv['code'] == 200)
$version_lv=isset($lv['data']['version']) && $lv['data']['version'] ? $lv['data']['version'] : false; $version_lv = isset($lv['data']['version']) && $lv['data']['version'] ? $lv['data']['version'] : false;
else else
return isset($lv['msg'])?self::getRet($lv['msg']):self::getRet('获取失败'); return isset($lv['msg']) ? self::getRet($lv['msg']) : self::getRet('获取失败');
if($version_lv===false) return self::getRet('获取失败'); if ($version_lv === false) return self::getRet('获取失败');
if(strstr($version[0],'=')!==false){ if (strstr($version[0], '=') !== false) {
$version=explode('=',$version[0]); $version = explode('=', $version[0]);
if($version[1]!=$version_lv){ if ($version[1] != $version_lv) {
return self::getRet($version_lv,200); return self::getRet($version_lv, 200);
} }
} }
return self::getRet('获取失败'); return self::getRet('获取失败');
} }
public static function getVersion(){
$pach = app()->getRootPath().'.version'; public static function getVersion()
if(!file_exists($pach)) return self::getRet($pach.'升级文件丢失,请联系管理员'); {
$version=@file($pach); $pach = app()->getRootPath() . '.version';
if(!isset($version[0]) && !isset($version[1])) return self::getRet('获取失败'); if (!file_exists($pach)) return self::getRet($pach . '升级文件丢失,请联系管理员');
$arr=[]; $version = @file($pach);
foreach ($version as $val){ if (!isset($version[0]) && !isset($version[1])) return self::getRet('获取失败');
list($k,$v)=explode('=',$val); $arr = [];
$arr[$k]=$v; foreach ($version as $val) {
list($k, $v) = explode('=', $val);
$arr[$k] = $v;
} }
return self::getRet($arr,200); return self::getRet($arr, 200);
} }
/** /**
* 模拟post进行url请求 * 模拟post进行url请求
* @param string $url * @param string $url
* @param array $post_data * @param array $post_data
*/ */
public static function request_post($url = '', $post_data = array()) { public static function request_post($url = '', $post_data = array())
if(strstr($url,'http')===false) $url=self::$domain.$url; {
if (empty($url)){ if (strstr($url, 'http') === false) $url = self::$domain . $url;
if (empty($url)) {
return false; return false;
} }
if(!isset($post_data['token'])) $post_data['token']=self::get_token(); if (!isset($post_data['token'])) $post_data['token'] = self::get_token();
$o = ""; $o = "";
foreach ( $post_data as $k => $v ) foreach ($post_data as $k => $v) {
{ $o .= "$k=" . urlencode($v) . "&";
$o.= "$k=" . urlencode( $v ). "&" ;
} }
$post_data = substr($o,0,-1); $post_data = substr($o, 0, -1);
$postUrl = $url; $postUrl = $url;
$curlPost = $post_data; $curlPost = $post_data;
$ch = curl_init();//初始化curl $ch = curl_init();//初始化curl
curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页 curl_setopt($ch, CURLOPT_URL, $postUrl);//抓取指定网页
curl_setopt($ch, CURLOPT_HEADER, 0);//设置header curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
curl_setopt($ch, CURLOPT_POST, 1);//post提交方式 curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost); curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
curl_setopt($ch, CURLOPT_TIMEOUT,20); curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$data = curl_exec($ch);//运行curl $data = curl_exec($ch);//运行curl
curl_close($ch); curl_close($ch);
if($data){ if ($data) {
$data=json_decode($data,true); $data = json_decode($data, true);
} }
return $data; return $data;
} }
/** /**
* 验证远程文件是否存在 以及下载 * 验证远程文件是否存在 以及下载
* @param string $url 文件路径 * @param string $url 文件路径
* @param string $savefile 保存地址 * @param string $savefile 保存地址
*/ */
public static function check_remote_file_exists($url,$savefile) public static function check_remote_file_exists($url, $savefile)
{ {
$url=self::$domain.'public'.DS.'uploads'.DS.'upgrade'.DS.$url; $url = self::$domain . 'public' . DS . 'uploads' . DS . 'upgrade' . DS . $url;
$url = str_replace('\\','/',$url); $url = str_replace('\\', '/', $url);
$curl = curl_init($url); $curl = curl_init($url);
curl_setopt($curl, CURLOPT_NOBODY, true); curl_setopt($curl, CURLOPT_NOBODY, true);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET'); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
@ -134,47 +149,49 @@ class UpgradeService extends FileService
$result = curl_exec($curl); $result = curl_exec($curl);
$found = false; $found = false;
// 如果请求没有发送失败 // 如果请求没有发送失败
if ($result !== false) if ($result !== false) {
{
// 再检查http响应码是否为200 // 再检查http响应码是否为200
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($statusCode == 200) if ($statusCode == 200) {
{
curl_close($curl); curl_close($curl);
$fileservice=new self; $fileservice = new self;
//下载文件 //下载文件
$zip=$fileservice->down_remote_file($url,$savefile); $zip = $fileservice->down_remote_file($url, $savefile);
if($zip['error']>0) return false; if ($zip['error'] > 0) return false;
if(!isset($zip['save_path']) && empty($zip['save_path'])) return false; if (!isset($zip['save_path']) && empty($zip['save_path'])) return false;
if(!file_exists($zip['save_path'])) return false; if (!file_exists($zip['save_path'])) return false;
return $zip['save_path']; return $zip['save_path'];
} }
} }
curl_close($curl); curl_close($curl);
return $found; return $found;
} }
/** /**
* 通用加密 * 通用加密
* @param String $string 需要加密的字串 * @param String $string 需要加密的字串
* @param String $skey 加密EKY * @param String $skey 加密EKY
* @return String * @return String
*/ */
private static function enCode($string = '', $skey = 'fb') { private static function enCode($string = '', $skey = 'fb')
{
$skey = array_reverse(str_split($skey)); $skey = array_reverse(str_split($skey));
$strArr = str_split(base64_encode($string)); $strArr = str_split(base64_encode($string));
$strCount = count($strArr); $strCount = count($strArr);
foreach ($skey as $key => $value) { foreach ($skey as $key => $value) {
$key < $strCount && $strArr[$key].=$value; $key < $strCount && $strArr[$key] .= $value;
} }
return str_replace('=', 'O0O0O', join('', $strArr)); return str_replace('=', 'O0O0O', join('', $strArr));
} }
/** /**
* 去除回车去取空格去除换行去除tab * 去除回车去取空格去除换行去除tab
* @param String $str 需要去除的字串 * @param String $str 需要去除的字串
* @return String * @return String
*/ */
public static function replace($str){ public static function replace($str)
return trim(str_replace(array("\r", "\n", "\t"), '',$str)); {
return trim(str_replace(array("\r", "\n", "\t"), '', $str));
} }
} }

View File

@ -50,8 +50,8 @@ class UploadService
'size' => 0, 'size' => 0,
'type' => 'image/jpeg', 'type' => 'image/jpeg',
'dir' => '', 'dir' => '',
'thumb_path'=> '', 'thumb_path' => '',
'image_type'=> '', 'image_type' => '',
'time' => 0, 'time' => 0,
]; ];
@ -83,7 +83,7 @@ class UploadService
*/ */
public static function getInstance() public static function getInstance()
{ {
if(is_null(self::$instance)) self::$instance = new self(); if (is_null(self::$instance)) self::$instance = new self();
return self::$instance; return self::$instance;
} }
@ -192,8 +192,8 @@ class UploadService
*/ */
protected static function uploadDir($path, $root = null) protected static function uploadDir($path, $root = null)
{ {
if ($root === null) $root = app()->getRootPath() . 'public' . DS ; if ($root === null) $root = app()->getRootPath() . 'public' . DS;
return $root . 'uploads' .DS. $path; return $root . 'uploads' . DS . $path;
} }
/** /**
@ -204,14 +204,14 @@ class UploadService
public function image($fileName) public function image($fileName)
{ {
$info = []; $info = [];
try{ try {
$uploadType = $this->uploadType ? : sysConfig('upload_type'); $uploadType = $this->uploadType ?: sysConfig('upload_type');
//TODO 没有选择默认使用本地上传 //TODO 没有选择默认使用本地上传
if (!$uploadType) $uploadType = 1; if (!$uploadType) $uploadType = 1;
switch ($uploadType) { switch ($uploadType) {
case 1 : case 1 :
$info = $this->uploadLocaFile($fileName); $info = $this->uploadLocaFile($fileName);
if(is_string($info)) return $info; if (is_string($info)) return $info;
break; break;
case 2 : case 2 :
$keys = Qiniu::uploadImage($fileName); $keys = Qiniu::uploadImage($fileName);
@ -219,7 +219,7 @@ class UploadService
foreach ($keys as $key => &$item) { foreach ($keys as $key => &$item) {
if (is_array($item)) { if (is_array($item)) {
$info = Qiniu::imageUrl($item['key']); $info = Qiniu::imageUrl($item['key']);
$info = $this->setUploadInfo($info['dir'],2,$item['key'],UtilService::setHttpType($info['thumb_path'])); $info = $this->setUploadInfo($info['dir'], 2, $item['key'], UtilService::setHttpType($info['thumb_path']));
} }
} }
} else return $keys; } else return $keys;
@ -227,21 +227,21 @@ class UploadService
case 3 : case 3 :
$serverImageInfo = OSS::uploadImage($fileName); $serverImageInfo = OSS::uploadImage($fileName);
if (!is_array($serverImageInfo)) return $serverImageInfo; if (!is_array($serverImageInfo)) return $serverImageInfo;
$info = $this->setUploadInfo(UtilService::setHttpType($serverImageInfo['info']['url']),3,substr(strrchr($serverImageInfo['info']['url'], '/'), 1)); $info = $this->setUploadInfo(UtilService::setHttpType($serverImageInfo['info']['url']), 3, substr(strrchr($serverImageInfo['info']['url'], '/'), 1));
break; break;
case 4 : case 4 :
list($imageUrl,$serverImageInfo) = COS::uploadImage($fileName); list($imageUrl, $serverImageInfo) = COS::uploadImage($fileName);
if (!is_array($serverImageInfo) && !is_object($serverImageInfo)) return $serverImageInfo; if (!is_array($serverImageInfo) && !is_object($serverImageInfo)) return $serverImageInfo;
$info = $this->setUploadInfo($imageUrl,4,substr(strrchr($imageUrl, '/'), 1)); $info = $this->setUploadInfo($imageUrl, 4, substr(strrchr($imageUrl, '/'), 1));
break; break;
default: default:
$info = $this->uploadLocaFile($fileName); $info = $this->uploadLocaFile($fileName);
if(is_string($info)) return $info; if (is_string($info)) return $info;
break; break;
} }
$this->uploadPath = ''; $this->uploadPath = '';
$this->autoValidate = true; $this->autoValidate = true;
}catch (\Exception $e){ } catch (\Exception $e) {
return $e->getMessage(); return $e->getMessage();
} }
return $info; return $info;
@ -254,8 +254,9 @@ class UploadService
* @param bool $isData 是否真实获取图片信息 * @param bool $isData 是否真实获取图片信息
* @return array * @return array
*/ */
public static function getImageHeaders(string $url,$type = 1,$isData = true){ public static function getImageHeaders(string $url, $type = 1, $isData = true)
stream_context_set_default( [ {
stream_context_set_default([
'ssl' => [ 'ssl' => [
'verify_peer' => false, 'verify_peer' => false,
'verify_peer_name' => false, 'verify_peer_name' => false,
@ -263,12 +264,12 @@ class UploadService
]); ]);
$header['Content-Length'] = 0; $header['Content-Length'] = 0;
$header['Content-Type'] = 'image/jpeg'; $header['Content-Type'] = 'image/jpeg';
if(!$isData) return $header; if (!$isData) return $header;
try{ try {
$header = get_headers(str_replace('\\', '/', UtilService::setHttpType($url, $type)), true); $header = get_headers(str_replace('\\', '/', UtilService::setHttpType($url, $type)), true);
if(!isset($header['Content-Length'])) $header['Content-Length'] = 0; if (!isset($header['Content-Length'])) $header['Content-Length'] = 0;
if(!isset($header['Content-Type'])) $header['Content-Type'] = 'image/jpeg'; if (!isset($header['Content-Type'])) $header['Content-Type'] = 'image/jpeg';
}catch (\Exception $e){ } catch (\Exception $e) {
$header['Content-Length'] = 0; $header['Content-Length'] = 0;
$header['Content-Type'] = 'image/jpeg'; $header['Content-Type'] = 'image/jpeg';
} }
@ -284,8 +285,7 @@ class UploadService
{ {
$file = request()->file($fileName); $file = request()->file($fileName);
if (!$file) return '上传文件不存在!'; if (!$file) return '上传文件不存在!';
if ($this->autoValidate) if ($this->autoValidate) {
{
try { try {
validate([$fileName => $this->imageValidate])->check([$fileName => $file]); validate([$fileName => $this->imageValidate])->check([$fileName => $file]);
} catch (ValidateException $e) { } catch (ValidateException $e) {
@ -297,9 +297,9 @@ class UploadService
$filePath = Filesystem::path($fileName); $filePath = Filesystem::path($fileName);
$fileInfo = new File($filePath); $fileInfo = new File($filePath);
$url = '/uploads/' . $fileName; $url = '/uploads/' . $fileName;
return $this->setUploadInfo($url,1,$fileInfo->getFilename(),self::thumb('.'.$url),[ return $this->setUploadInfo($url, 1, $fileInfo->getFilename(), self::thumb('.' . $url), [
'Content-Length'=>$fileInfo->getSize(), 'Content-Length' => $fileInfo->getSize(),
'Content-Type'=>$fileInfo->getMime() 'Content-Type' => $fileInfo->getMime()
]); ]);
} }
@ -310,7 +310,7 @@ class UploadService
* @param string $root * @param string $root
* @return array|string * @return array|string
*/ */
public function uploadLocalStream($key, $content,$root='') public function uploadLocalStream($key, $content, $root = '')
{ {
$siteUrl = sysConfig('site_url') . '/'; $siteUrl = sysConfig('site_url') . '/';
$path = self::uploadDir($this->uploadPath, $root); $path = self::uploadDir($this->uploadPath, $root);
@ -321,9 +321,9 @@ class UploadService
$name = $path . DS . $key; $name = $path . DS . $key;
file_put_contents($name, $content); file_put_contents($name, $content);
$path = str_replace('\\', '/', $path); $path = str_replace('\\', '/', $path);
$headerArray = self::getImageHeaders($siteUrl . $path . '/' .$key); $headerArray = self::getImageHeaders($siteUrl . $path . '/' . $key);
$url = '/'.$path . '/' .$key; $url = '/' . $path . '/' . $key;
return $this->setUploadInfo($url,1,$key,$url,$headerArray); return $this->setUploadInfo($url, 1, $key, $url, $headerArray);
} }
/** /**
@ -334,7 +334,7 @@ class UploadService
* @return array|string * @return array|string
* @throws \Exception * @throws \Exception
*/ */
public function imageStream($key, $content,$root='') public function imageStream($key, $content, $root = '')
{ {
$uploadType = sysConfig('upload_type'); $uploadType = sysConfig('upload_type');
//TODO 没有选择默认使用本地上传 //TODO 没有选择默认使用本地上传
@ -342,8 +342,8 @@ class UploadService
$info = []; $info = [];
switch ($uploadType) { switch ($uploadType) {
case 1 : case 1 :
$info = $this->uploadLocalStream($key, $content,$root); $info = $this->uploadLocalStream($key, $content, $root);
if(is_string($info)) return $info; if (is_string($info)) return $info;
break; break;
case 2 : case 2 :
$keys = Qiniu::uploadImageStream($key, $content); $keys = Qiniu::uploadImageStream($key, $content);
@ -352,7 +352,7 @@ class UploadService
if (is_array($item)) { if (is_array($item)) {
$info = Qiniu::imageUrl($item['key']); $info = Qiniu::imageUrl($item['key']);
$info['dir'] = UtilService::setHttpType($info['dir']); $info['dir'] = UtilService::setHttpType($info['dir']);
$info = $this->setUploadInfo($info['dir'],2,$item['key'],$info['thumb_path']); $info = $this->setUploadInfo($info['dir'], 2, $item['key'], $info['thumb_path']);
} }
} }
if (!count($info)) return '七牛云文件上传失败'; if (!count($info)) return '七牛云文件上传失败';
@ -362,16 +362,16 @@ class UploadService
$content = COS::resourceStream($content); $content = COS::resourceStream($content);
$serverImageInfo = OSS::uploadImageStream($key, $content); $serverImageInfo = OSS::uploadImageStream($key, $content);
if (!is_array($serverImageInfo)) return $serverImageInfo; if (!is_array($serverImageInfo)) return $serverImageInfo;
$info = $this->setUploadInfo(UtilService::setHttpType($serverImageInfo['info']['url']),3,substr(strrchr($serverImageInfo['info']['url'], '/'), 1)); $info = $this->setUploadInfo(UtilService::setHttpType($serverImageInfo['info']['url']), 3, substr(strrchr($serverImageInfo['info']['url'], '/'), 1));
break; break;
case 4 : case 4 :
list($imageUrl,$serverImageInfo) = COS::uploadImageStream($key, $content); list($imageUrl, $serverImageInfo) = COS::uploadImageStream($key, $content);
if (!is_array($serverImageInfo) && !is_object($serverImageInfo)) return $serverImageInfo; if (!is_array($serverImageInfo) && !is_object($serverImageInfo)) return $serverImageInfo;
$info = $this->setUploadInfo($imageUrl,4,substr(strrchr($imageUrl, '/'), 1)); $info = $this->setUploadInfo($imageUrl, 4, substr(strrchr($imageUrl, '/'), 1));
break; break;
default: default:
$info = $this->uploadLocalStream($key, $content,$root); $info = $this->uploadLocalStream($key, $content, $root);
if(is_string($info)) return $info; if (is_string($info)) return $info;
break; break;
} }
$this->uploadPath = ''; $this->uploadPath = '';
@ -387,25 +387,25 @@ class UploadService
* @param string $thumbPath * @param string $thumbPath
* @return array * @return array
*/ */
protected function setUploadInfo(string $url,int $imageType,string $name = '',string $thumbPath = '',array $headerArray = []) protected function setUploadInfo(string $url, int $imageType, string $name = '', string $thumbPath = '', array $headerArray = [])
{ {
$headerArray = count($headerArray) ? $headerArray : self::getImageHeaders($url); $headerArray = count($headerArray) ? $headerArray : self::getImageHeaders($url);
if(is_array($headerArray['Content-Type']) && count($headerArray['Content-Length']) == 2){ if (is_array($headerArray['Content-Type']) && count($headerArray['Content-Length']) == 2) {
$headerArray['Content-Length'] = $headerArray['Content-Length'][1]; $headerArray['Content-Length'] = $headerArray['Content-Length'][1];
} }
if(is_array($headerArray['Content-Type']) && count($headerArray['Content-Type']) == 2){ if (is_array($headerArray['Content-Type']) && count($headerArray['Content-Type']) == 2) {
$headerArray['Content-Type'] = $headerArray['Content-Type'][1]; $headerArray['Content-Type'] = $headerArray['Content-Type'][1];
} }
$info = [ $info = [
'name' => str_replace('\\','/',$name ? : $url), 'name' => str_replace('\\', '/', $name ?: $url),
'dir' => str_replace('\\','/',$url), 'dir' => str_replace('\\', '/', $url),
'size' => $headerArray['Content-Length'], 'size' => $headerArray['Content-Length'],
'type' => $headerArray['Content-Type'], 'type' => $headerArray['Content-Type'],
'time' => time(), 'time' => time(),
'thumb_path' => str_replace('\\','/',$thumbPath ? : $url), 'thumb_path' => str_replace('\\', '/', $thumbPath ?: $url),
'image_type' => $imageType, 'image_type' => $imageType,
]; ];
$uploadInfo = array_merge($this->uploadInfo,$info); $uploadInfo = array_merge($this->uploadInfo, $info);
return $uploadInfo; return $uploadInfo;
} }
@ -421,8 +421,7 @@ class UploadService
if (strtolower($extension) == 'php' || !$extension) if (strtolower($extension) == 'php' || !$extension)
return self::setError('上传文件非法!'); return self::setError('上传文件非法!');
$file = request()->file($fileName); $file = request()->file($fileName);
if ($this->autoValidate) if ($this->autoValidate) {
{
try { try {
validate([$fileName => $this->imageValidate])->check([$fileName => $file]); validate([$fileName => $this->imageValidate])->check([$fileName => $file]);
} catch (ValidateException $e) { } catch (ValidateException $e) {
@ -431,7 +430,7 @@ class UploadService
}; };
$fileName = Filesystem::putFile($this->uploadPath, $file); $fileName = Filesystem::putFile($this->uploadPath, $file);
if (!$fileName) return self::setError('图片上传失败!'); if (!$fileName) return self::setError('图片上传失败!');
return self::successful(str_replace('\\','/',$fileName)); return self::successful(str_replace('\\', '/', $fileName));
} }
public static function pathToUrl($path) public static function pathToUrl($path)
@ -462,7 +461,7 @@ class UploadService
$fileName = basename($filePath); $fileName = basename($filePath);
$savePath = $dir . DS . $pre . $fileName; $savePath = $dir . DS . $pre . $fileName;
$img->thumb($width, $height)->save($savePath); $img->thumb($width, $height)->save($savePath);
if(substr($savePath, 0, 2) == './') return substr($savePath, 1, strlen($savePath)); if (substr($savePath, 0, 2) == './') return substr($savePath, 1, strlen($savePath));
return DS . $savePath; return DS . $savePath;
} }

View File

@ -24,19 +24,19 @@ class UtilService
* @param bool $suffix * @param bool $suffix
* @return array * @return array
*/ */
public static function postMore($params,$request = null,$suffix = false) public static function postMore($params, $request = null, $suffix = false)
{ {
if($request === null) $request = app('request'); if ($request === null) $request = app('request');
$p = []; $p = [];
$i = 0; $i = 0;
foreach ($params as $param){ foreach ($params as $param) {
if(!is_array($param)) { if (!is_array($param)) {
$p[$suffix == true ? $i++ : $param] = $request->param($param); $p[$suffix == true ? $i++ : $param] = $request->param($param);
}else{ } else {
if(!isset($param[1])) $param[1] = null; if (!isset($param[1])) $param[1] = null;
if(!isset($param[2])) $param[2] = ''; if (!isset($param[2])) $param[2] = '';
$name = is_array($param[1]) ? $param[0].'/a' : $param[0]; $name = is_array($param[1]) ? $param[0] . '/a' : $param[0];
$p[$suffix == true ? $i++ : (isset($param[3]) ? $param[3] : $param[0])] = $request->param($name,$param[1],$param[2]); $p[$suffix == true ? $i++ : (isset($param[3]) ? $param[3] : $param[0])] = $request->param($name, $param[1], $param[2]);
} }
} }
return $p; return $p;
@ -49,25 +49,26 @@ class UtilService
* @param bool $suffix * @param bool $suffix
* @return array * @return array
*/ */
public static function getMore($params,$request=null,$suffix = false) public static function getMore($params, $request = null, $suffix = false)
{ {
if($request === null) $request = app('request'); if ($request === null) $request = app('request');
$p = []; $p = [];
$i = 0; $i = 0;
foreach ($params as $param){ foreach ($params as $param) {
if(!is_array($param)) { if (!is_array($param)) {
$p[$suffix == true ? $i++ : $param] = $request->param($param); $p[$suffix == true ? $i++ : $param] = $request->param($param);
}else{ } else {
if(!isset($param[1])) $param[1] = null; if (!isset($param[1])) $param[1] = null;
if(!isset($param[2])) $param[2] = ''; if (!isset($param[2])) $param[2] = '';
$name = is_array($param[1]) ? $param[0].'/a' : $param[0]; $name = is_array($param[1]) ? $param[0] . '/a' : $param[0];
$p[$suffix == true ? $i++ : (isset($param[3]) ? $param[3] : $param[0])] = $request->param($name,$param[1],$param[2]); $p[$suffix == true ? $i++ : (isset($param[3]) ? $param[3] : $param[0])] = $request->param($name, $param[1], $param[2]);
} }
} }
return $p; return $p;
} }
public static function encrypt($string, $operation = false, $key = '', $expiry = 0) { public static function encrypt($string, $operation = false, $key = '', $expiry = 0)
{
// 动态密匙长度,相同的明文会生成不同密文就是依靠动态密匙 // 动态密匙长度,相同的明文会生成不同密文就是依靠动态密匙
$ckey_length = 6; $ckey_length = 6;
@ -79,33 +80,33 @@ class UtilService
// 密匙b会用来做数据完整性验证 // 密匙b会用来做数据完整性验证
$keyb = md5(substr($key, 16, 16)); $keyb = md5(substr($key, 16, 16));
// 密匙c用于变化生成的密文 // 密匙c用于变化生成的密文
$keyc = $ckey_length ? ($operation == false ? substr($string, 0, $ckey_length): $keyc = $ckey_length ? ($operation == false ? substr($string, 0, $ckey_length) :
substr(md5(microtime()), -$ckey_length)) : ''; substr(md5(microtime()), -$ckey_length)) : '';
// 参与运算的密匙 // 参与运算的密匙
$cryptkey = $keya.md5($keya.$keyc); $cryptkey = $keya . md5($keya . $keyc);
$key_length = strlen($cryptkey); $key_length = strlen($cryptkey);
// 明文前10位用来保存时间戳解密时验证数据有效性10到26位用来保存$keyb(密匙b) // 明文前10位用来保存时间戳解密时验证数据有效性10到26位用来保存$keyb(密匙b)
//解密时会通过这个密匙验证数据完整性 //解密时会通过这个密匙验证数据完整性
// 如果是解码的话,会从第$ckey_length位开始因为密文前$ckey_length位保存 动态密匙,以保证解密正确 // 如果是解码的话,会从第$ckey_length位开始因为密文前$ckey_length位保存 动态密匙,以保证解密正确
$string = $operation == false ? base64_decode(substr($string, $ckey_length)) : $string = $operation == false ? base64_decode(substr($string, $ckey_length)) :
sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string; sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
$string_length = strlen($string); $string_length = strlen($string);
$result = ''; $result = '';
$box = range(0, 255); $box = range(0, 255);
$rndkey = array(); $rndkey = array();
// 产生密匙簿 // 产生密匙簿
for($i = 0; $i <= 255; $i++) { for ($i = 0; $i <= 255; $i++) {
$rndkey[$i] = ord($cryptkey[$i % $key_length]); $rndkey[$i] = ord($cryptkey[$i % $key_length]);
} }
// 用固定的算法,打乱密匙簿,增加随机性,好像很复杂,实际上对并不会增加密文的强度 // 用固定的算法,打乱密匙簿,增加随机性,好像很复杂,实际上对并不会增加密文的强度
for($j = $i = 0; $i < 256; $i++) { for ($j = $i = 0; $i < 256; $i++) {
$j = ($j + $box[$i] + $rndkey[$i]) % 256; $j = ($j + $box[$i] + $rndkey[$i]) % 256;
$tmp = $box[$i]; $tmp = $box[$i];
$box[$i] = $box[$j]; $box[$i] = $box[$j];
$box[$j] = $tmp; $box[$j] = $tmp;
} }
// 核心加解密部分 // 核心加解密部分
for($a = $j = $i = 0; $i < $string_length; $i++) { for ($a = $j = $i = 0; $i < $string_length; $i++) {
$a = ($a + 1) % 256; $a = ($a + 1) % 256;
$j = ($j + $box[$a]) % 256; $j = ($j + $box[$a]) % 256;
$tmp = $box[$a]; $tmp = $box[$a];
@ -114,10 +115,10 @@ class UtilService
// 从密匙簿得出密匙进行异或,再转成字符 // 从密匙簿得出密匙进行异或,再转成字符
$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256])); $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
} }
if($operation == false) { if ($operation == false) {
// 验证数据有效性,请看未加密明文的格式 // 验证数据有效性,请看未加密明文的格式
if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) &&
substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) { substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
return substr($result, 26); return substr($result, 26);
} else { } else {
return ''; return '';
@ -125,7 +126,7 @@ class UtilService
} else { } else {
// 把动态密匙保存在密文里,这也是为什么同样的明文,生产不同密文后能解密的原因 // 把动态密匙保存在密文里,这也是为什么同样的明文,生产不同密文后能解密的原因
// 因为加密后的密文可能是一些特殊字符复制过程可能会丢失所以用base64编码 // 因为加密后的密文可能是一些特殊字符复制过程可能会丢失所以用base64编码
return $keyc.str_replace('=', '', base64_encode($result)); return $keyc . str_replace('=', '', base64_encode($result));
} }
} }
@ -137,7 +138,7 @@ class UtilService
*/ */
public static function pathToUrl($path) public static function pathToUrl($path)
{ {
return trim(str_replace(DS, '/', $path),'.'); return trim(str_replace(DS, '/', $path), '.');
} }
/** /**
@ -147,10 +148,10 @@ class UtilService
*/ */
public static function urlToPath($url) public static function urlToPath($url)
{ {
$path = trim(str_replace('/',DS,$url),DS); $path = trim(str_replace('/', DS, $url), DS);
if(0 !== strripos($path, 'public')) if (0 !== strripos($path, 'public'))
$path = 'public' . DS . $path; $path = 'public' . DS . $path;
return app()->getRootPath().$path; return app()->getRootPath() . $path;
} }
/** /**
@ -202,6 +203,7 @@ class UtilService
} }
return $list; return $list;
} }
/** /**
* 分级返回多维数组 * 分级返回多维数组
* @param $data * @param $data
@ -227,6 +229,7 @@ class UtilService
} }
/**分级返回下级所有分类ID /**分级返回下级所有分类ID
* @param $data * @param $data
* @param string $children * @param string $children
@ -234,12 +237,12 @@ class UtilService
* @param string $pk * @param string $pk
* @return string * @return string
*/ */
public static function getChildrenPid($data,$pid, $field = 'pid', $pk = 'id') public static function getChildrenPid($data, $pid, $field = 'pid', $pk = 'id')
{ {
static $pids = ''; static $pids = '';
foreach ($data as $k => $res) { foreach ($data as $k => $res) {
if ($res[$field] == $pid) { if ($res[$field] == $pid) {
$pids .= ','.$res[$pk]; $pids .= ',' . $res[$pk];
self::getChildrenPid($data, $res[$pk], $field, $pk); self::getChildrenPid($data, $res[$pk], $field, $pk);
} }
} }
@ -252,13 +255,13 @@ class UtilService
* @param $url * @param $url
* @return \StdClass * @return \StdClass
*/ */
public static function rmPublicResource($url,$isPath = false) public static function rmPublicResource($url, $isPath = false)
{ {
$path = $isPath ? $url : realpath(self::urlToPath($url)); $path = $isPath ? $url : realpath(self::urlToPath($url));
if(!$path) return JsonService::fail('删除文件不存在!'); if (!$path) return JsonService::fail('删除文件不存在!');
if(!file_exists($path)) return JsonService::fail('删除路径不合法!'); if (!file_exists($path)) return JsonService::fail('删除路径不合法!');
// if(0 !== strpos($path,app()->getRootPath().'public/uploads/')) return JsonService::fail('删除路径不合法!'); // if(0 !== strpos($path,app()->getRootPath().'public/uploads/')) return JsonService::fail('删除路径不合法!');
if(!unlink($path)) return JsonService::fail('删除文件失败!'); if (!unlink($path)) return JsonService::fail('删除文件失败!');
return JsonService::successful(); return JsonService::successful();
} }
@ -278,14 +281,14 @@ class UtilService
*/ */
public static function anonymity($name) public static function anonymity($name)
{ {
$strLen = mb_strlen($name,'UTF-8'); $strLen = mb_strlen($name, 'UTF-8');
$min = 3; $min = 3;
if($strLen <= 1) if ($strLen <= 1)
return '*'; return '*';
if($strLen<= $min) if ($strLen <= $min)
return mb_substr($name,0,1,'UTF-8').str_repeat('*',$min-1); return mb_substr($name, 0, 1, 'UTF-8') . str_repeat('*', $min - 1);
else else
return mb_substr($name,0,1,'UTF-8').str_repeat('*',$strLen-1).mb_substr($name,-1,1,'UTF-8'); return mb_substr($name, 0, 1, 'UTF-8') . str_repeat('*', $strLen - 1) . mb_substr($name, -1, 1, 'UTF-8');
} }
/** /**
@ -293,45 +296,45 @@ class UtilService
* @param $card * @param $card
* @return bool * @return bool
*/ */
public static function setCard($card){ public static function setCard($card)
$city = [11=>"北京",12=>"天津",13=>"河北",14=>"山西",15=>"内蒙古",21=>"辽宁",22=>"吉林",23=>"黑龙江 ",31=>"上海",32=>"江苏",33=>"浙江",34=>"安徽",35=>"福建",36=>"江西",37=>"山东",41=>"河南",42=>"湖北 ",43=>"湖南",44=>"广东",45=>"广西",46=>"海南",50=>"重庆",51=>"四川",52=>"贵州",53=>"云南",54=>"西藏 ",61=>"陕西",62=>"甘肃",63=>"青海",64=>"宁夏",65=>"新疆",71=>"台湾",81=>"香港",82=>"澳门",91=>"国外 "]; {
$city = [11 => "北京", 12 => "天津", 13 => "河北", 14 => "山西", 15 => "内蒙古", 21 => "辽宁", 22 => "吉林", 23 => "黑龙江 ", 31 => "上海", 32 => "江苏", 33 => "浙江", 34 => "安徽", 35 => "福建", 36 => "江西", 37 => "山东", 41 => "河南", 42 => "湖北 ", 43 => "湖南", 44 => "广东", 45 => "广西", 46 => "海南", 50 => "重庆", 51 => "四川", 52 => "贵州", 53 => "云南", 54 => "西藏 ", 61 => "陕西", 62 => "甘肃", 63 => "青海", 64 => "宁夏", 65 => "新疆", 71 => "台湾", 81 => "香港", 82 => "澳门", 91 => "国外 "];
$tip = ""; $tip = "";
$match = "/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/"; $match = "/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/";
$pass= true; $pass = true;
if(!$card || !preg_match($match,$card)){ if (!$card || !preg_match($match, $card)) {
//身份证格式错误 //身份证格式错误
$pass = false; $pass = false;
}else if(!$city[substr($card,0,2)]){ } else if (!$city[substr($card, 0, 2)]) {
//地址错误 //地址错误
$pass = false; $pass = false;
}else{ } else {
//18位身份证需要验证最后一位校验位 //18位身份证需要验证最后一位校验位
if(strlen($card) == 18){ if (strlen($card) == 18) {
$card = str_split($card); $card = str_split($card);
//∑(ai×Wi)(mod 11) //∑(ai×Wi)(mod 11)
//加权因子 //加权因子
$factor = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 ]; $factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
//校验位 //校验位
$parity = [ 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 ]; $parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
$sum = 0; $sum = 0;
$ai = 0; $ai = 0;
$wi = 0; $wi = 0;
for ($i = 0; $i < 17; $i++) for ($i = 0; $i < 17; $i++) {
{
$ai = $card[$i]; $ai = $card[$i];
$wi = $factor[$i]; $wi = $factor[$i];
$sum += $ai * $wi; $sum += $ai * $wi;
} }
$last = $parity[$sum % 11]; $last = $parity[$sum % 11];
if($parity[$sum % 11] != $card[17]){ if ($parity[$sum % 11] != $card[17]) {
// $tip = "校验位错误"; // $tip = "校验位错误";
$pass =false; $pass = false;
} }
}else{ } else {
$pass =false; $pass = false;
} }
} }
if(!$pass) return false;/* 身份证格式错误*/ if (!$pass) return false;/* 身份证格式错误*/
return true;/* 身份证格式正确*/ return true;/* 身份证格式正确*/
} }
@ -342,96 +345,97 @@ class UtilService
* @return array|bool|string * @return array|bool|string
* @throws \Exception * @throws \Exception
*/ */
public static function setShareMarketingPoster($data = array(), $path){ public static function setShareMarketingPoster($data = array(), $path)
{
$config = array( $config = array(
'text'=>array( 'text' => array(
array( array(
'text'=>$data['price'],//TODO 价格 'text' => $data['price'],//TODO 价格
'left'=>116, 'left' => 116,
'top'=>200, 'top' => 200,
'fontPath'=>app()->getRootPath().'public/static/font/Alibaba-PuHuiTi-Regular.otf', //字体文件 'fontPath' => app()->getRootPath() . 'public/static/font/Alibaba-PuHuiTi-Regular.otf', //字体文件
'fontSize'=>50, //字号 'fontSize' => 50, //字号
'fontColor'=>'255,0,0', //字体颜色 'fontColor' => '255,0,0', //字体颜色
'angle'=>0, 'angle' => 0,
), ),
array( array(
'text'=>$data['label'],//TODO 标签 'text' => $data['label'],//TODO 标签
'left'=>394, 'left' => 394,
'top'=>190, 'top' => 190,
'fontPath'=>app()->getRootPath().'public/static/font/Alibaba-PuHuiTi-Regular.otf', //字体文件 'fontPath' => app()->getRootPath() . 'public/static/font/Alibaba-PuHuiTi-Regular.otf', //字体文件
'fontSize'=>24, //字号 'fontSize' => 24, //字号
'fontColor'=>'255,255,255', //字体颜色 'fontColor' => '255,255,255', //字体颜色
'angle'=>0, 'angle' => 0,
), ),
array( array(
'text'=>$data['msg'],//TODO 简述 'text' => $data['msg'],//TODO 简述
'left'=>80, 'left' => 80,
'top'=>270, 'top' => 270,
'fontPath'=>app()->getRootPath().'public/static/font/Alibaba-PuHuiTi-Regular.otf', //字体文件 'fontPath' => app()->getRootPath() . 'public/static/font/Alibaba-PuHuiTi-Regular.otf', //字体文件
'fontSize'=>22, //字号 'fontSize' => 22, //字号
'fontColor'=>'40,40,40', //字体颜色 'fontColor' => '40,40,40', //字体颜色
'angle'=>0, 'angle' => 0,
) )
), ),
'image'=>array( 'image' => array(
array( array(
'url'=>$data['image'], //图片 'url' => $data['image'], //图片
'stream'=>0, 'stream' => 0,
'left'=>120, 'left' => 120,
'top'=>340, 'top' => 340,
'right'=>0, 'right' => 0,
'bottom'=>0, 'bottom' => 0,
'width'=>450, 'width' => 450,
'height'=>450, 'height' => 450,
'opacity'=>100 'opacity' => 100
), ),
array( array(
'url'=>$data['url'], //二维码资源 'url' => $data['url'], //二维码资源
'stream'=>0, 'stream' => 0,
'left'=>260, 'left' => 260,
'top'=>890, 'top' => 890,
'right'=>0, 'right' => 0,
'bottom'=>0, 'bottom' => 0,
'width'=>160, 'width' => 160,
'height'=>160, 'height' => 160,
'opacity'=>100 'opacity' => 100
) )
), ),
'background'=>app()->getRootPath().'/public/static/poster/poster.jpg' 'background' => app()->getRootPath() . '/public/static/poster/poster.jpg'
); );
if(!file_exists($config['background'])) exception('缺少系统预设背景图片'); if (!file_exists($config['background'])) exception('缺少系统预设背景图片');
if(strlen($data['title']) < 36){ if (strlen($data['title']) < 36) {
$text = array( $text = array(
'text'=>$data['title'],//TODO 标题 'text' => $data['title'],//TODO 标题
'left'=>76, 'left' => 76,
'top'=>100, 'top' => 100,
'fontPath'=>app()->getRootPath().'public/static/font/Alibaba-PuHuiTi-Regular.otf', //字体文件 'fontPath' => app()->getRootPath() . 'public/static/font/Alibaba-PuHuiTi-Regular.otf', //字体文件
'fontSize'=>32, //字号 'fontSize' => 32, //字号
'fontColor'=>'0,0,0', //字体颜色 'fontColor' => '0,0,0', //字体颜色
'angle'=>0, 'angle' => 0,
); );
array_push($config['text'],$text); array_push($config['text'], $text);
}else{ } else {
$titleOne = array( $titleOne = array(
'text'=>mb_substr($data['title'], 0, 12),//TODO 标题 'text' => mb_substr($data['title'], 0, 12),//TODO 标题
'left'=>76, 'left' => 76,
'top'=>70, 'top' => 70,
'fontPath'=>app()->getRootPath().'public/static/font/Alibaba-PuHuiTi-Regular.otf', //字体文件 'fontPath' => app()->getRootPath() . 'public/static/font/Alibaba-PuHuiTi-Regular.otf', //字体文件
'fontSize'=>32, //字号 'fontSize' => 32, //字号
'fontColor'=>'0,0,0', //字体颜色 'fontColor' => '0,0,0', //字体颜色
'angle'=>0, 'angle' => 0,
); );
$titleTwo = array( $titleTwo = array(
'text'=> mb_substr($data['title'], 12, 12),//TODO 标题 'text' => mb_substr($data['title'], 12, 12),//TODO 标题
'left'=>76, 'left' => 76,
'top'=>120, 'top' => 120,
'fontPath'=>app()->getRootPath().'public/static/font/Alibaba-PuHuiTi-Regular.otf', //字体文件 'fontPath' => app()->getRootPath() . 'public/static/font/Alibaba-PuHuiTi-Regular.otf', //字体文件
'fontSize'=>32, //字号 'fontSize' => 32, //字号
'fontColor'=>'0,0,0', //字体颜色 'fontColor' => '0,0,0', //字体颜色
'angle'=>0, 'angle' => 0,
); );
array_push($config['text'],$titleOne); array_push($config['text'], $titleOne);
array_push($config['text'],$titleTwo); array_push($config['text'], $titleTwo);
} }
return self::setSharePoster($config, $path); return self::setSharePoster($config, $path);
} }
@ -443,70 +447,71 @@ class UtilService
* @return array|bool|string * @return array|bool|string
* @throws \Exception * @throws \Exception
*/ */
public static function setSharePoster($config = array(), $path){ public static function setSharePoster($config = array(), $path)
{
$imageDefault = array( $imageDefault = array(
'left'=>0, 'left' => 0,
'top'=>0, 'top' => 0,
'right'=>0, 'right' => 0,
'bottom'=>0, 'bottom' => 0,
'width'=>100, 'width' => 100,
'height'=>100, 'height' => 100,
'opacity'=>100 'opacity' => 100
); );
$textDefault = array( $textDefault = array(
'text'=>'', 'text' => '',
'left'=>0, 'left' => 0,
'top'=>0, 'top' => 0,
'fontSize'=>32, //字号 'fontSize' => 32, //字号
'fontColor'=>'255,255,255', //字体颜色 'fontColor' => '255,255,255', //字体颜色
'angle'=>0, 'angle' => 0,
); );
$background = $config['background'];//海报最底层得背景 $background = $config['background'];//海报最底层得背景
$backgroundInfo = getimagesize($background); $backgroundInfo = getimagesize($background);
$background = imagecreatefromstring(file_get_contents($background)); $background = imagecreatefromstring(file_get_contents($background));
$backgroundWidth = $backgroundInfo[0]; //背景宽度 $backgroundWidth = $backgroundInfo[0]; //背景宽度
$backgroundHeight = $backgroundInfo[1]; //背景高度 $backgroundHeight = $backgroundInfo[1]; //背景高度
$imageRes = imageCreatetruecolor($backgroundWidth,$backgroundHeight); $imageRes = imageCreatetruecolor($backgroundWidth, $backgroundHeight);
$color = imagecolorallocate($imageRes, 0, 0, 0); $color = imagecolorallocate($imageRes, 0, 0, 0);
imagefill($imageRes, 0, 0, $color); imagefill($imageRes, 0, 0, $color);
imagecopyresampled($imageRes,$background,0,0,0,0,imagesx($background),imagesy($background),imagesx($background),imagesy($background)); imagecopyresampled($imageRes, $background, 0, 0, 0, 0, imagesx($background), imagesy($background), imagesx($background), imagesy($background));
if(!empty($config['image'])){ if (!empty($config['image'])) {
foreach ($config['image'] as $key => $val) { foreach ($config['image'] as $key => $val) {
$val = array_merge($imageDefault,$val); $val = array_merge($imageDefault, $val);
$info = getimagesize($val['url']); $info = getimagesize($val['url']);
$function = 'imagecreatefrom'.image_type_to_extension($info[2], false); $function = 'imagecreatefrom' . image_type_to_extension($info[2], false);
if($val['stream']){ if ($val['stream']) {
$info = getimagesizefromstring($val['url']); $info = getimagesizefromstring($val['url']);
$function = 'imagecreatefromstring'; $function = 'imagecreatefromstring';
} }
$res = $function($val['url']); $res = $function($val['url']);
$resWidth = $info[0]; $resWidth = $info[0];
$resHeight = $info[1]; $resHeight = $info[1];
$canvas=imagecreatetruecolor($val['width'], $val['height']); $canvas = imagecreatetruecolor($val['width'], $val['height']);
imagefill($canvas, 0, 0, $color); imagefill($canvas, 0, 0, $color);
imagecopyresampled($canvas, $res, 0, 0, 0, 0, $val['width'], $val['height'],$resWidth,$resHeight); imagecopyresampled($canvas, $res, 0, 0, 0, 0, $val['width'], $val['height'], $resWidth, $resHeight);
$val['left'] = $val['left']<0?$backgroundWidth- abs($val['left']) - $val['width']:$val['left']; $val['left'] = $val['left'] < 0 ? $backgroundWidth - abs($val['left']) - $val['width'] : $val['left'];
$val['top'] = $val['top']<0?$backgroundHeight- abs($val['top']) - $val['height']:$val['top']; $val['top'] = $val['top'] < 0 ? $backgroundHeight - abs($val['top']) - $val['height'] : $val['top'];
imagecopymerge($imageRes,$canvas, $val['left'],$val['top'],$val['right'],$val['bottom'],$val['width'],$val['height'],$val['opacity']);//左,上,右,下,宽度,高度,透明度 imagecopymerge($imageRes, $canvas, $val['left'], $val['top'], $val['right'], $val['bottom'], $val['width'], $val['height'], $val['opacity']);//左,上,右,下,宽度,高度,透明度
} }
} }
if(isset($config['text']) && !empty($config['text'])){ if (isset($config['text']) && !empty($config['text'])) {
foreach ($config['text'] as $key => $val) { foreach ($config['text'] as $key => $val) {
$val = array_merge($textDefault,$val); $val = array_merge($textDefault, $val);
list($R,$G,$B) = explode(',', $val['fontColor']); list($R, $G, $B) = explode(',', $val['fontColor']);
$fontColor = imagecolorallocate($imageRes, $R, $G, $B); $fontColor = imagecolorallocate($imageRes, $R, $G, $B);
$val['left'] = $val['left']<0?$backgroundWidth- abs($val['left']):$val['left']; $val['left'] = $val['left'] < 0 ? $backgroundWidth - abs($val['left']) : $val['left'];
$val['top'] = $val['top']<0?$backgroundHeight- abs($val['top']):$val['top']; $val['top'] = $val['top'] < 0 ? $backgroundHeight - abs($val['top']) : $val['top'];
imagettftext($imageRes,$val['fontSize'],$val['angle'],$val['left'],$val['top'],$fontColor,$val['fontPath'],$val['text']); imagettftext($imageRes, $val['fontSize'], $val['angle'], $val['left'], $val['top'], $fontColor, $val['fontPath'], $val['text']);
} }
} }
ob_start(); ob_start();
imagejpeg ($imageRes); imagejpeg($imageRes);
imagedestroy($imageRes); imagedestroy($imageRes);
$res = ob_get_contents(); $res = ob_get_contents();
ob_end_clean(); ob_end_clean();
$key = substr(md5(rand(0, 9999)) , 0, 5). date('YmdHis') . rand(0, 999999) . '.jpg'; $key = substr(md5(rand(0, 9999)), 0, 5) . date('YmdHis') . rand(0, 999999) . '.jpg';
return UploadService::getInstance()->setUploadPath($path)->imageStream($key,$res); return UploadService::getInstance()->setUploadPath($path)->imageStream($key, $res);
} }
/* /*
@ -516,7 +521,7 @@ class UtilService
* */ * */
public static function getCurrentController() public static function getCurrentController()
{ {
return strtolower(app('http')->getName().'/'.request()->controller().'/'.request()->action()); return strtolower(app('http')->getName() . '/' . request()->controller() . '/' . request()->action());
} }
/** /**
@ -530,9 +535,9 @@ class UtilService
curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curl); $result = curl_exec($curl);
$result = json_decode($result,true); $result = json_decode($result, true);
if(is_array($result)) return ['status'=>false,'msg'=>$result['errcode'].'---'.$result['errmsg']]; if (is_array($result)) return ['status' => false, 'msg' => $result['errcode'] . '---' . $result['errmsg']];
return ['status'=>true]; return ['status' => true];
} }
/** /**
@ -543,19 +548,22 @@ class UtilService
*/ */
public static function setHttpType($url, $type = 0) public static function setHttpType($url, $type = 0)
{ {
$domainTop = substr($url,0,5); $domainTop = substr($url, 0, 5);
if($type){ if($domainTop == 'https') $url = 'http'.substr($url,5,strlen($url)); } if ($type) {
else{ if($domainTop != 'https') $url = 'https:'.substr($url,5,strlen($url)); } if ($domainTop == 'https') $url = 'http' . substr($url, 5, strlen($url));
} else {
if ($domainTop != 'https') $url = 'https:' . substr($url, 5, strlen($url));
}
return $url; return $url;
} }
public static function setSiteUrl($image, $siteUrl = '') public static function setSiteUrl($image, $siteUrl = '')
{ {
if(!strlen(trim($siteUrl))) $siteUrl = sysConfig('site_url'); if (!strlen(trim($siteUrl))) $siteUrl = sysConfig('site_url');
$domainTop = substr($image,0,4); $domainTop = substr($image, 0, 4);
if($domainTop == 'http') return $image; if ($domainTop == 'http') return $image;
$image = str_replace('\\', '/', $image); $image = str_replace('\\', '/', $image);
return $siteUrl.$image; return $siteUrl . $image;
} }
/** /**
@ -566,16 +574,16 @@ class UtilService
public static function CurlFileExist($url) public static function CurlFileExist($url)
{ {
$ch = curl_init(); $ch = curl_init();
try{ try {
curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 10); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
$contents = curl_exec($ch); $contents = curl_exec($ch);
if (preg_match("/404/", $contents)) return false; if (preg_match("/404/", $contents)) return false;
if (preg_match("/403/", $contents)) return false; if (preg_match("/403/", $contents)) return false;
return true; return true;
}catch (\Exception $e){ } catch (\Exception $e) {
return false; return false;
} }
} }
@ -588,26 +596,26 @@ class UtilService
*/ */
public static function getQRCodePath($url, $name) public static function getQRCodePath($url, $name)
{ {
if(!strlen(trim($url)) || !strlen(trim($name))) return false; if (!strlen(trim($url)) || !strlen(trim($name))) return false;
try{ try {
$uploadType = sysConfig('upload_type'); $uploadType = sysConfig('upload_type');
//TODO 没有选择默认使用本地上传 //TODO 没有选择默认使用本地上传
if (!$uploadType) $uploadType = 1; if (!$uploadType) $uploadType = 1;
$siteUrl = sysConfig('site_url'); $siteUrl = sysConfig('site_url');
if(!$siteUrl) return '请前往后台设置->系统设置->网站域名 填写您的域名格式为http://域名'; if (!$siteUrl) return '请前往后台设置->系统设置->网站域名 填写您的域名格式为http://域名';
$info = []; $info = [];
$outfile = Config::get('qrcode.cache_dir'); $outfile = Config::get('qrcode.cache_dir');
$code = new QRcode(); $code = new QRcode();
$wapCodePath = $code->png($url, $outfile.'/'.$name)->getPath(); //获取二维码生成的地址 $wapCodePath = $code->png($url, $outfile . '/' . $name)->getPath(); //获取二维码生成的地址
$content = file_get_contents('.'.$wapCodePath); $content = file_get_contents('.' . $wapCodePath);
switch ($uploadType) { switch ($uploadType) {
case 1 : case 1 :
$info["code"] = 200; $info["code"] = 200;
$info["name"] = $name; $info["name"] = $name;
$info["dir"] = $wapCodePath; $info["dir"] = $wapCodePath;
$info["time"] = time(); $info["time"] = time();
$headerArray=UploadService::getImageHeaders($siteUrl.$info['dir'],1,false); $headerArray = UploadService::getImageHeaders($siteUrl . $info['dir'], 1, false);
$info['size'] = $headerArray['Content-Length']; $info['size'] = $headerArray['Content-Length'];
$info['type'] = $headerArray['Content-Type']; $info['type'] = $headerArray['Content-Type'];
$info["image_type"] = 1; $info["image_type"] = 1;
@ -620,7 +628,7 @@ class UtilService
if (is_array($item)) { if (is_array($item)) {
$info = Qiniu::imageUrl($item['key']); $info = Qiniu::imageUrl($item['key']);
$info['dir'] = UtilService::setHttpType($info['dir']); $info['dir'] = UtilService::setHttpType($info['dir']);
$headerArray = UploadService::getImageHeaders( $info['dir']); $headerArray = UploadService::getImageHeaders($info['dir']);
$info['size'] = $headerArray['Content-Length']; $info['size'] = $headerArray['Content-Length'];
$info['type'] = $headerArray['Content-Type']; $info['type'] = $headerArray['Content-Type'];
$info['image_type'] = 2; $info['image_type'] = 2;
@ -638,14 +646,14 @@ class UtilService
$serverImageInfo['info']['url'] = UtilService::setHttpType($serverImageInfo['info']['url']); $serverImageInfo['info']['url'] = UtilService::setHttpType($serverImageInfo['info']['url']);
$info['dir'] = $serverImageInfo['info']['url']; $info['dir'] = $serverImageInfo['info']['url'];
$info['thumb_path'] = $serverImageInfo['info']['url']; $info['thumb_path'] = $serverImageInfo['info']['url'];
$headerArray = UploadService::getImageHeaders($serverImageInfo['info']['url'],1,true); $headerArray = UploadService::getImageHeaders($serverImageInfo['info']['url'], 1, true);
$info['size'] = $headerArray['Content-Length']; $info['size'] = $headerArray['Content-Length'];
$info['type'] = $headerArray['Content-Type']; $info['type'] = $headerArray['Content-Type'];
$info['time'] = time(); $info['time'] = time();
$info['image_type'] = 3; $info['image_type'] = 3;
break; break;
case 4 : case 4 :
list($imageUrl,$serverImageInfo) = COS::uploadImageStream($name, $content); list($imageUrl, $serverImageInfo) = COS::uploadImageStream($name, $content);
if (!is_array($serverImageInfo) && !is_object($serverImageInfo)) return $serverImageInfo; if (!is_array($serverImageInfo) && !is_object($serverImageInfo)) return $serverImageInfo;
if (is_object($serverImageInfo)) $serverImageInfo = $serverImageInfo->toArray(); if (is_object($serverImageInfo)) $serverImageInfo = $serverImageInfo->toArray();
$serverImageInfo['ObjectURL'] = $imageUrl; $serverImageInfo['ObjectURL'] = $imageUrl;
@ -653,7 +661,7 @@ class UtilService
$info['name'] = substr(strrchr($serverImageInfo['ObjectURL'], '/'), 1); $info['name'] = substr(strrchr($serverImageInfo['ObjectURL'], '/'), 1);
$info['dir'] = $serverImageInfo['ObjectURL']; $info['dir'] = $serverImageInfo['ObjectURL'];
$info['thumb_path'] = $serverImageInfo['ObjectURL']; $info['thumb_path'] = $serverImageInfo['ObjectURL'];
$headerArray = UploadService::getImageHeaders( $serverImageInfo['ObjectURL'],true); $headerArray = UploadService::getImageHeaders($serverImageInfo['ObjectURL'], true);
$info['size'] = $headerArray['Content-Length']; $info['size'] = $headerArray['Content-Length'];
$info['type'] = $headerArray['Content-Type']; $info['type'] = $headerArray['Content-Type'];
$info['time'] = time(); $info['time'] = time();
@ -663,7 +671,7 @@ class UtilService
return '上传类型错误,请先选择文件上传类型'; return '上传类型错误,请先选择文件上传类型';
} }
return $info; return $info;
}catch (\Exception $e){ } catch (\Exception $e) {
return $e->getMessage(); return $e->getMessage();
} }
} }
@ -673,19 +681,20 @@ class UtilService
* @param string $avatar * @param string $avatar
* @return bool|string * @return bool|string
*/ */
public static function setImageBase64($avatar = '',$timeout=9){ public static function setImageBase64($avatar = '', $timeout = 9)
try{ {
$url=parse_url($avatar); try {
$url=$url['host']; $url = parse_url($avatar);
$url = $url['host'];
$header = [ $header = [
'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:45.0) Gecko/20100101 Firefox/45.0', 'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:45.0) Gecko/20100101 Firefox/45.0',
'Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3', 'Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
'Accept-Encoding: gzip, deflate', 'Accept-Encoding: gzip, deflate',
'Host:'.$url 'Host:' . $url
]; ];
$dir= pathinfo($url); $dir = pathinfo($url);
$host = $dir['dirname']; $host = $dir['dirname'];
$refer= $host.'/'; $refer = $host . '/';
$curl = curl_init(); $curl = curl_init();
curl_setopt($curl, CURLOPT_REFERER, $refer); curl_setopt($curl, CURLOPT_REFERER, $refer);
curl_setopt($curl, CURLOPT_URL, $avatar); curl_setopt($curl, CURLOPT_URL, $avatar);
@ -699,7 +708,7 @@ class UtilService
curl_close($curl); curl_close($curl);
if ($code == 200) return "data:image/jpeg;base64," . base64_encode($data); if ($code == 200) return "data:image/jpeg;base64," . base64_encode($data);
else return false; else return false;
}catch (\Exception $e){ } catch (\Exception $e) {
return false; return false;
} }
} }

View File

@ -593,7 +593,6 @@ class WechatService
$staff = self::staffService(); $staff = self::staffService();
$staff = is_callable($message) ? $staff->message($message()) : $staff->message($message); $staff = is_callable($message) ? $staff->message($message()) : $staff->message($message);
$res = $staff->to($to)->send(); $res = $staff->to($to)->send();
HookService::afterListen('wechat_staff_to',compact('to','message'),$res);
return $res; return $res;
} }

View File

@ -58,10 +58,11 @@ class WechatTemplateService implements ProviderInterface
//砍价成功 //砍价成功
const BARGAIN_SUCCESS = 'OPENTM410292733'; const BARGAIN_SUCCESS = 'OPENTM410292733';
public static function getConstants($code='') { public static function getConstants($code = '')
{
$oClass = new \ReflectionClass(__CLASS__); $oClass = new \ReflectionClass(__CLASS__);
$stants=$oClass->getConstants(); $stants = $oClass->getConstants();
if($code) return isset($stants[$code]) ? $stants[$code] : ''; if ($code) return isset($stants[$code]) ? $stants[$code] : '';
else return $stants; else return $stants;
} }
@ -79,13 +80,13 @@ class WechatTemplateService implements ProviderInterface
* @param string $defaultColor * @param string $defaultColor
* @return bool * @return bool
*/ */
public static function sendTemplate($openid,$templateId,array $data,$url = null,$defaultColor = '') public static function sendTemplate($openid, $templateId, array $data, $url = null, $defaultColor = '')
{ {
$tempid = WechatTemplateModel::where('tempkey',$templateId)->where('status',1)->value('tempid'); $tempid = WechatTemplateModel::where('tempkey', $templateId)->where('status', 1)->value('tempid');
if(!$tempid) return false; if (!$tempid) return false;
try{ try {
return WechatService::sendTemplate($openid,$tempid,$data,$url,$defaultColor); return WechatService::sendTemplate($openid, $tempid, $data, $url, $defaultColor);
}catch (\Exception $e){ } catch (\Exception $e) {
dump($e->getMessage()); dump($e->getMessage());
return false; return false;
} }
@ -97,24 +98,24 @@ class WechatTemplateService implements ProviderInterface
* @param string $defaultColor * @param string $defaultColor
* @return bool * @return bool
*/ */
public static function sendAdminNoticeTemplate(array $data,$url = null,$defaultColor = '') public static function sendAdminNoticeTemplate(array $data, $url = null, $defaultColor = '')
{ {
$adminIds = explode(',',trim(sysConfig('site_store_admin_uids'))); $adminIds = explode(',', trim(sysConfig('site_store_admin_uids')));
$kefuIds = ServiceModel::where('notify',1)->column('uid','uid'); $kefuIds = ServiceModel::where('notify', 1)->column('uid', 'uid');
if(empty($adminIds[0])){ if (empty($adminIds[0])) {
$adminList = array_unique($kefuIds); $adminList = array_unique($kefuIds);
}else{ } else {
$adminList = array_unique(array_merge($adminIds,$kefuIds)); $adminList = array_unique(array_merge($adminIds, $kefuIds));
} }
if(!is_array($adminList) || empty($adminList)) return false; if (!is_array($adminList) || empty($adminList)) return false;
foreach ($adminList as $uid){ foreach ($adminList as $uid) {
try{ try {
$openid = WechatUser::uidToOpenid($uid, 'openid'); $openid = WechatUser::uidToOpenid($uid, 'openid');
if(!$openid) continue; if (!$openid) continue;
}catch (\Exception $e){ } catch (\Exception $e) {
continue; continue;
} }
self::sendTemplate($openid,self::ADMIN_NOTICE,$data,$url,$defaultColor); self::sendTemplate($openid, self::ADMIN_NOTICE, $data, $url, $defaultColor);
} }
} }

View File

@ -3,13 +3,17 @@
namespace crmeb\services; namespace crmeb\services;
use app\models\system\Cache as CacheModel; use app\models\system\Cache as CacheModel;
use crmeb\interfaces\ProviderInterface;
use crmeb\traits\LogicTrait;
/** /**
* Class YLYService * Class YLYService
* @package crmeb\services * @package crmeb\services
*/ */
class YLYService extends HttpService class YLYService extends HttpService implements ProviderInterface
{ {
use LogicTrait;
/** /**
* 开发者创建的应用的应用ID * 开发者创建的应用的应用ID
* @var string * @var string
@ -32,13 +36,13 @@ class YLYService extends HttpService
* 易联云token * 易联云token
* @var null * @var null
*/ */
protected $access_token=null; protected $access_token = null;
/** /**
* 订单编号 * 订单编号
* @var null * @var null
*/ */
protected $order_id=null; protected $order_id = null;
/** /**
* 终端号码 * 终端号码
@ -58,18 +62,18 @@ class YLYService extends HttpService
*/ */
protected $apiUrl = 'https://open-api.10ss.net/'; protected $apiUrl = 'https://open-api.10ss.net/';
/**
* 本类实例化句柄 public function register($congig = [])
* @var {
*/
protected static $instance; }
/** /**
* YLYService constructor. * YLYService constructor.
*/ */
protected function __construct() protected function __construct()
{ {
$system = SystemConfigService::more(['develop_id','printing_api_key','printing_client_id','terminal_number']); $system = SystemConfigService::more(['develop_id', 'printing_api_key', 'printing_client_id', 'terminal_number']);
$this->partner = $system['develop_id'] ?? ''; $this->partner = $system['develop_id'] ?? '';
$this->apiKey = $system['printing_api_key'] ?? ''; $this->apiKey = $system['printing_api_key'] ?? '';
$this->client_id = $system['printing_client_id'] ?? ''; $this->client_id = $system['printing_client_id'] ?? '';
@ -77,36 +81,27 @@ class YLYService extends HttpService
$this->getAccessToken(); $this->getAccessToken();
} }
/**
* 实例化本类
* @return YLYService
*/
public static function getInstance()
{
if(is_null(self::$instance)) self::$instance = new self();
return self::$instance;
}
/** /**
* 获取AccessToken * 获取AccessToken
* */ * */
protected function getAccessToken(){ protected function getAccessToken()
{
$token = CacheModel::getDbCache('YLY_access_token'); $token = CacheModel::getDbCache('YLY_access_token');
if(!$token){ if (!$token) {
$request = self::postRequest($this->apiUrl.'oauth/oauth',[ $request = self::postRequest($this->apiUrl . 'oauth/oauth', [
'client_id' => $this->client_id, 'client_id' => $this->client_id,
'grant_type'=> 'client_credentials', 'grant_type' => 'client_credentials',
'sign' => strtolower(md5($this->client_id.time().$this->apiKey)), 'sign' => strtolower(md5($this->client_id . time() . $this->apiKey)),
'scope' => 'all', 'scope' => 'all',
'timestamp' => time(), 'timestamp' => time(),
'id' => $this->createUuid(), 'id' => $this->createUuid(),
]); ]);
$request = json_decode($request,true); $request = json_decode($request, true);
$request['error'] = $request['error'] ?? 0; $request['error'] = $request['error'] ?? 0;
$request['error_description'] = $request['error_description'] ?? ''; $request['error_description'] = $request['error_description'] ?? '';
if($request['error'] == 0 && $request['error_description'] == 'success'){ if ($request['error'] == 0 && $request['error_description'] == 'success') {
$token = $request['body']['access_token'] ?? ''; $token = $request['body']['access_token'] ?? '';
CacheModel::setDbCache('YLY_access_token',$token); CacheModel::setDbCache('YLY_access_token', $token);
} }
} }
$this->access_token = $token; $this->access_token = $token;
@ -116,9 +111,10 @@ class YLYService extends HttpService
* 生成UUID4 * 生成UUID4
* @return string * @return string
*/ */
protected function createUuid() { protected function createUuid()
return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',mt_rand( 0, 0xffff ),mt_rand( 0, 0xffff ),mt_rand( 0, 0xffff ), {
mt_rand( 0, 0x0fff )|0x4000,mt_rand( 0, 0x3fff )|0x8000,mt_rand( 0, 0xffff ),mt_rand( 0, 0xffff ),mt_rand( 0, 0xffff )); return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x', mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff),
mt_rand(0, 0x0fff) | 0x4000, mt_rand(0, 0x3fff) | 0x8000, mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff));
} }
/** /**
@ -129,18 +125,18 @@ class YLYService extends HttpService
*/ */
public function orderPrinting(string $order_id = '') public function orderPrinting(string $order_id = '')
{ {
$request=self::postRequest($this->apiUrl.'print/index',[ $request = self::postRequest($this->apiUrl . 'print/index', [
'client_id' => $this->client_id, 'client_id' => $this->client_id,
'access_token' => $this->access_token, 'access_token' => $this->access_token,
'machine_code' => $this->terminal, 'machine_code' => $this->terminal,
'content' => $this->content, 'content' => $this->content,
'origin_id' => $order_id ? $order_id : $this->order_id, 'origin_id' => $order_id ? $order_id : $this->order_id,
'sign' => strtolower(md5($this->client_id.time().$this->apiKey)), 'sign' => strtolower(md5($this->client_id . time() . $this->apiKey)),
'id' => $this->createUuid(), 'id' => $this->createUuid(),
'timestamp' => time() 'timestamp' => time()
]); ]);
if($request === false) return false; if ($request === false) return false;
return json_decode($request,true); return json_decode($request, true);
} }
/** /**
@ -150,16 +146,16 @@ class YLYService extends HttpService
*/ */
public function deletePrinter($machine_code) public function deletePrinter($machine_code)
{ {
$request = self::postRequest($this->apiUrl.'printer/deleteprinter',[ $request = self::postRequest($this->apiUrl . 'printer/deleteprinter', [
'client_id' => $this->client_id, 'client_id' => $this->client_id,
'access_token' => $this->access_token, 'access_token' => $this->access_token,
'machine_code' => $machine_code, 'machine_code' => $machine_code,
'sign' => strtolower(md5($this->client_id.time().$this->apiKey)), 'sign' => strtolower(md5($this->client_id . time() . $this->apiKey)),
'id' => $this->createUuid(), 'id' => $this->createUuid(),
'timestamp' => time(), 'timestamp' => time(),
]); ]);
if($request === false) return false; if ($request === false) return false;
return json_decode($request,true); return json_decode($request, true);
} }
/** /**
@ -169,18 +165,19 @@ class YLYService extends HttpService
* @param array $product 订单详情 * @param array $product 订单详情
* @return $this * @return $this
*/ */
public function setContent(string $name,array $orderInfo,array $product){ public function setContent(string $name, array $orderInfo, array $product)
$timeYmd = date('Y-m-d',time()); {
$timeHis = date('H:i:s',time()); $timeYmd = date('Y-m-d', time());
$timeHis = date('H:i:s', time());
$goodsStr = '<table><tr><td>商品名称</td><td>数量</td><td>单价</td><td>金额</td></tr>'; $goodsStr = '<table><tr><td>商品名称</td><td>数量</td><td>单价</td><td>金额</td></tr>';
foreach ($product as $item){ foreach ($product as $item) {
$goodsStr.='<tr>'; $goodsStr .= '<tr>';
$goodsStr.="<td>{$item['productInfo']['store_name']}</td><td>{$item['cart_num']}</td><td>{$item['productInfo']['price']}</td><td>{$item['truePrice']}</td>"; $goodsStr .= "<td>{$item['productInfo']['store_name']}</td><td>{$item['cart_num']}</td><td>{$item['productInfo']['price']}</td><td>{$item['truePrice']}</td>";
$goodsStr.='</tr>'; $goodsStr .= '</tr>';
} }
$goodsStr.='</table>'; $goodsStr .= '</table>';
$this->order_id = $orderInfo['order_id']; $this->order_id = $orderInfo['order_id'];
$count=<<<CONTENT $count = <<<CONTENT
<FB><center> ** {$name} **</center></FB> <FB><center> ** {$name} **</center></FB>
<FH2><FW2>----------------</FW2></FH2> <FH2><FW2>----------------</FW2></FH2>
订单编号:{$orderInfo['order_id']}\r 订单编号:{$orderInfo['order_id']}\r
@ -212,8 +209,8 @@ CONTENT;
return $this->content; return $this->content;
} }
protected function __clone() protected function __destruct()
{ {
// TODO: Implement __clone() method. // TODO: Implement __destruct() method.
} }
} }

View File

@ -1,4 +1,5 @@
<?php <?php
namespace crmeb\services\storage; namespace crmeb\services\storage;
use crmeb\services\SystemConfigService; use crmeb\services\SystemConfigService;
@ -32,34 +33,35 @@ class COS
* @return null|Client * @return null|Client
* @throws \Exception * @throws \Exception
*/ */
protected static function autoInfo(){ protected static function autoInfo()
if(($storageRegion = Cache::get('storageRegion')) && ($storageName = Cache::get('storageName')) && ($uploadUrl = Cache::get('uploadUrl')) && ($accessKey = Cache::get('accessKey')) && ($secretKey = Cache::get('secretKey'))){ {
if (($storageRegion = Cache::get('storageRegion')) && ($storageName = Cache::get('storageName')) && ($uploadUrl = Cache::get('uploadUrl')) && ($accessKey = Cache::get('accessKey')) && ($secretKey = Cache::get('secretKey'))) {
self::$accessKey = $accessKey; self::$accessKey = $accessKey;
self::$secretKey = $secretKey; self::$secretKey = $secretKey;
self::$uploadUrl = $uploadUrl; self::$uploadUrl = $uploadUrl;
self::$storageName = $storageName; self::$storageName = $storageName;
self::$storageRegion = $storageRegion; self::$storageRegion = $storageRegion;
}else{ } else {
self::$accessKey = trim(sysConfig('accessKey')); self::$accessKey = trim(sysConfig('accessKey'));
self::$secretKey = trim(sysConfig('secretKey')); self::$secretKey = trim(sysConfig('secretKey'));
self::$uploadUrl = trim(sysConfig('uploadUrl')).'/'; self::$uploadUrl = trim(sysConfig('uploadUrl')) . '/';
self::$storageName = trim(sysConfig('storage_name')); self::$storageName = trim(sysConfig('storage_name'));
self::$storageRegion = trim(sysConfig('storage_region')); self::$storageRegion = trim(sysConfig('storage_region'));
Cache::set('accessKey',self::$accessKey); Cache::set('accessKey', self::$accessKey);
Cache::set('secretKey',self::$secretKey); Cache::set('secretKey', self::$secretKey);
Cache::set('uploadUrl',self::$uploadUrl); Cache::set('uploadUrl', self::$uploadUrl);
Cache::set('storageName',self::$storageName); Cache::set('storageName', self::$storageName);
Cache::set('storageRegion',self::$storageRegion); Cache::set('storageRegion', self::$storageRegion);
} }
if(!self::$accessKey || !self::$secretKey || !self::$uploadUrl || !self::$storageName){ if (!self::$accessKey || !self::$secretKey || !self::$uploadUrl || !self::$storageName) {
exception('请设置 secretKey 和 accessKey 和 空间域名 和 存储空间名称'); exception('请设置 secretKey 和 accessKey 和 空间域名 和 存储空间名称');
} }
if(self::$auth == null) { if (self::$auth == null) {
self::$auth = new Client([ self::$auth = new Client([
'region'=>self::$storageRegion, 'region' => self::$storageRegion,
'credentials'=>[ 'credentials' => [
'secretId'=>self::$accessKey, 'secretId' => self::$accessKey,
'secretKey'=>self::$secretKey, 'secretKey' => self::$secretKey,
] ]
]); ]);
} }
@ -71,21 +73,22 @@ class COS
* @param string $filename * @param string $filename
* @return string * @return string
*/ */
public static function uploadImage($filename = 'image'){ public static function uploadImage($filename = 'image')
{
$request = app('request'); $request = app('request');
$file = $request->file($filename); $file = $request->file($filename);
$filePath = $file->getRealPath(); $filePath = $file->getRealPath();
$ext = $file->getOriginalExtension(); $ext = $file->getOriginalExtension();
$key = substr(md5($file->getRealPath()) , 0, 5). date('YmdHis') . rand(0, 9999) . '.' . $ext; $key = substr(md5($file->getRealPath()), 0, 5) . date('YmdHis') . rand(0, 9999) . '.' . $ext;
try { try {
self::autoInfo(); self::autoInfo();
return [self::$uploadUrl.$key,self::$auth->putObject([ return [self::$uploadUrl . $key, self::$auth->putObject([
'Bucket' => self::$storageName, 'Bucket' => self::$storageName,
'Key' => $key, 'Key' => $key,
'Body' => fopen($filePath, 'rb') 'Body' => fopen($filePath, 'rb')
])]; ])];
} catch (\Exception $e) { } catch (\Exception $e) {
return [false,$e->getMessage()]; return [false, $e->getMessage()];
} }
} }
@ -95,16 +98,17 @@ class COS
* @param $content * @param $content
* @return string * @return string
*/ */
public static function uploadImageStream($key, $content){ public static function uploadImageStream($key, $content)
{
try { try {
self::autoInfo(); self::autoInfo();
return [self::$uploadUrl.$key,self::$auth->putObject([ return [self::$uploadUrl . $key, self::$auth->putObject([
'Bucket' => self::$storageName, 'Bucket' => self::$storageName,
'Key' => $key, 'Key' => $key,
'Body' => $content 'Body' => $content
])]; ])];
} catch (\Exception $e) { } catch (\Exception $e) {
return [false,$e->getMessage()]; return [false, $e->getMessage()];
} }
} }
@ -113,7 +117,8 @@ class COS
* @param $key * @param $key
* @return mixed * @return mixed
*/ */
public static function delete($key){ public static function delete($key)
{
try { try {
self::autoInfo(); self::autoInfo();
return self::$auth->deleteObject([ return self::$auth->deleteObject([

View File

@ -1,4 +1,5 @@
<?php <?php
namespace crmeb\services\storage; namespace crmeb\services\storage;
use crmeb\services\SystemConfigService; use crmeb\services\SystemConfigService;
@ -30,28 +31,29 @@ class OSS
* @return null|OssClient * @return null|OssClient
* @throws \OSS\Core\OssException * @throws \OSS\Core\OssException
*/ */
protected static function autoInfo(){ protected static function autoInfo()
if(($storageName = Cache::get('storageName')) && ($uploadUrl = Cache::get('uploadUrl')) && ($accessKey = Cache::get('accessKey')) && ($secretKey = Cache::get('secretKey'))){ {
if (($storageName = Cache::get('storageName')) && ($uploadUrl = Cache::get('uploadUrl')) && ($accessKey = Cache::get('accessKey')) && ($secretKey = Cache::get('secretKey'))) {
self::$accessKey = $accessKey; self::$accessKey = $accessKey;
self::$secretKey = $secretKey; self::$secretKey = $secretKey;
self::$uploadUrl = $uploadUrl; self::$uploadUrl = $uploadUrl;
self::$storageName = $storageName; self::$storageName = $storageName;
}else{ } else {
self::$accessKey = trim(sysConfig('accessKey')); self::$accessKey = trim(sysConfig('accessKey'));
self::$secretKey = trim(sysConfig('secretKey')); self::$secretKey = trim(sysConfig('secretKey'));
self::$uploadUrl = trim(sysConfig('uploadUrl')).'/'; self::$uploadUrl = trim(sysConfig('uploadUrl')) . '/';
self::$storageName = trim(sysConfig('storage_name')); self::$storageName = trim(sysConfig('storage_name'));
Cache::set('accessKey',self::$accessKey); Cache::set('accessKey', self::$accessKey);
Cache::set('secretKey',self::$secretKey); Cache::set('secretKey', self::$secretKey);
Cache::set('uploadUrl',self::$uploadUrl); Cache::set('uploadUrl', self::$uploadUrl);
Cache::set('storageName',self::$storageName); Cache::set('storageName', self::$storageName);
} }
if(!self::$accessKey || !self::$secretKey || !self::$uploadUrl || !self::$storageName){ if (!self::$accessKey || !self::$secretKey || !self::$uploadUrl || !self::$storageName) {
exception('请设置 secretKey 和 accessKey 和 空间域名 和 存储空间名称'); exception('请设置 secretKey 和 accessKey 和 空间域名 和 存储空间名称');
} }
if(self::$auth == null) { if (self::$auth == null) {
self::$auth = new OssClient(self::$accessKey,self::$secretKey,self::$uploadUrl); self::$auth = new OssClient(self::$accessKey, self::$secretKey, self::$uploadUrl);
if(!self::$auth->doesBucketExist(self::$storageName)) self::$auth->createBucket(self::$storageName,self::$auth::OSS_ACL_TYPE_PUBLIC_READ_WRITE); if (!self::$auth->doesBucketExist(self::$storageName)) self::$auth->createBucket(self::$storageName, self::$auth::OSS_ACL_TYPE_PUBLIC_READ_WRITE);
} }
return self::$auth; return self::$auth;
} }
@ -61,16 +63,17 @@ class OSS
* @param string $filename * @param string $filename
* @return string * @return string
*/ */
public static function uploadImage($filename = 'image'){ public static function uploadImage($filename = 'image')
{
$request = app('request'); $request = app('request');
$file = $request->file($filename); $file = $request->file($filename);
$filePath = $file->getRealPath(); $filePath = $file->getRealPath();
$ext = $file->getOriginalExtension(); $ext = $file->getOriginalExtension();
$key = substr(md5($file->getRealPath()) , 0, 5). date('YmdHis') . rand(0, 9999) . '.' . $ext; $key = substr(md5($file->getRealPath()), 0, 5) . date('YmdHis') . rand(0, 9999) . '.' . $ext;
try{ try {
self::autoInfo(); self::autoInfo();
return self::$auth->uploadFile(self::$storageName,$key,$filePath); return self::$auth->uploadFile(self::$storageName, $key, $filePath);
}catch (OssException $e){ } catch (OssException $e) {
return $e->getMessage(); return $e->getMessage();
} }
} }
@ -81,11 +84,12 @@ class OSS
* @param $content * @param $content
* @return string * @return string
*/ */
public static function uploadImageStream($key, $content){ public static function uploadImageStream($key, $content)
try{ {
try {
self::autoInfo(); self::autoInfo();
return self::$auth->putObject(self::$storageName,$key,$content); return self::$auth->putObject(self::$storageName, $key, $content);
}catch (OssException $e){ } catch (OssException $e) {
return $e->getMessage(); return $e->getMessage();
} }
} }
@ -95,10 +99,11 @@ class OSS
* @param $key * @param $key
* @return mixed * @return mixed
*/ */
public static function delete($key){ public static function delete($key)
{
try { try {
self::autoInfo(); self::autoInfo();
return self::$auth->deleteObject(self::$storageName,$key); return self::$auth->deleteObject(self::$storageName, $key);
} catch (OssException $e) { } catch (OssException $e) {
return $e->getMessage(); return $e->getMessage();
} }

View File

@ -1,4 +1,5 @@
<?php <?php
namespace crmeb\services\storage; namespace crmeb\services\storage;
use crmeb\services\SystemConfigService; use crmeb\services\SystemConfigService;
@ -28,32 +29,32 @@ class Qiniu
protected static $storageName; protected static $storageName;
/** /**
* TODO 初始化 * TODO 初始化
* @return null|Auth * @return null|Auth
* @throws \Exception * @throws \Exception
*/ */
protected static function autoInfo(){ protected static function autoInfo()
if(($storageName = Cache::get('storageName')) && ($uploadUrl = Cache::get('uploadUrl')) && ($accessKey = Cache::get('accessKey')) && ($secretKey = Cache::get('secretKey'))){ {
if (($storageName = Cache::get('storageName')) && ($uploadUrl = Cache::get('uploadUrl')) && ($accessKey = Cache::get('accessKey')) && ($secretKey = Cache::get('secretKey'))) {
self::$accessKey = $accessKey; self::$accessKey = $accessKey;
self::$secretKey = $secretKey; self::$secretKey = $secretKey;
self::$uploadUrl = $uploadUrl; self::$uploadUrl = $uploadUrl;
self::$storageName = $storageName; self::$storageName = $storageName;
}else{ } else {
self::$accessKey = trim(sysConfig('accessKey')); self::$accessKey = trim(sysConfig('accessKey'));
self::$secretKey = trim(sysConfig('secretKey')); self::$secretKey = trim(sysConfig('secretKey'));
self::$uploadUrl = trim(sysConfig('uploadUrl')).'/'; self::$uploadUrl = trim(sysConfig('uploadUrl')) . '/';
self::$storageName = trim(sysConfig('storage_name')); self::$storageName = trim(sysConfig('storage_name'));
Cache::set('accessKey',self::$accessKey); Cache::set('accessKey', self::$accessKey);
Cache::set('secretKey',self::$secretKey); Cache::set('secretKey', self::$secretKey);
Cache::set('uploadUrl',self::$uploadUrl); Cache::set('uploadUrl', self::$uploadUrl);
Cache::set('storageName',self::$storageName); Cache::set('storageName', self::$storageName);
} }
if(!self::$accessKey || !self::$secretKey || !self::$uploadUrl || !self::$storageName){ if (!self::$accessKey || !self::$secretKey || !self::$uploadUrl || !self::$storageName) {
exception('请设置 secretKey 和 accessKey 和 空间域名 和 存储空间名称'); exception('请设置 secretKey 和 accessKey 和 空间域名 和 存储空间名称');
} }
if(self::$auth == null) self::$auth = new Auth(self::$accessKey,self::$secretKey); if (self::$auth == null) self::$auth = new Auth(self::$accessKey, self::$secretKey);
return self::$auth; return self::$auth;
} }
@ -61,11 +62,12 @@ class Qiniu
* TODO 获取上传图片视频token和domain * TODO 获取上传图片视频token和domain
* @return array * @return array
*/ */
public static function getToKenAndDomainI(){ public static function getToKenAndDomainI()
{
$token = self::autoInfo()->uploadToken(self::$storageName); $token = self::autoInfo()->uploadToken(self::$storageName);
$domain = self::$uploadUrl; $domain = self::$uploadUrl;
$fileName = md5(rand(1000,9999). date('YmdHis') . rand(0, 9999)); $fileName = md5(rand(1000, 9999) . date('YmdHis') . rand(0, 9999));
return compact('token','domain','fileName'); return compact('token', 'domain', 'fileName');
} }
/** /**
@ -74,17 +76,18 @@ class Qiniu
* @return array * @return array
* @throws \Exception * @throws \Exception
*/ */
public static function uploadImage($filename = 'image'){ public static function uploadImage($filename = 'image')
{
$request = app('request'); $request = app('request');
$file = $request->file($filename); $file = $request->file($filename);
$filePath = $file->getRealPath(); $filePath = $file->getRealPath();
$ext = $file->getOriginalExtension(); $ext = $file->getOriginalExtension();
$key = substr(md5($file->getRealPath()) , 0, 5). date('YmdHis') . rand(0, 9999) . '.' . $ext; $key = substr(md5($file->getRealPath()), 0, 5) . date('YmdHis') . rand(0, 9999) . '.' . $ext;
$token = self::autoInfo()->uploadToken(self::$storageName); $token = self::autoInfo()->uploadToken(self::$storageName);
try{ try {
$uploadMgr = new UploadManager(); $uploadMgr = new UploadManager();
return $uploadMgr->putFile($token, $key, $filePath); return $uploadMgr->putFile($token, $key, $filePath);
}catch (\Exception $e){ } catch (\Exception $e) {
return $e->getMessage(); return $e->getMessage();
} }
} }
@ -96,12 +99,13 @@ class Qiniu
* @return array|string * @return array|string
* @throws \Exception * @throws \Exception
*/ */
public static function uploadImageStream($key, $content){ public static function uploadImageStream($key, $content)
{
$token = self::autoInfo()->uploadToken(self::$storageName, $key); $token = self::autoInfo()->uploadToken(self::$storageName, $key);
try{ try {
$uploadMgr = new UploadManager(); $uploadMgr = new UploadManager();
return $uploadMgr->put($token, $key, $content); return $uploadMgr->put($token, $key, $content);
}catch (\Exception $e){ } catch (\Exception $e) {
return $e->getMessage(); return $e->getMessage();
} }
} }
@ -114,8 +118,9 @@ class Qiniu
* @param int $time 图片链接最后的访问时间 * @param int $time 图片链接最后的访问时间
* @return array * @return array
*/ */
public static function imageUrl($key, $type = '', $imageUrl = '', $time = 0){ public static function imageUrl($key, $type = '', $imageUrl = '', $time = 0)
return ['code'=>200,'name'=>$key,'dir'=>self::$uploadUrl.$key,'thumb_path'=>self::$uploadUrl.$key,'time'=>time()]; {
return ['code' => 200, 'name' => $key, 'dir' => self::$uploadUrl . $key, 'thumb_path' => self::$uploadUrl . $key, 'time' => time()];
// $imageValue = !strlen(trim($type)) ? self::$uploadUrl.$key : self::$uploadUrl.$key.self::getType($type); // $imageValue = !strlen(trim($type)) ? self::$uploadUrl.$key : self::$uploadUrl.$key.self::getType($type);
// if($time > time() && !strlen(trim($imageUrl))) return ['code'=>100,'dir'=>$imageUrl,'thumb_path'=>$imageUrl,'time'=>$time]; // if($time > time() && !strlen(trim($imageUrl))) return ['code'=>100,'dir'=>$imageUrl,'thumb_path'=>$imageUrl,'time'=>$time];
// $imageUrl = self::autoInfo()->privateDownloadUrl($imageValue); // $imageUrl = self::autoInfo()->privateDownloadUrl($imageValue);
@ -127,11 +132,12 @@ class Qiniu
* @param $imageType * @param $imageType
* @return string * @return string
*/ */
public static function getType($imageType){ public static function getType($imageType)
{
$type = ''; $type = '';
switch ($imageType){ switch ($imageType) {
case "8x6": case "8x6":
$type='?imageView2/1/w/800/h/600'; $type = '?imageView2/1/w/800/h/600';
break; break;
} }
return $type; return $type;
@ -143,8 +149,9 @@ class Qiniu
* @param $bucket * @param $bucket
* @return mixed * @return mixed
*/ */
public static function delete($key){ public static function delete($key)
$bucketManager = new BucketManager(self::autoInfo(),new Config()); {
$bucketManager = new BucketManager(self::autoInfo(), new Config());
return $bucketManager->delete(self::$storageName, $key); return $bucketManager->delete(self::$storageName, $key);
} }
} }

View File

@ -25,7 +25,7 @@ class WorkermanHandle
]); ]);
} }
$session = app('session',[],true); $session = app('session', [], true);
$session->setId($sessionId); $session->setId($sessionId);
$session->init(); $session->init();

View File

@ -1,7 +1,9 @@
<?php <?php
namespace crmeb\subscribes; namespace crmeb\subscribes;
use think\facade\Db; use think\facade\Db;
/** /**
* 素材消息事件 * 素材消息事件
* Class MaterialSubscribe * Class MaterialSubscribe
@ -21,7 +23,7 @@ class MaterialSubscribe
*/ */
public function onWechatMaterialAfter($event) public function onWechatMaterialAfter($event)
{ {
list($data,$type) = $event; list($data, $type) = $event;
$data['type'] = $type; $data['type'] = $type;
$data['add_time'] = time(); $data['add_time'] = time();
$data['temporary'] = 0; $data['temporary'] = 0;

View File

@ -1,4 +1,5 @@
<?php <?php
namespace crmeb\subscribes; namespace crmeb\subscribes;
use app\admin\model\wechat\WechatMessage; use app\admin\model\wechat\WechatMessage;
@ -31,18 +32,19 @@ class MessageSubscribe
*/ */
public function onAdminNewPush($event) public function onAdminNewPush($event)
{ {
try{ try {
$data['ordernum'] = StoreOrder::where('paid',1)->where('status',0) $data['ordernum'] = StoreOrder::where('paid', 1)->where('status', 0)
->where('shipping_type',1)->where('refund_status',0) ->where('shipping_type', 1)->where('refund_status', 0)
->where('is_del',0)->count(); ->where('is_del', 0)->count();
$store_stock = sysConfig('store_stock'); $store_stock = sysConfig('store_stock');
if($store_stock < 0) $store_stock = 2; if ($store_stock < 0) $store_stock = 2;
$data['inventory'] = StoreProduct::where('stock','<=',$store_stock)->where('is_show',1)->where('is_del',0)->count();//库存 $data['inventory'] = StoreProduct::where('stock', '<=', $store_stock)->where('is_show', 1)->where('is_del', 0)->count();//库存
$data['commentnum'] = StoreProductReply::where('is_reply',0)->count(); $data['commentnum'] = StoreProductReply::where('is_reply', 0)->count();
$data['reflectnum'] = UserExtract::where('status',0)->count();//提现 $data['reflectnum'] = UserExtract::where('status', 0)->count();//提现
$data['msgcount'] = intval($data['ordernum']) + intval($data['inventory']) + intval($data['commentnum']) + intval($data['reflectnum']); $data['msgcount'] = intval($data['ordernum']) + intval($data['inventory']) + intval($data['commentnum']) + intval($data['reflectnum']);
ChannelService::instance()->send('ADMIN_NEW_PUSH',$data); ChannelService::instance()->send('ADMIN_NEW_PUSH', $data);
}catch (\Exception $e){} } catch (\Exception $e) {
}
} }
/** /**
@ -55,10 +57,10 @@ class MessageSubscribe
WechatUser::saveUser($message->FromUserName); WechatUser::saveUser($message->FromUserName);
$event = isset($message->Event) ? $event = isset($message->Event) ?
$message->MsgType.( $message->MsgType . (
$message->Event == 'subscribe' && isset($message->EventKey) ? '_scan' : '' $message->Event == 'subscribe' && isset($message->EventKey) ? '_scan' : ''
).'_'.$message->Event : $message->MsgType; ) . '_' . $message->Event : $message->MsgType;
WechatMessage::setMessage(json_encode($message),$message->FromUserName,strtolower($event)); WechatMessage::setMessage(json_encode($message), $message->FromUserName, strtolower($event));
} }
/** /**
@ -86,21 +88,22 @@ class MessageSubscribe
public function onShortMssageSend($event) public function onShortMssageSend($event)
{ {
//$actions 可为数组 //$actions 可为数组
list($order_id,$actions) = $event; list($order_id, $actions) = $event;
try{ try {
if(is_array($actions)){ if (is_array($actions)) {
foreach ($actions as $action){ foreach ($actions as $action) {
$actionName = 'MssageSend'.$action; $actionName = 'MssageSend' . $action;
if(method_exists($this,$actionName)) $this->$actionName($order_id); if (method_exists($this, $actionName)) $this->$actionName($order_id);
} }
}else{ } else {
$actionName = 'MssageSend'.$actions; $actionName = 'MssageSend' . $actions;
if(method_exists($this,$actionName)) $this->$actionName($order_id); if (method_exists($this, $actionName)) $this->$actionName($order_id);
} }
}catch (\Exception $e){ } catch (\Exception $e) {
Log::error('短信下发事件发生系统错误,错误原因:'.$e->getMessage()); Log::error('短信下发事件发生系统错误,错误原因:' . $e->getMessage());
} }
} }
/** /**
* 发送短信 * 发送短信
* @param boolean $switch 发送开关 * @param boolean $switch 发送开关
@ -109,9 +112,9 @@ class MessageSubscribe
* @param int $template 模板编号 * @param int $template 模板编号
* @param string $logMsg 错误日志记录 * @param string $logMsg 错误日志记录
*/ */
public function send($switch,$phone,array $data,$template,$logMsg='') public function send($switch, $phone, array $data, $template, $logMsg = '')
{ {
if($switch && $phone){ if ($switch && $phone) {
$template = SMSService::getConstants($template); $template = SMSService::getConstants($template);
$res = SMSService::send($phone, $template, $data); $res = SMSService::send($phone, $template, $data);
if ($res['status'] == 400) Log::info($logMsg); if ($res['status'] == 400) Log::info($logMsg);
@ -124,12 +127,12 @@ class MessageSubscribe
*/ */
public function MssageSendPaySuccess($order_id) public function MssageSendPaySuccess($order_id)
{ {
$storeInfo = StoreOrder::where(['order_id'=>$order_id,'paid'=>1,'refund_status'=>0])->find(); $storeInfo = StoreOrder::where(['order_id' => $order_id, 'paid' => 1, 'refund_status' => 0])->find();
if(!$storeInfo) return; if (!$storeInfo) return;
$switch = sysConfig('lower_order_switch') ? true : false; $switch = sysConfig('lower_order_switch') ? true : false;
//模板变量 //模板变量
$pay_price = $storeInfo->pay_price; $pay_price = $storeInfo->pay_price;
$this->send($switch,$storeInfo->user_phone,compact('order_id','pay_price'),'PAY_SUCCESS_CODE','用户支付成功发送短信失败,订单号为:'.$order_id); $this->send($switch, $storeInfo->user_phone, compact('order_id', 'pay_price'), 'PAY_SUCCESS_CODE', '用户支付成功发送短信失败,订单号为:' . $order_id);
} }
/** /**
@ -138,13 +141,13 @@ class MessageSubscribe
*/ */
public function MssageSendDeliver($order_id) public function MssageSendDeliver($order_id)
{ {
$storeInfo = StoreOrder::where(['order_id'=>$order_id,'paid'=>1,'refund_status'=>0,'status'=>1])->find(); $storeInfo = StoreOrder::where(['order_id' => $order_id, 'paid' => 1, 'refund_status' => 0, 'status' => 1])->find();
if(!$storeInfo) return; if (!$storeInfo) return;
$switch = sysConfig('deliver_goods_switch') ? true : false; $switch = sysConfig('deliver_goods_switch') ? true : false;
//模板变量 //模板变量
$nickname = User::where('uid',$storeInfo->uid)->value('nickname'); $nickname = User::where('uid', $storeInfo->uid)->value('nickname');
$store_name = StoreOrder::getProductTitle($storeInfo->cart_id); $store_name = StoreOrder::getProductTitle($storeInfo->cart_id);
$this->send($switch,$storeInfo->user_phone,compact('order_id','store_name','nickname'),'DELIVER_GOODS_CODE','用户发货发送短信失败,订单号为:'.$order_id); $this->send($switch, $storeInfo->user_phone, compact('order_id', 'store_name', 'nickname'), 'DELIVER_GOODS_CODE', '用户发货发送短信失败,订单号为:' . $order_id);
} }
/** /**
@ -153,12 +156,12 @@ class MessageSubscribe
*/ */
public function MssageSendReceiving($order_id) public function MssageSendReceiving($order_id)
{ {
$storeInfo = StoreOrder::where(['order_id'=>$order_id,'paid'=>1,'refund_status'=>0,'status'=>2])->find(); $storeInfo = StoreOrder::where(['order_id' => $order_id, 'paid' => 1, 'refund_status' => 0, 'status' => 2])->find();
if(!$storeInfo) return; if (!$storeInfo) return;
$switch = sysConfig('confirm_take_over_switch') ? true : false; $switch = sysConfig('confirm_take_over_switch') ? true : false;
//模板变量 //模板变量
$store_name = StoreOrder::getProductTitle($storeInfo->cart_id); $store_name = StoreOrder::getProductTitle($storeInfo->cart_id);
$this->send($switch,$storeInfo->user_phone,compact('store_name','order_id'),'TAKE_DELIVERY_CODE','用户确认收货发送短信失败,订单号为:'.$order_id); $this->send($switch, $storeInfo->user_phone, compact('store_name', 'order_id'), 'TAKE_DELIVERY_CODE', '用户确认收货发送短信失败,订单号为:' . $order_id);
} }
/** /**
@ -167,14 +170,14 @@ class MessageSubscribe
*/ */
public function MssageSendAdminPlaceAnOrder($order_id) public function MssageSendAdminPlaceAnOrder($order_id)
{ {
$storeInfo = StoreOrder::where(['order_id'=>$order_id,'paid'=>0,'refund_status'=>0,'status'=>0])->find(); $storeInfo = StoreOrder::where(['order_id' => $order_id, 'paid' => 0, 'refund_status' => 0, 'status' => 0])->find();
if(!$storeInfo) return; if (!$storeInfo) return;
$switch = sysConfig('admin_lower_order_switch') ? true : false; $switch = sysConfig('admin_lower_order_switch') ? true : false;
$switch && $this->getAdminNoticeAuth(function ($userInfo) use($storeInfo) { $switch && $this->getAdminNoticeAuth(function ($userInfo) use ($storeInfo) {
//模板变量 //模板变量
$admin_name = $userInfo->nickname; $admin_name = $userInfo->nickname;
$order_id = $storeInfo->order_id; $order_id = $storeInfo->order_id;
$this->send(true,$userInfo->phone,compact('admin_name','order_id'),'ADMIN_PLACE_ORDER_CODE','用户下单成功管理员发送短信通知失败,订单号为:'.$storeInfo->order_id); $this->send(true, $userInfo->phone, compact('admin_name', 'order_id'), 'ADMIN_PLACE_ORDER_CODE', '用户下单成功管理员发送短信通知失败,订单号为:' . $storeInfo->order_id);
}); });
} }
@ -184,14 +187,14 @@ class MessageSubscribe
*/ */
public function MssageSendAdminPaySuccess($order_id) public function MssageSendAdminPaySuccess($order_id)
{ {
$storeInfo = StoreOrder::where(['order_id'=>$order_id,'paid'=>1,'refund_status'=>0,'status'=>0])->find(); $storeInfo = StoreOrder::where(['order_id' => $order_id, 'paid' => 1, 'refund_status' => 0, 'status' => 0])->find();
if(!$storeInfo) return; if (!$storeInfo) return;
$switch = sysConfig('admin_pay_success_switch') ? true : false; $switch = sysConfig('admin_pay_success_switch') ? true : false;
$switch && $this->getAdminNoticeAuth(function ($userInfo) use($storeInfo) { $switch && $this->getAdminNoticeAuth(function ($userInfo) use ($storeInfo) {
//模板变量 //模板变量
$admin_name = $userInfo->nickname; $admin_name = $userInfo->nickname;
$order_id = $storeInfo->order_id; $order_id = $storeInfo->order_id;
$this->send(true,$userInfo->phone,compact('admin_name','order_id'),'ADMIN_PAY_SUCCESS_CODE','用户支付成功管理员发送短信通知失败,订单号为:'.$storeInfo->order_id); $this->send(true, $userInfo->phone, compact('admin_name', 'order_id'), 'ADMIN_PAY_SUCCESS_CODE', '用户支付成功管理员发送短信通知失败,订单号为:' . $storeInfo->order_id);
}); });
} }
@ -201,14 +204,14 @@ class MessageSubscribe
*/ */
public function MssageSendAdminConfirmTakeOver($order_id) public function MssageSendAdminConfirmTakeOver($order_id)
{ {
$storeInfo = StoreOrder::where(['order_id'=>$order_id,'paid'=>1,'refund_status'=>0,'status'=>2])->find(); $storeInfo = StoreOrder::where(['order_id' => $order_id, 'paid' => 1, 'refund_status' => 0, 'status' => 2])->find();
if(!$storeInfo) return; if (!$storeInfo) return;
$switch = sysConfig('admin_confirm_take_over_switch') ? true : false; $switch = sysConfig('admin_confirm_take_over_switch') ? true : false;
$switch && $this->getAdminNoticeAuth(function ($userInfo) use($storeInfo) { $switch && $this->getAdminNoticeAuth(function ($userInfo) use ($storeInfo) {
//模板变量 //模板变量
$admin_name = $userInfo->nickname; $admin_name = $userInfo->nickname;
$order_id = $storeInfo->order_id; $order_id = $storeInfo->order_id;
$this->send(true,$userInfo->phone,compact('admin_name','order_id'),'ADMIN_TAKE_DELIVERY_CODE','用户确认收货成功管理员发送短信通知失败,订单号为:'.$storeInfo->order_id); $this->send(true, $userInfo->phone, compact('admin_name', 'order_id'), 'ADMIN_TAKE_DELIVERY_CODE', '用户确认收货成功管理员发送短信通知失败,订单号为:' . $storeInfo->order_id);
}); });
} }
@ -218,16 +221,17 @@ class MessageSubscribe
*/ */
public function MssageSendAdminRefund($order_id) public function MssageSendAdminRefund($order_id)
{ {
$storeInfo = StoreOrder::where(['order_id'=>$order_id,'paid'=>1,'refund_status'=>1])->find(); $storeInfo = StoreOrder::where(['order_id' => $order_id, 'paid' => 1, 'refund_status' => 1])->find();
if(!$storeInfo) return; if (!$storeInfo) return;
$switch = sysConfig('admin_refund_switch') ? true : false; $switch = sysConfig('admin_refund_switch') ? true : false;
$switch && $this->getAdminNoticeAuth(function ($userInfo) use($storeInfo) { $switch && $this->getAdminNoticeAuth(function ($userInfo) use ($storeInfo) {
//模板变量 //模板变量
$admin_name = $userInfo->nickname; $admin_name = $userInfo->nickname;
$order_id = $storeInfo->order_id; $order_id = $storeInfo->order_id;
$this->send(true,$userInfo->phone,compact('admin_name','order_id'),'ADMIN_RETURN_GOODS_CODE','用户退款管理员发送短信通知失败,订单号为:'.$storeInfo->order_id); $this->send(true, $userInfo->phone, compact('admin_name', 'order_id'), 'ADMIN_RETURN_GOODS_CODE', '用户退款管理员发送短信通知失败,订单号为:' . $storeInfo->order_id);
}); });
} }
/** /**
* 提取管理员权限 * 提取管理员权限
* @param callable $callable 回调函数 * @param callable $callable 回调函数
@ -235,10 +239,10 @@ class MessageSubscribe
public function getAdminNoticeAuth(callable $callable) public function getAdminNoticeAuth(callable $callable)
{ {
$serviceOrderNotice = StoreService::getStoreServiceOrderNotice(); $serviceOrderNotice = StoreService::getStoreServiceOrderNotice();
if(count($serviceOrderNotice)) { if (count($serviceOrderNotice)) {
foreach ($serviceOrderNotice as $uid) { foreach ($serviceOrderNotice as $uid) {
$userInfo= User::where('uid',$uid)->field('phone,nickname')->find(); $userInfo = User::where('uid', $uid)->field('phone,nickname')->find();
if($userInfo && is_callable($callable)) $callable($userInfo); if ($userInfo && is_callable($callable)) $callable($userInfo);
} }
} }
} }

View File

@ -41,8 +41,8 @@ class OrderSubscribe
*/ */
public function onStoreProductOrderDeliveryAfter($event) public function onStoreProductOrderDeliveryAfter($event)
{ {
list($data,$oid) = $event; list($data, $oid) = $event;
AdminStoreOrder::orderPostageAfter($oid,$data); AdminStoreOrder::orderPostageAfter($oid, $data);
} }
/** /**
@ -54,8 +54,8 @@ class OrderSubscribe
*/ */
public function onStoreProductOrderDeliveryGoodsAfter($event) public function onStoreProductOrderDeliveryGoodsAfter($event)
{ {
list($data,$oid) = $event; list($data, $oid) = $event;
AdminStoreOrder::orderPostageAfter($oid,$data); AdminStoreOrder::orderPostageAfter($oid, $data);
} }
/** /**
@ -64,8 +64,8 @@ class OrderSubscribe
*/ */
public function onStoreProductOrderRefundNAfter($event) public function onStoreProductOrderRefundNAfter($event)
{ {
list($data,$id) = $event; list($data, $id) = $event;
AdminStoreOrder::refundNoPrieTemplate($id,$data); AdminStoreOrder::refundNoPrieTemplate($id, $data);
} }
/** /**
@ -84,7 +84,7 @@ class OrderSubscribe
*/ */
public function onStoreProductOrderEditAfter($event) public function onStoreProductOrderEditAfter($event)
{ {
list($data,$id) = $event; list($data, $id) = $event;
//$data total_price 商品总价 pay_price 实际支付 //$data total_price 商品总价 pay_price 实际支付
//订单编号 $id //订单编号 $id
} }
@ -95,7 +95,7 @@ class OrderSubscribe
*/ */
public function onStoreProductOrderDistributionAfter($event) public function onStoreProductOrderDistributionAfter($event)
{ {
list($data,$id) = $event; list($data, $id) = $event;
//$data 送货人姓名/快递公司 送货人电话/快递单号 //$data 送货人姓名/快递公司 送货人电话/快递单号
//订单编号 $id //订单编号 $id
} }
@ -125,17 +125,18 @@ class OrderSubscribe
*/ */
public function onOrderPaySuccess($event) public function onOrderPaySuccess($event)
{ {
list($order,$formId) = $event; list($order, $formId) = $event;
//更新用户支付订单数量 //更新用户支付订单数量
User::bcInc($order['uid'], 'pay_count', 1, 'uid'); User::bcInc($order['uid'], 'pay_count', 1, 'uid');
//发送模版消息、客服消息、短信、小票打印给客户和管理员 //发送模版消息、客服消息、短信、小票打印给客户和管理员
NoticeRepositories::noticeOrderPaySuccess($order,$formId); NoticeRepositories::noticeOrderPaySuccess($order, $formId);
//检测会员等级 //检测会员等级
event('UserLevelAfter', [$order['uid']]); event('UserLevelAfter', [$order['uid']]);
try{ try {
//向后台发送新订单消息 //向后台发送新订单消息
ChannelService::instance()->send('NEW_ORDER', ['order_id'=>$order['order_id']]); ChannelService::instance()->send('NEW_ORDER', ['order_id' => $order['order_id']]);
}catch (\Throwable $e){} } catch (\Throwable $e) {
}
} }
} }

View File

@ -1,4 +1,5 @@
<?php <?php
namespace crmeb\subscribes; namespace crmeb\subscribes;
/** /**
@ -30,7 +31,8 @@ class ProductSubscribe
* 用户操作产品添加事件 用户点赞产品 用户收藏产品 * 用户操作产品添加事件 用户点赞产品 用户收藏产品
* @param $event * @param $event
*/ */
public function onStoreProductUserOperationConfirmAfter($event){ public function onStoreProductUserOperationConfirmAfter($event)
{
list($category, $productId, $relationType, $uid) = $event; list($category, $productId, $relationType, $uid) = $event;
//$category 产品类型 //$category 产品类型
//$productId 产品编号 //$productId 产品编号
@ -42,7 +44,8 @@ class ProductSubscribe
* 用户操作产品取消事件 用户取消点赞产品 用户取消收藏产品 * 用户操作产品取消事件 用户取消点赞产品 用户取消收藏产品
* @param $event * @param $event
*/ */
public function onStoreProductUserOperationCancelAfter($event){ public function onStoreProductUserOperationCancelAfter($event)
{
list($category, $productId, $relationType, $uid) = $event; list($category, $productId, $relationType, $uid) = $event;
//$category 产品类型 //$category 产品类型
//$productId 产品编号 //$productId 产品编号

View File

@ -1,8 +1,10 @@
<?php <?php
namespace crmeb\subscribes; namespace crmeb\subscribes;
use app\admin\model\system\SystemAdmin; use app\admin\model\system\SystemAdmin;
use app\admin\model\system\SystemLog; use app\admin\model\system\SystemLog;
/** /**
* 后台系统事件 * 后台系统事件
* Class SystemSubscribe * Class SystemSubscribe
@ -22,8 +24,8 @@ class SystemSubscribe
*/ */
public function onAdminVisit($event) public function onAdminVisit($event)
{ {
list($adminInfo,$type) = $event; list($adminInfo, $type) = $event;
if(strtolower(app('request')->controller()) != 'index') SystemLog::adminVisit($adminInfo->id,$adminInfo->account,$type); if (strtolower(app('request')->controller()) != 'index') SystemLog::adminVisit($adminInfo->id, $adminInfo->account, $type);
} }
/** /**
@ -33,7 +35,7 @@ class SystemSubscribe
public function onSystemAdminLoginAfter($event) public function onSystemAdminLoginAfter($event)
{ {
list($adminInfo) = $event; list($adminInfo) = $event;
SystemAdmin::edit(['last_ip'=>app('request')->ip(),'last_time'=>time()],$adminInfo['id']); SystemAdmin::edit(['last_ip' => app('request')->ip(), 'last_time' => time()], $adminInfo['id']);
} }
/** /**

View File

@ -1,4 +1,5 @@
<?php <?php
namespace crmeb\subscribes; namespace crmeb\subscribes;
use app\admin\model\system\SystemAttachment; use app\admin\model\system\SystemAttachment;
@ -26,6 +27,7 @@ class TaskSubscribe
public function onTask_2() public function onTask_2()
{ {
} }
/** /**
* 6秒钟执行的方法 * 6秒钟执行的方法
*/ */
@ -45,14 +47,14 @@ class TaskSubscribe
*/ */
public function onTask_30() public function onTask_30()
{ {
try{ try {
Db::startTrans(); Db::startTrans();
StoreBargainUser::startBargainUserStatus();//批量修改砍价状态为 砍价失败 StoreBargainUser::startBargainUserStatus();//批量修改砍价状态为 砍价失败
StoreOrder::orderUnpaidCancel();//订单未支付默认取消 StoreOrder::orderUnpaidCancel();//订单未支付默认取消
StoreOrder::startTakeOrder();//7天自动收货 StoreOrder::startTakeOrder();//7天自动收货
StorePink::statusPink();//拼团到期修改状态 StorePink::statusPink();//拼团到期修改状态
Db::commit(); Db::commit();
}catch (\Exception $e){ } catch (\Exception $e) {
Db::rollback(); Db::rollback();
} }
} }

View File

@ -41,24 +41,24 @@ class UserSubscribe
*/ */
public function onWechatOauthAfter($event) public function onWechatOauthAfter($event)
{ {
list($openid, $wechatInfo, $spreadId,$login_type) = $event; list($openid, $wechatInfo, $spreadId, $login_type) = $event;
if (!User::be(['uid' => $spreadId])) $spreadId = 0; if (!User::be(['uid' => $spreadId])) $spreadId = 0;
$wechatInfo['nickname'] = filterEmoji($wechatInfo['nickname']); $wechatInfo['nickname'] = filterEmoji($wechatInfo['nickname']);
Cookie::set('is_login', 1); Cookie::set('is_login', 1);
if (isset($wechatInfo['unionid']) && $wechatInfo['unionid'] != '' && ($uid = WechatUser::where('unionid', $wechatInfo['unionid'])->where('user_type','<>','h5')->value('uid'))) { if (isset($wechatInfo['unionid']) && $wechatInfo['unionid'] != '' && ($uid = WechatUser::where('unionid', $wechatInfo['unionid'])->where('user_type', '<>', 'h5')->value('uid'))) {
WechatUser::edit($wechatInfo, $uid, 'uid'); WechatUser::edit($wechatInfo, $uid, 'uid');
if (!User::be(['uid' => $uid])) { if (!User::be(['uid' => $uid])) {
$wechatInfo = WechatUser::where('uid', $uid)->find(); $wechatInfo = WechatUser::where('uid', $uid)->find();
User::setWechatUser($wechatInfo, $spreadId); User::setWechatUser($wechatInfo, $spreadId);
} else { } else {
if($login_type) $wechatInfo['login_type'] = $login_type; if ($login_type) $wechatInfo['login_type'] = $login_type;
User::updateWechatUser($wechatInfo, $uid); User::updateWechatUser($wechatInfo, $uid);
} }
} else if ($uid = WechatUser::where(['openid' => $wechatInfo['openid']])->where('user_type','<>','h5')->value('uid')) { } else if ($uid = WechatUser::where(['openid' => $wechatInfo['openid']])->where('user_type', '<>', 'h5')->value('uid')) {
WechatUser::edit($wechatInfo, $uid, 'uid'); WechatUser::edit($wechatInfo, $uid, 'uid');
if($login_type) $wechatInfo['login_type'] = $login_type; if ($login_type) $wechatInfo['login_type'] = $login_type;
User::updateWechatUser($wechatInfo, $uid); User::updateWechatUser($wechatInfo, $uid);
} else { } else {
if (isset($wechatInfo['subscribe_scene'])) unset($wechatInfo['subscribe_scene']); if (isset($wechatInfo['subscribe_scene'])) unset($wechatInfo['subscribe_scene']);

View File

@ -29,19 +29,19 @@ trait LogicTrait
* @param $params 参数 * @param $params 参数
* @return mixed * @return mixed
*/ */
public static function __callStatic($method,$params) public static function __callStatic($method, $params)
{ {
return call_user_func_array([self::$instance,$method],$params); return call_user_func_array([self::$instance, $method], $params);
} }
/** /**
* 配置参数 * 配置参数
* @param array $config * @param array $config
*/ */
protected function setConfig(array $config=[]) protected function setConfig(array $config = [])
{ {
foreach ($config as $key => $value) { foreach ($config as $key => $value) {
$this->set($this->items,$key, $value); $this->set($this->items, $key, $value);
} }
} }
@ -72,11 +72,9 @@ trait LogicTrait
*/ */
protected function registerProviders() protected function registerProviders()
{ {
if (property_exists($this,'providers')) if (property_exists($this, 'providers')) {
{ foreach ($this->providers as $key => $provider) {
foreach ($this->providers as $key=>$provider) $this->register(new $provider(), $key);
{
$this->register(new $provider(),$key);
} }
} }
} }
@ -86,14 +84,14 @@ trait LogicTrait
* @param object $pimple * @param object $pimple
* @return $this * @return $this
* */ * */
protected function register($pimple,$key) protected function register($pimple, $key)
{ {
$response=$pimple->register($this->items); $response = $pimple->register($this->items);
if(is_array($response)) { if (is_array($response)) {
list($key,$provider)=$response; [$key, $provider] = $response;
$this->$key= $provider; $this->$key = $provider;
}else if(is_string($key)){ } else if (is_string($key)) {
$this->$key= $pimple; $this->$key = $pimple;
} }
return $this; return $this;
} }
@ -103,12 +101,13 @@ trait LogicTrait
* @param array $config * @param array $config
* @return $this * @return $this
* */ * */
public static function instance($config=[]) public static function instance($config = [])
{ {
if(is_null(self::$instance)) { if (is_null(self::$instance)) {
self::$instance = new self(); self::$instance = new self();
self::$instance->setConfig($config); self::$instance->setConfig($config);
self::$instance->registerProviders(); self::$instance->registerProviders();
if (method_exists(self::$instance, 'bool'))
self::$instance->bool(); self::$instance->bool();
} }
return self::$instance; return self::$instance;
@ -144,36 +143,35 @@ trait LogicTrait
* @param $ages * @param $ages
* @return $this * @return $this
*/ */
public function __call($method,$ages) public function __call($method, $ages)
{
$keys = property_exists($this,'propsRule') ? array_keys($this->providers) : [];
$propsRuleKeys = property_exists($this,'propsRule') ? array_keys($this->propsRule) : [];
if (strstr($method,'set') !== false) {
$attribute = lcfirst(str_replace('set','',$method));
if (property_exists($this,$attribute)
&& in_array($attribute,$propsRuleKeys)
&& isset($this->propsRule[$attribute]))
{ {
$keys = property_exists($this, 'propsRule') ? array_keys($this->providers) : [];
$propsRuleKeys = property_exists($this, 'propsRule') ? array_keys($this->propsRule) : [];
if (strstr($method, 'set') !== false) {
$attribute = lcfirst(str_replace('set', '', $method));
if (property_exists($this, $attribute)
&& in_array($attribute, $propsRuleKeys)
&& isset($this->propsRule[$attribute])) {
$propsRuleValeu = $this->propsRule[$attribute]; $propsRuleValeu = $this->propsRule[$attribute];
$type = $propsRuleValeu[1] ?? 'string'; $type = $propsRuleValeu[1] ?? 'string';
$callable = $propsRuleValeu[2] ?? null; $callable = $propsRuleValeu[2] ?? null;
if ($type == 'callable' && $callable) { if ($type == 'callable' && $callable) {
$callable = $propsRuleValeu[2]; $callable = $propsRuleValeu[2];
if (method_exists($this,$callable)) if (method_exists($this, $callable))
$ages[0] = $this->{$callable}($ages[0],$ages[1] ?? ''); $ages[0] = $this->{$callable}($ages[0], $ages[1] ?? '');
} else if($type) { } else if ($type) {
$ages[0] = $this->toType($ages[0],$type) ?? null; $ages[0] = $this->toType($ages[0], $type) ?? null;
} }
$this->{$attribute} = $ages[0]; $this->{$attribute} = $ages[0];
return $this; return $this;
} }
} else if(in_array($method,$keys)) { } else if (in_array($method, $keys)) {
$this->sendType = $method; $this->sendType = $method;
return $this; return $this;
} else { } else {
throw new AuthException('Method does not exist'.$method); throw new AuthException('Method does not exist' . $method);
} }
} }
} }

View File

@ -22,7 +22,7 @@ use think\app\Url;
* @method $this setTemplateCode(string $templateCode) 设置模板id * @method $this setTemplateCode(string $templateCode) 设置模板id
* @method $this setSendType($sendType) 设置发送类型句柄 1 = 小程序 2 = 公众号 * @method $this setSendType($sendType) 设置发送类型句柄 1 = 小程序 2 = 公众号
* @method $this setDefaultData($defaultData) 设置默认数据 * @method $this setDefaultData($defaultData) 设置默认数据
* @method $this setTemplateUrl(Url $url,string $sux = '') 设置跳转Url * @method $this setTemplateUrl(Url $url, string $sux = '') 设置跳转Url
* @method $this routine() 设置当前发送类型句柄为 小程序 * @method $this routine() 设置当前发送类型句柄为 小程序
* @method $this wechat() 设置当前发送类型句柄为 公众号 * @method $this wechat() 设置当前发送类型句柄为 公众号
*/ */
@ -46,7 +46,7 @@ class Template
protected $propsRule = [ protected $propsRule = [
'defaultData' => [null, 'string'], 'defaultData' => [null, 'string'],
'templateCode' => [null, 'string'], 'templateCode' => [null, 'string'],
'templateData' => [[],'array'], 'templateData' => [[], 'array'],
'templateUrl' => [null, 'callable', 'postpositionUrl'], 'templateUrl' => [null, 'callable', 'postpositionUrl'],
'templateFormId' => [null, 'string'], 'templateFormId' => [null, 'string'],
'sendType' => [null, 'string'], 'sendType' => [null, 'string'],
@ -82,7 +82,7 @@ class Template
* 模板消息formid 为小程序提供 * 模板消息formid 为小程序提供
* @var string * @var string
*/ */
protected $templateFormId =''; protected $templateFormId = '';
/** /**
* 发送类型 对应 $providers key * 发送类型 对应 $providers key
@ -116,7 +116,7 @@ class Template
* @param string $suffix * @param string $suffix
* @return string * @return string
*/ */
public function postpositionUrl(Url $url,string $suffix = '') public function postpositionUrl(Url $url, string $suffix = '')
{ {
return $url->suffix($suffix)->domain(true)->build(); return $url->suffix($suffix)->domain(true)->build();
} }
@ -128,21 +128,21 @@ class Template
{ {
$keys = array_keys($this->providers); $keys = array_keys($this->providers);
if (is_string($this->sendType)) { if (is_string($this->sendType)) {
if(!in_array($this->sendType,$keys)) if (!in_array($this->sendType, $keys))
throw new AuthException('设置的发送类型句柄不存在:'.$this->sendType); throw new AuthException('设置的发送类型句柄不存在:' . $this->sendType);
} elseif (is_int($this->sendType)) { } elseif (is_int($this->sendType)) {
if($this->sendType > count($keys)) if ($this->sendType > count($keys))
throw new AuthException('设置的发送类型句柄不存在:'.$this->sendType); throw new AuthException('设置的发送类型句柄不存在:' . $this->sendType);
$this->sendType = $keys[$this->sendType - 1]; $this->sendType = $keys[$this->sendType - 1];
} }
if (!$this->sendType) if (!$this->sendType)
throw new AuthException('请设置发送类型句柄'); throw new AuthException('请设置发送类型句柄');
if(!$this->templateData) if (!$this->templateData)
throw new AuthException('请设置发送模板数据'); throw new AuthException('请设置发送模板数据');
if(!$this->templateOpenId) if (!$this->templateOpenId)
throw new AuthException('请设置发送模板OPENID'); throw new AuthException('请设置发送模板OPENID');
} }
@ -153,12 +153,12 @@ class Template
*/ */
public function send(bool $excep = false) public function send(bool $excep = false)
{ {
try{ try {
$this->validate(); $this->validate();
$resource = null; $resource = null;
switch ($this->sendType){ switch ($this->sendType) {
case 'routine': case 'routine':
$resource = self::$instance->routine->sendTemplate( $resource = self::$instance->routine->sendTemplate(
$this->templateCode, $this->templateCode,
@ -186,8 +186,8 @@ class Template
$this->clear(); $this->clear();
return $resource; return $resource;
}catch (\Throwable $e){ } catch (\Throwable $e) {
if($excep) if ($excep)
throw new AuthException($e->getMessage()); throw new AuthException($e->getMessage());
return false; return false;
} }