格式化代码

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\WechatService;
use crmeb\services\FormBuilder as Form;
use crmeb\services\HookService;
use crmeb\subscribes\OrderSubscribe;
use app\admin\model\order\StoreOrderStatus;
use app\admin\model\ump\StorePink;
use app\admin\model\user\User;

View File

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

View File

@ -4,6 +4,7 @@
* User: xurongyao <763569752@qq.com>
* Date: 2019/11/13 4:52 PM
*/
namespace crmeb\repositories;
use app\models\user\WechatUser;
@ -26,59 +27,60 @@ class NoticeRepositories
* @param $order
* @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();
if($wechatUser){
$wechatUser = WechatUser::where('uid', $order['uid'])->field('openid', 'routine_openid')->find();
if ($wechatUser) {
$openid = $wechatUser['openid'];
$routineOpenid = $wechatUser['routine_openid'];
try{
if($openid){//公众号发送模板消息
WechatTemplateService::sendTemplate($openid,WechatTemplateService::ORDER_PAY_SUCCESS, [
'first'=>'亲,您购买的商品已支付成功',
'keyword1'=>$order['order_id'],
'keyword2'=>$order['pay_price'],
'remark'=>'点击查看订单详情'
],Route::buildUrl('order/detail/'.$order['order_id'])->suffix('')->domain(true)->build());
try {
if ($openid) {//公众号发送模板消息
WechatTemplateService::sendTemplate($openid, WechatTemplateService::ORDER_PAY_SUCCESS, [
'first' => '亲,您购买的商品已支付成功',
'keyword1' => $order['order_id'],
'keyword2' => $order['pay_price'],
'remark' => '点击查看订单详情'
], Route::buildUrl('order/detail/' . $order['order_id'])->suffix('')->domain(true)->build());
//订单支付成功后给客服发送模版消息
WechatTemplateService::sendAdminNoticeTemplate([
'first'=>"亲,您有一个新订单 \n订单号:{$order['order_id']}",
'keyword1'=>'新订单',
'keyword2'=>'已支付',
'keyword3'=>date('Y/m/d H:i',time()),
'remark'=>'请及时处理'
'first' => "亲,您有一个新订单 \n订单号:{$order['order_id']}",
'keyword1' => '新订单',
'keyword2' => '已支付',
'keyword3' => date('Y/m/d H:i', time()),
'remark' => '请及时处理'
]);
//订单支付成功后给客服发送客服消息
CustomerRepository::sendOrderPaySuccessCustomerService($order, 1);
}else if($routineOpenid){//小程序发送模板消息
} else if ($routineOpenid) {//小程序发送模板消息
RoutineTemplate::sendOrderSuccess($formId, $order['order_id']);
//订单支付成功后给客服发送客服消息
CustomerRepository::sendOrderPaySuccessCustomerService($order, 0);
}
}catch (\Exception $e){}
} catch (\Exception $e) {
}
}
//打印小票
$switch = sysConfig('pay_success_printing_switch') ? true : false ;
if($switch){
try{
$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();
$switch = sysConfig('pay_success_printing_switch') ? true : false;
if ($switch) {
try {
$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 = count($cartInfo) ? $cartInfo->toArray() : [];
$product = [];
foreach ($cartInfo as $item){
$product = [];
foreach ($cartInfo as $item) {
$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'] = StoreOrderCartInfo::getSubstrUTf8($value['productInfo']['store_name'],10,'UTF-8','');
$value['productInfo']['store_name'] = StoreOrderCartInfo::getSubstrUTf8($value['productInfo']['store_name'], 10, 'UTF-8', '');
$product[] = $value;
}
YLYService::getInstance()->setContent(sysConfig('site_name'),is_object($order) ? $order->toArray() : $order,$product)->orderPrinting();
}catch (\Exception $e){
Log::error('小票打印出现错误,错误原因:'.$e->getMessage());
YLYService::instance()->setContent(sysConfig('site_name'), is_object($order) ? $order->toArray() : $order, $product)->orderPrinting();
} catch (\Exception $e) {
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;
/**
* 错误码统一存放类
* Class ApiErrorCode
@ -17,10 +16,10 @@ namespace crmeb\services;
class ApiErrorCode
{
const SUCCESS = [200,'SUCCESS'];
const ERROR = [400,'操作失败'];
const SUCCESS = [200, 'SUCCESS'];
const ERROR = [400, '操作失败'];
const ERR_LOGIN = [40010,'登陆过期'];
const ERR_LOGIN = [40010, '登陆过期'];
}

View File

@ -29,13 +29,13 @@ class CacheService
* @param int $expire 缓存时间为0读取系统缓存时间
* @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);
if(!is_int($expire))
$expire = $expire ?: SystemConfigService::get('cache_config', null, true);
if (!is_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
* @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)
{
return self::handler()->remember($name,'');
return self::handler()->remember($name, '');
}
/**

View File

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

View File

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

View File

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

View File

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

View File

@ -21,12 +21,12 @@ class GroupDataService
* @param bool $isCaChe 是否读取缓存
* @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}";
$callable = function () use ($config_name,$limit) {
$callable = function () use ($config_name, $limit) {
$data = SystemGroupData::getGroupData($config_name, $limit);
if (is_object($data))
$data = $data->toArray();
@ -36,9 +36,9 @@ class GroupDataService
if ($isCaChe)
return $callable();
return CacheService::get($cacheName,$callable);
return CacheService::get($cacheName, $callable);
}catch (\Throwable $e){
} catch (\Throwable $e) {
return [];
}
}
@ -50,24 +50,24 @@ class GroupDataService
* @param bool $isCaChe 是否读取缓存
* @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}";
$callable = function () use ($config_name,$limit) {
$callable = function () use ($config_name, $limit) {
$data = SystemGroupData::getAllValue($config_name, $limit);
if(is_object($data))
if (is_object($data))
$data = $data->toArray();
return $data;
};
if($isCaChe)
if ($isCaChe)
return $callable();
return CacheService::get($cacheName,$callable);
return CacheService::get($cacheName, $callable);
}catch (\Throwable $e){
} catch (\Throwable $e) {
return [];
}
}
@ -78,24 +78,24 @@ class GroupDataService
* @param bool $isCaChe 是否读取缓存
* @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}";
$callable = function () use ($id) {
$callable = function () use ($id) {
$data = SystemGroupData::getDateValue($id);
if (is_object($data))
$data = $data->toArray();
return $data;
};
if($isCaChe)
if ($isCaChe)
return $callable();
return CacheService::get($cacheName,$callable);
return CacheService::get($cacheName, $callable);
}catch (\Throwable $e){
} catch (\Throwable $e) {
return [];
}
}

View File

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

View File

@ -13,57 +13,59 @@ class JsonService
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')));
}
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);
exit(json_encode(compact('code', 'msg', 'data', 'count')));
}
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);
if(true == is_array($msg)){
if (true == is_array($msg)) {
$result = $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;
$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;
$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 返回数据
* @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\Payment\Order;
use think\facade\Route as Url;
use crmeb\services\HookService;
use crmeb\interfaces\ProviderInterface;
use app\models\store\StoreOrder as StoreOrderRoutineModel;
use app\models\user\UserRecharge;
@ -324,7 +323,6 @@ class MiniProgramService implements ProviderInterface
$staff = self::staffService();
$staff = is_callable($message) ? $staff->message($message()) : $staff->message($message);
$res = $staff->to($to)->send();
HookService::afterListen('wechat_staff_to',compact('to','message'),$res);
return $res;
}

View File

@ -1,4 +1,5 @@
<?php
namespace crmeb\services;
use crmeb\services\JsonService as Json;
@ -6,7 +7,7 @@ use crmeb\services\JsonService as Json;
class PHPExcelService
{
//PHPExcel实例化对象
private static $PHPExcel=null;
private static $PHPExcel = null;
//表头计数
protected static $count;
//表头占行数
@ -14,19 +15,19 @@ class PHPExcelService
//表能占据表行的字母对应self::$cellkey
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(
'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',
'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'
'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',
'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'
);
//设置style
private static $styleArray = array(
@ -43,36 +44,41 @@ class PHPExcelService
//'color' => array('argb' => 'FFFF0000'),
),
),
'font'=>[
'bold'=>true
'font' => [
'bold' => true
],
'alignment'=>[
'horizontal'=>\PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
'vertical'=>\PHPExcel_Style_Alignment::VERTICAL_CENTER
'alignment' => [
'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
'vertical' => \PHPExcel_Style_Alignment::VERTICAL_CENTER
]
);
/**
*初始化PHPExcel类
*@param $data array()
*@param $fun function()
* @param $data array()
* @param $fun function()
* return
*/
private static function initialize($data,$fun){
self::$PHPExcel= new \PHPExcel();
if($fun!==null && is_callable($fun)){
self::$styleArray=$fun();
private static function initialize($data, $fun)
{
self::$PHPExcel = new \PHPExcel();
if ($fun !== null && is_callable($fun)) {
self::$styleArray = $fun();
}
if(!is_array($data)) exit(Json::fail('data 为数组'));
self::$data=$data;
if (!is_array($data)) exit(Json::fail('data 为数组'));
self::$data = $data;
}
/**
*设置字体格式
*@param $title string 必选
* @param $title string 必选
* return string
*/
public static function setUtf8($title){
public static function setUtf8($title)
{
return iconv('utf-8', 'gb2312', $title);
}
/**
*
* execl数据导出
@ -81,48 +87,50 @@ class PHPExcelService
*
* 特殊处理:合并单元格需要先对数据进行处理
*/
public function setExcelContent($list=null)
public function setExcelContent($list = null)
{
$sheet=self::$PHPExcel->getActiveSheet();
foreach(self::$data as $key=>$val){
$row=self::$cellKey[$key];
$sheet->getColumnDimension($row)->setWidth(isset($val['w'])?$val['w']:self::$where);
$sheet->setCellValue($row.self::$topNumber,isset($val['name'])?$val['name']:$val);
$sheet = self::$PHPExcel->getActiveSheet();
foreach (self::$data as $key => $val) {
$row = self::$cellKey[$key];
$sheet->getColumnDimension($row)->setWidth(isset($val['w']) ? $val['w'] : self::$where);
$sheet->setCellValue($row . self::$topNumber, isset($val['name']) ? $val['name'] : $val);
}
$cellkey=array_slice(self::$cellKey,0,self::$count);
if($list!==null && is_array($list)){
foreach ($cellkey as $k=>$v){
foreach ($list as $key=>$val){
if(isset($val[$k]) && !is_array($val[$k])){
$sheet->setCellValue($v.(self::$topNumber+1+$key),$val[$k]);
}else if(isset($val[$k]) && is_array($val[$k])){
$str='';
foreach ($val[$k] as $value){
$str.=$value.chr(10);
$cellkey = array_slice(self::$cellKey, 0, self::$count);
if ($list !== null && is_array($list)) {
foreach ($cellkey as $k => $v) {
foreach ($list as $key => $val) {
if (isset($val[$k]) && !is_array($val[$k])) {
$sheet->setCellValue($v . (self::$topNumber + 1 + $key), $val[$k]);
} else if (isset($val[$k]) && is_array($val[$k])) {
$str = '';
foreach ($val[$k] as $value) {
$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->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);
}else if($list!==null && is_callable($list)){
$list($sheet,self::$topNumber,$cellkey,self::$cells)->applyFromArray(self::$styleArray);
$sheet->getStyle('A4:' . self::$cells . (count($list) + self::$topNumber))->getAlignment()->setWrapText(true);
} else if ($list !== null && is_callable($list)) {
$list($sheet, self::$topNumber, $cellkey, self::$cells)->applyFromArray(self::$styleArray);
}
return $this;
}
/**
* 保存表格数据,并下载
* @param
* @return
*/
public function ExcelSave(){
$objWriter=\PHPExcel_IOFactory::createWriter(self::$PHPExcel,'Excel2007');
$filename=self::$title.'--'.time().'.xlsx';
public function ExcelSave()
{
$objWriter = \PHPExcel_IOFactory::createWriter(self::$PHPExcel, 'Excel2007');
$filename = self::$title . '--' . time() . '.xlsx';
ob_end_clean();
header('Content-Type: application/vnd.ms-excel');
header('Content-Type: application/octet-stream');
@ -138,20 +146,21 @@ class PHPExcelService
* @param $fun function() 主要设置边框的粗细
* @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::$cellKey)){
if (self::$count = count(self::$data)) {
if (self::$count > count(self::$cellKey)) {
return Json::fail('表头长度过长');
}
self::$cells=self::$cellKey[self::$count-1];
}else{
self::$cells = self::$cellKey[self::$count - 1];
} else {
return Json::fail('data 参数二不能为空');
}
return new self;
}
/**
* 设置标题
* @param $title string || array ['title'=>'','name'=>'','info'=>[]]
@ -160,20 +169,21 @@ class PHPExcelService
* @param $funName function($style,$A,$A2) 自定义设置头部样式
* @return $this
*/
public function setExcelTile($title='',$Name='',$info=[],$funName=null){
public function setExcelTile($title = '', $Name = '', $info = [], $funName = null)
{
//设置参数
if(is_array($title)){
if(isset($title['title'])) $title=$title['title'];
if(isset($title['name'])) $Name=$title['name'];
if(isset($title['info'])) $info=$title['info'];
if (is_array($title)) {
if (isset($title['title'])) $title = $title['title'];
if (isset($title['name'])) $Name = $title['name'];
if (isset($title['info'])) $info = $title['info'];
}
if(empty($title))
$title=self::$title;
if (empty($title))
$title = self::$title;
else
self::$title=$title;
if(empty($Name)) $Name=time();
self::$title = $title;
if (empty($Name)) $Name = time();
//设置Excel属性
self::$PHPExcel ->getProperties()
self::$PHPExcel->getProperties()
->setCreator("Neo")
->setLastModifiedBy("Neo")
->setTitle(self::setUtf8($title))
@ -181,25 +191,25 @@ class PHPExcelService
->setDescription("")
->setKeywords($Name)
->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('A2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
self::$PHPExcel->setActiveSheetIndex(0);
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('A2:'.self::$cells.'2');
self::$PHPExcel->getActiveSheet()->mergeCells('A1:' . self::$cells . '1');
self::$PHPExcel->getActiveSheet()->mergeCells('A2:' . self::$cells . '2');
self::$PHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(40);
self::$PHPExcel->getActiveSheet()->getRowDimension(2)->setRowHeight(20);
//设置表头行高
if($funName!==null && is_callable($funName)){
$fontstyle=self::$PHPExcel->getActiveSheet();
$funName($fontstyle,'A1','A2');
}else{
if ($funName !== null && is_callable($funName)) {
$fontstyle = self::$PHPExcel->getActiveSheet();
$funName($fontstyle, 'A1', 'A2');
} else {
//设置表头字体
self::$PHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setName('黑体');
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()->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;
}
/**
* 设置第二行标题内容
* @param $info array (['name'=>'','site'=>'','phone'=>123] || ['我是表名','我是地址','我是手机号码'] ) || string 自定义
* @return string
*/
private static function setCellInfo($info){
$content=['操作者:','导出日期:'.date('Y-m-d',time()),'地址:','电话:'];
if(is_array($info) && !empty($info)){
if(isset($info['name'])){
$content[0].=$info['name'];
}else{
$content[0].=isset($info[0])?$info[0]:'';
private static function setCellInfo($info)
{
$content = ['操作者:', '导出日期:' . date('Y-m-d', time()), '地址:', '电话:'];
if (is_array($info) && !empty($info)) {
if (isset($info['name'])) {
$content[0] .= $info['name'];
} else {
$content[0] .= isset($info[0]) ? $info[0] : '';
}
if(isset($info['site'])){
$content[2].=$info['site'];
}else{
$content[2].=isset($info[1])?$info[1]:'';
if (isset($info['site'])) {
$content[2] .= $info['site'];
} else {
$content[2] .= isset($info[1]) ? $info[1] : '';
}
if(isset($info['phone'])){
$content[3].=$info['phone'];
}else{
$content[3].=isset($info[2])?$info[2]:'';
if (isset($info['phone'])) {
$content[3] .= $info['phone'];
} else {
$content[3] .= isset($info[2]) ? $info[2] : '';
}
return implode(' ',$content);
}else if(is_string($info)){
return empty($info)?implode(' ',$content):$info;
return implode(' ', $content);
} else if (is_string($info)) {
return empty($info) ? implode(' ', $content) : $info;
}
}
}

View File

@ -10,21 +10,21 @@ namespace crmeb\services;
* @Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
* @updated 2015-08-26
*/
class PHPTreeService{
class PHPTreeService
{
protected static $config = array(
/* 主键 */
'primary_key' => 'id',
'primary_key' => 'id',
/* 父键 */
'parent_key' => 'pid',
'parent_key' => 'pid',
/* 展开属性 */
'expanded_key' => 'expanded',
'expanded_key' => 'expanded',
/* 叶子节点属性 */
'leaf_key' => 'leaf',
'leaf_key' => 'leaf',
/* 孩子节点属性 */
'children_key' => 'children',
'children_key' => 'children',
/* 是否展开子节点 */
'expanded' => false
'expanded' => false
);
/* 结果集 */
@ -32,33 +32,37 @@ class PHPTreeService{
/* 层次暂存 */
protected static $level = array();
/**
* @name 生成树形结构
* @param array 二维数组
* @return mixed 多维数组
*/
public static function makeTree($data,$options=array() ){
$dataset = self::buildData($data,$options);
$r = self::makeTreeCore(0,$dataset,'normal');
public static function makeTree($data, $options = array())
{
$dataset = self::buildData($data, $options);
$r = self::makeTreeCore(0, $dataset, 'normal');
return $r;
}
/* 生成线性结构, 便于HTML输出, 参数同上 */
public static function makeTreeForHtml($data,$options=array()){
public static function makeTreeForHtml($data, $options = array())
{
$dataset = self::buildData($data,$options);
$r = self::makeTreeCore(0,$dataset,'linear');
$dataset = self::buildData($data, $options);
$r = self::makeTreeCore(0, $dataset, 'linear');
return $r;
}
/* 格式化数据, 私有方法 */
private static function buildData($data,$options){
$config = array_merge(self::$config,$options);
private static function buildData($data, $options)
{
$config = array_merge(self::$config, $options);
self::$config = $config;
extract($config);
$r = array();
foreach($data as $item){
foreach ($data as $item) {
$id = $item[$primary_key];
$parent_id = $item[$parent_key];
$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);
foreach($data[$index] as $id=>$item)
{
if($type=='normal'){
if(isset($data[$id]))
{
$item[$expanded_key]= self::$config['expanded'];
$item[$children_key]= self::makeTreeCore($id,$data,$type);
}
else
{
$item[$leaf_key]= true;
foreach ($data[$index] as $id => $item) {
if ($type == 'normal') {
if (isset($data[$id])) {
$item[$expanded_key] = self::$config['expanded'];
$item[$children_key] = self::makeTreeCore($id, $data, $type);
} else {
$item[$leaf_key] = true;
}
$r[] = $item;
}else if($type=='linear'){
} else if ($type == 'linear') {
$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];
self::$result[] = $item;
if(isset($data[$id])){
self::makeTreeCore($id,$data,$type);
if (isset($data[$id])) {
self::makeTreeCore($id, $data, $type);
}
$r = self::$result;

View File

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

View File

@ -1,4 +1,5 @@
<?php
namespace crmeb\services;
/**
@ -23,25 +24,25 @@ class SMSService
//短信支付回调地址
private static $payNotify;
//验证码
const VERIFICATION_CODE = 518076;
const VERIFICATION_CODE = 518076;
//支付成功
const PAY_SUCCESS_CODE = 520268;
const PAY_SUCCESS_CODE = 520268;
//发货提醒
const DELIVER_GOODS_CODE = 520269;
const DELIVER_GOODS_CODE = 520269;
//确认收货提醒
const TAKE_DELIVERY_CODE = 520271;
const TAKE_DELIVERY_CODE = 520271;
//管理员下单提醒
const ADMIN_PLACE_ORDER_CODE = 520272;
const ADMIN_PLACE_ORDER_CODE = 520272;
//管理员退货提醒
const ADMIN_RETURN_GOODS_CODE = 520274;
const ADMIN_RETURN_GOODS_CODE = 520274;
//管理员支付成功提醒
const ADMIN_PAY_SUCCESS_CODE = 520273;
const ADMIN_PAY_SUCCESS_CODE = 520273;
//管理员确认收货
const ADMIN_TAKE_DELIVERY_CODE = 520422;
const ADMIN_TAKE_DELIVERY_CODE = 520422;
public function __construct()
{
self::$status = strlen(sysConfig('sms_account')) != 0 ?? false && strlen(sysConfig('sms_token')) != 0 ?? false;
self::$status = strlen(sysConfig('sms_account')) != 0 ?? false && strlen(sysConfig('sms_token')) != 0 ?? false;
}
public static function getConstants($code = '')
@ -53,20 +54,20 @@ class SMSService
}
private static function auto()
{
self::$SMSAccount = sysConfig('sms_account');
self::$SMSToken = md5(self::$SMSAccount.md5(sysConfig('sms_token')));
self::$payNotify = sysConfig('site_url').'/api/sms/pay/notify';
}
{
self::$SMSAccount = sysConfig('sms_account');
self::$SMSToken = md5(self::$SMSAccount . md5(sysConfig('sms_token')));
self::$payNotify = sysConfig('site_url') . '/api/sms/pay/notify';
}
/**
* 验证码接口
* @return string
*/
public static function code()
{
return self::$SMSUrl.'sms/captcha';
}
public static function code()
{
return self::$SMSUrl . 'sms/captcha';
}
/**
@ -79,30 +80,30 @@ class SMSService
* @param $sign
* @return mixed
*/
public static function register($account, $password, $url, $phone, $code, $sign)
{
self::auto();
$data['account'] = $account;
$data['password'] = $password;
$data['url'] = $url;
$data['phone'] = $phone;
$data['sign'] = $sign;
$data['code'] = $code;
return json_decode(HttpService::postRequest(self::$SMSUrl.'sms/register', $data), true);
}
public static function register($account, $password, $url, $phone, $code, $sign)
{
self::auto();
$data['account'] = $account;
$data['password'] = $password;
$data['url'] = $url;
$data['phone'] = $phone;
$data['sign'] = $sign;
$data['code'] = $code;
return json_decode(HttpService::postRequest(self::$SMSUrl . 'sms/register', $data), true);
}
/**
* 公共短信模板列表
* @param array $data
* @return mixed
*/
public static function publictemp(array $data)
{
self::auto();
$data['account'] = self::$SMSAccount;
$data['token'] = self::$SMSToken;
return json_decode(HttpService::postRequest(self::$SMSUrl.'sms/publictemp', $data), true);
}
public static function publictemp(array $data)
{
self::auto();
$data['account'] = self::$SMSAccount;
$data['token'] = self::$SMSToken;
return json_decode(HttpService::postRequest(self::$SMSUrl . 'sms/publictemp', $data), true);
}
/**
* 公共短信模板添加
@ -110,15 +111,15 @@ class SMSService
* @param $tempId
* @return mixed
*/
public static function use($id, $tempId)
{
self::auto();
$data['account'] = self::$SMSAccount;
$data['token'] = self::$SMSToken;
$data['id'] = $id;
$data['tempId'] = $tempId;
return json_decode(HttpService::postRequest(self::$SMSUrl.'sms/use', $data), true);
}
public static function use($id, $tempId)
{
self::auto();
$data['account'] = self::$SMSAccount;
$data['token'] = self::$SMSToken;
$data['id'] = $id;
$data['tempId'] = $tempId;
return json_decode(HttpService::postRequest(self::$SMSUrl . 'sms/use', $data), true);
}
/**
* 发送短信
@ -127,28 +128,28 @@ class SMSService
* @param $param
* @return bool|string
*/
public static function send($phone, $template, array $param)
{
self::auto();
$data['uid'] = self::$SMSAccount;
$data['token'] = self::$SMSToken;
$data['mobile'] = $phone;
$data['template'] = $template;
$data['param'] = json_encode($param);
return json_decode(HttpService::postRequest(self::$SMSUrl.'sms/send', $data), true);
}
public static function send($phone, $template, array $param)
{
self::auto();
$data['uid'] = self::$SMSAccount;
$data['token'] = self::$SMSToken;
$data['mobile'] = $phone;
$data['template'] = $template;
$data['param'] = json_encode($param);
return json_decode(HttpService::postRequest(self::$SMSUrl . 'sms/send', $data), true);
}
/**
* 账号信息
* @return mixed
*/
public static function count()
{
self::auto();
$data['account'] = self::$SMSAccount;
$data['token'] = self::$SMSToken;
return json_decode(HttpService::postRequest(self::$SMSUrl.'sms/userinfo', $data), true);
}
public static function count()
{
self::auto();
$data['account'] = self::$SMSAccount;
$data['token'] = self::$SMSToken;
return json_decode(HttpService::postRequest(self::$SMSUrl . 'sms/userinfo', $data), true);
}
/**
* 支付套餐
@ -156,12 +157,12 @@ class SMSService
* @param $limit
* @return mixed
*/
public static function meal($page, $limit)
{
$data['page'] = $page;
$data['limit'] = $limit;
return json_decode(HttpService::getRequest(self::$SMSUrl.'sms/meal', $data), true);
}
public static function meal($page, $limit)
{
$data['page'] = $page;
$data['limit'] = $limit;
return json_decode(HttpService::getRequest(self::$SMSUrl . 'sms/meal', $data), true);
}
/**
* 支付码
@ -171,18 +172,18 @@ class SMSService
* @param $attach
* @return mixed
*/
public static function pay($payType, $mealId, $price, $attach)
{
self::auto();
$data['uid'] = self::$SMSAccount;
$data['token'] = self::$SMSToken;
$data['payType'] = $payType;
$data['mealId'] = $mealId;
$data['notify'] = self::$payNotify;
$data['price'] = $price;
$data['attach'] = $attach;
return json_decode(HttpService::postRequest(self::$SMSUrl.'sms/mealpay', $data), true);
}
public static function pay($payType, $mealId, $price, $attach)
{
self::auto();
$data['uid'] = self::$SMSAccount;
$data['token'] = self::$SMSToken;
$data['payType'] = $payType;
$data['mealId'] = $mealId;
$data['notify'] = self::$payNotify;
$data['price'] = $price;
$data['attach'] = $attach;
return json_decode(HttpService::postRequest(self::$SMSUrl . 'sms/mealpay', $data), true);
}
/**
* 申请模板消息
@ -191,27 +192,27 @@ class SMSService
* @param $type
* @return mixed
*/
public static function apply($title, $content, $type)
{
self::auto();
$data['account'] = self::$SMSAccount;
$data['token'] = self::$SMSToken;
$data['title'] = $title;
$data['content'] = $content;
$data['type'] = $type;
return json_decode(HttpService::postRequest(self::$SMSUrl.'sms/apply', $data), true);
}
public static function apply($title, $content, $type)
{
self::auto();
$data['account'] = self::$SMSAccount;
$data['token'] = self::$SMSToken;
$data['title'] = $title;
$data['content'] = $content;
$data['type'] = $type;
return json_decode(HttpService::postRequest(self::$SMSUrl . 'sms/apply', $data), true);
}
/**
* 短信模板列表
* @param $data
* @return mixed
*/
public static function template($data)
{
self::auto();
$data['account'] = self::$SMSAccount;
$data['token'] = self::$SMSToken;
return json_decode(HttpService::postRequest(self::$SMSUrl.'sms/template', $data), true);
}
public static function template($data)
{
self::auto();
$data['account'] = self::$SMSAccount;
$data['token'] = self::$SMSToken;
return json_decode(HttpService::postRequest(self::$SMSUrl . 'sms/template', $data), true);
}
}

View File

@ -20,13 +20,6 @@ class SystemConfigService
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
namespace crmeb\services;
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无权限
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 = "{&&}";
//更新网址信息
public function snyweninfo($serverweb){
return self::request_post(self::$UpdateWeBinfo,$serverweb);
public function snyweninfo($serverweb)
{
return self::request_post(self::$UpdateWeBinfo, $serverweb);
}
//判断是否有权限 返回1有权限0无权限
public function isauth(){
public function isauth()
{
return self::request_post(self::$Isauth);
}
/*
*获取ip token 生成当前时间和过期时间
* @param string ip
* @param int $valid_peroid 过期周期 15
*/
public static function get_token($ip='',$valid_peroid=1296000){
$request=app('request');
if(empty($ip)) $ip=$request->ip();
$to_ken=$request->domain().self::$seperater.$ip.self::$seperater.time().self::$seperater.(time()+$valid_peroid).self::$seperater;
$token=self::enCode($to_ken);
public static function get_token($ip = '', $valid_peroid = 1296000)
{
$request = app('request');
if (empty($ip)) $ip = $request->ip();
$to_ken = $request->domain() . self::$seperater . $ip . self::$seperater . time() . self::$seperater . (time() + $valid_peroid) . self::$seperater;
$token = self::enCode($to_ken);
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 array $post_data
*/
public static function start(){
$pach = app()->getRootPath().'version';
public static function start()
{
$pach = app()->getRootPath() . 'version';
$request = app('request');
if(!file_exists($pach)) return self::getRet($pach.'升级文件丢失,请联系管理员');
$version=@file($pach);
if(!isset($version[0])) return self::getRet('获取失败');
$lv=self::request_post(self::$isNowVersionUrl,['token'=>self::get_token($request->ip())]);
if(isset($lv['code']) && $lv['code']==200)
$version_lv=isset($lv['data']['version']) && $lv['data']['version'] ? $lv['data']['version'] : false;
if (!file_exists($pach)) return self::getRet($pach . '升级文件丢失,请联系管理员');
$version = @file($pach);
if (!isset($version[0])) return self::getRet('获取失败');
$lv = self::request_post(self::$isNowVersionUrl, ['token' => self::get_token($request->ip())]);
if (isset($lv['code']) && $lv['code'] == 200)
$version_lv = isset($lv['data']['version']) && $lv['data']['version'] ? $lv['data']['version'] : false;
else
return isset($lv['msg'])?self::getRet($lv['msg']):self::getRet('获取失败');
if($version_lv===false) return self::getRet('获取失败');
if(strstr($version[0],'=')!==false){
$version=explode('=',$version[0]);
if($version[1]!=$version_lv){
return self::getRet($version_lv,200);
return isset($lv['msg']) ? self::getRet($lv['msg']) : self::getRet('获取失败');
if ($version_lv === false) return self::getRet('获取失败');
if (strstr($version[0], '=') !== false) {
$version = explode('=', $version[0]);
if ($version[1] != $version_lv) {
return self::getRet($version_lv, 200);
}
}
return self::getRet('获取失败');
}
public static function getVersion(){
$pach = app()->getRootPath().'.version';
if(!file_exists($pach)) return self::getRet($pach.'升级文件丢失,请联系管理员');
$version=@file($pach);
if(!isset($version[0]) && !isset($version[1])) return self::getRet('获取失败');
$arr=[];
foreach ($version as $val){
list($k,$v)=explode('=',$val);
$arr[$k]=$v;
public static function getVersion()
{
$pach = app()->getRootPath() . '.version';
if (!file_exists($pach)) return self::getRet($pach . '升级文件丢失,请联系管理员');
$version = @file($pach);
if (!isset($version[0]) && !isset($version[1])) return self::getRet('获取失败');
$arr = [];
foreach ($version as $val) {
list($k, $v) = explode('=', $val);
$arr[$k] = $v;
}
return self::getRet($arr,200);
return self::getRet($arr, 200);
}
/**
* 模拟post进行url请求
* @param string $url
* @param array $post_data
*/
public static function request_post($url = '', $post_data = array()) {
if(strstr($url,'http')===false) $url=self::$domain.$url;
if (empty($url)){
public static function request_post($url = '', $post_data = array())
{
if (strstr($url, 'http') === false) $url = self::$domain . $url;
if (empty($url)) {
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 = "";
foreach ( $post_data as $k => $v )
{
$o.= "$k=" . urlencode( $v ). "&" ;
foreach ($post_data as $k => $v) {
$o .= "$k=" . urlencode($v) . "&";
}
$post_data = substr($o,0,-1);
$post_data = substr($o, 0, -1);
$postUrl = $url;
$curlPost = $post_data;
$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_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
curl_setopt($ch, CURLOPT_TIMEOUT,20);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$data = curl_exec($ch);//运行curl
curl_close($ch);
if($data){
$data=json_decode($data,true);
if ($data) {
$data = json_decode($data, true);
}
return $data;
}
/**
* 验证远程文件是否存在 以及下载
* @param string $url 文件路径
* @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 = str_replace('\\','/',$url);
$url = self::$domain . 'public' . DS . 'uploads' . DS . 'upgrade' . DS . $url;
$url = str_replace('\\', '/', $url);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_NOBODY, true);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
@ -134,47 +149,49 @@ class UpgradeService extends FileService
$result = curl_exec($curl);
$found = false;
// 如果请求没有发送失败
if ($result !== false)
{
if ($result !== false) {
// 再检查http响应码是否为200
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($statusCode == 200)
{
if ($statusCode == 200) {
curl_close($curl);
$fileservice=new self;
$fileservice = new self;
//下载文件
$zip=$fileservice->down_remote_file($url,$savefile);
if($zip['error']>0) return false;
if(!isset($zip['save_path']) && empty($zip['save_path'])) return false;
if(!file_exists($zip['save_path'])) return false;
$zip = $fileservice->down_remote_file($url, $savefile);
if ($zip['error'] > 0) return false;
if (!isset($zip['save_path']) && empty($zip['save_path'])) return false;
if (!file_exists($zip['save_path'])) return false;
return $zip['save_path'];
}
}
curl_close($curl);
return $found;
}
/**
* 通用加密
* @param String $string 需要加密的字串
* @param String $skey 加密EKY
* @return String
*/
private static function enCode($string = '', $skey = 'fb') {
private static function enCode($string = '', $skey = 'fb')
{
$skey = array_reverse(str_split($skey));
$strArr = str_split(base64_encode($string));
$strCount = count($strArr);
foreach ($skey as $key => $value) {
$key < $strCount && $strArr[$key].=$value;
$key < $strCount && $strArr[$key] .= $value;
}
return str_replace('=', 'O0O0O', join('', $strArr));
}
/**
* 去除回车去取空格去除换行去除tab
* @param String $str 需要去除的字串
* @return String
*/
public static function replace($str){
return trim(str_replace(array("\r", "\n", "\t"), '',$str));
public static function replace($str)
{
return trim(str_replace(array("\r", "\n", "\t"), '', $str));
}
}

View File

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

View File

@ -24,19 +24,19 @@ class UtilService
* @param bool $suffix
* @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 = [];
$i = 0;
foreach ($params as $param){
if(!is_array($param)) {
foreach ($params as $param) {
if (!is_array($param)) {
$p[$suffix == true ? $i++ : $param] = $request->param($param);
}else{
if(!isset($param[1])) $param[1] = null;
if(!isset($param[2])) $param[2] = '';
$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]);
} else {
if (!isset($param[1])) $param[1] = null;
if (!isset($param[2])) $param[2] = '';
$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]);
}
}
return $p;
@ -49,25 +49,26 @@ class UtilService
* @param bool $suffix
* @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 = [];
$i = 0;
foreach ($params as $param){
if(!is_array($param)) {
foreach ($params as $param) {
if (!is_array($param)) {
$p[$suffix == true ? $i++ : $param] = $request->param($param);
}else{
if(!isset($param[1])) $param[1] = null;
if(!isset($param[2])) $param[2] = '';
$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]);
} else {
if (!isset($param[1])) $param[1] = null;
if (!isset($param[2])) $param[2] = '';
$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]);
}
}
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;
@ -79,33 +80,33 @@ class UtilService
// 密匙b会用来做数据完整性验证
$keyb = md5(substr($key, 16, 16));
// 密匙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)) : '';
// 参与运算的密匙
$cryptkey = $keya.md5($keya.$keyc);
$cryptkey = $keya . md5($keya . $keyc);
$key_length = strlen($cryptkey);
// 明文前10位用来保存时间戳解密时验证数据有效性10到26位用来保存$keyb(密匙b)
//解密时会通过这个密匙验证数据完整性
// 如果是解码的话,会从第$ckey_length位开始因为密文前$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);
$result = '';
$box = range(0, 255);
$rndkey = array();
// 产生密匙簿
for($i = 0; $i <= 255; $i++) {
for ($i = 0; $i <= 255; $i++) {
$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;
$tmp = $box[$i];
$box[$i] = $box[$j];
$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;
$j = ($j + $box[$a]) % 256;
$tmp = $box[$a];
@ -114,10 +115,10 @@ class UtilService
// 从密匙簿得出密匙进行异或,再转成字符
$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) &&
substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) &&
substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
return substr($result, 26);
} else {
return '';
@ -125,7 +126,7 @@ class UtilService
} else {
// 把动态密匙保存在密文里,这也是为什么同样的明文,生产不同密文后能解密的原因
// 因为加密后的密文可能是一些特殊字符复制过程可能会丢失所以用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)
{
return trim(str_replace(DS, '/', $path),'.');
return trim(str_replace(DS, '/', $path), '.');
}
/**
@ -147,10 +148,10 @@ class UtilService
*/
public static function urlToPath($url)
{
$path = trim(str_replace('/',DS,$url),DS);
if(0 !== strripos($path, 'public'))
$path = trim(str_replace('/', DS, $url), DS);
if (0 !== strripos($path, 'public'))
$path = 'public' . DS . $path;
return app()->getRootPath().$path;
return app()->getRootPath() . $path;
}
/**
@ -202,6 +203,7 @@ class UtilService
}
return $list;
}
/**
* 分级返回多维数组
* @param $data
@ -227,6 +229,7 @@ class UtilService
}
/**分级返回下级所有分类ID
* @param $data
* @param string $children
@ -234,12 +237,12 @@ class UtilService
* @param string $pk
* @return string
*/
public static function getChildrenPid($data,$pid, $field = 'pid', $pk = 'id')
public static function getChildrenPid($data, $pid, $field = 'pid', $pk = 'id')
{
static $pids = '';
foreach ($data as $k => $res) {
if ($res[$field] == $pid) {
$pids .= ','.$res[$pk];
$pids .= ',' . $res[$pk];
self::getChildrenPid($data, $res[$pk], $field, $pk);
}
}
@ -252,13 +255,13 @@ class UtilService
* @param $url
* @return \StdClass
*/
public static function rmPublicResource($url,$isPath = false)
public static function rmPublicResource($url, $isPath = false)
{
$path = $isPath ? $url : realpath(self::urlToPath($url));
if(!$path) return JsonService::fail('删除文件不存在!');
if(!file_exists($path)) return JsonService::fail('删除路径不合法!');
if (!$path) return JsonService::fail('删除文件不存在!');
if (!file_exists($path)) 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();
}
@ -278,14 +281,14 @@ class UtilService
*/
public static function anonymity($name)
{
$strLen = mb_strlen($name,'UTF-8');
$strLen = mb_strlen($name, 'UTF-8');
$min = 3;
if($strLen <= 1)
if ($strLen <= 1)
return '*';
if($strLen<= $min)
return mb_substr($name,0,1,'UTF-8').str_repeat('*',$min-1);
if ($strLen <= $min)
return mb_substr($name, 0, 1, 'UTF-8') . str_repeat('*', $min - 1);
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
* @return bool
*/
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=>"国外 "];
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 => "国外 "];
$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)$/";
$pass= true;
if(!$card || !preg_match($match,$card)){
$pass = true;
if (!$card || !preg_match($match, $card)) {
//身份证格式错误
$pass = false;
}else if(!$city[substr($card,0,2)]){
} else if (!$city[substr($card, 0, 2)]) {
//地址错误
$pass = false;
}else{
} else {
//18位身份证需要验证最后一位校验位
if(strlen($card) == 18){
if (strlen($card) == 18) {
$card = str_split($card);
//∑(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;
$ai = 0;
$wi = 0;
for ($i = 0; $i < 17; $i++)
{
for ($i = 0; $i < 17; $i++) {
$ai = $card[$i];
$wi = $factor[$i];
$sum += $ai * $wi;
}
$last = $parity[$sum % 11];
if($parity[$sum % 11] != $card[17]){
if ($parity[$sum % 11] != $card[17]) {
// $tip = "校验位错误";
$pass =false;
$pass = false;
}
}else{
$pass =false;
} else {
$pass = false;
}
}
if(!$pass) return false;/* 身份证格式错误*/
if (!$pass) return false;/* 身份证格式错误*/
return true;/* 身份证格式正确*/
}
@ -342,96 +345,97 @@ class UtilService
* @return array|bool|string
* @throws \Exception
*/
public static function setShareMarketingPoster($data = array(), $path){
public static function setShareMarketingPoster($data = array(), $path)
{
$config = array(
'text'=>array(
'text' => array(
array(
'text'=>$data['price'],//TODO 价格
'left'=>116,
'top'=>200,
'fontPath'=>app()->getRootPath().'public/static/font/Alibaba-PuHuiTi-Regular.otf', //字体文件
'fontSize'=>50, //字号
'fontColor'=>'255,0,0', //字体颜色
'angle'=>0,
'text' => $data['price'],//TODO 价格
'left' => 116,
'top' => 200,
'fontPath' => app()->getRootPath() . 'public/static/font/Alibaba-PuHuiTi-Regular.otf', //字体文件
'fontSize' => 50, //字号
'fontColor' => '255,0,0', //字体颜色
'angle' => 0,
),
array(
'text'=>$data['label'],//TODO 标签
'left'=>394,
'top'=>190,
'fontPath'=>app()->getRootPath().'public/static/font/Alibaba-PuHuiTi-Regular.otf', //字体文件
'fontSize'=>24, //字号
'fontColor'=>'255,255,255', //字体颜色
'angle'=>0,
'text' => $data['label'],//TODO 标签
'left' => 394,
'top' => 190,
'fontPath' => app()->getRootPath() . 'public/static/font/Alibaba-PuHuiTi-Regular.otf', //字体文件
'fontSize' => 24, //字号
'fontColor' => '255,255,255', //字体颜色
'angle' => 0,
),
array(
'text'=>$data['msg'],//TODO 简述
'left'=>80,
'top'=>270,
'fontPath'=>app()->getRootPath().'public/static/font/Alibaba-PuHuiTi-Regular.otf', //字体文件
'fontSize'=>22, //字号
'fontColor'=>'40,40,40', //字体颜色
'angle'=>0,
'text' => $data['msg'],//TODO 简述
'left' => 80,
'top' => 270,
'fontPath' => app()->getRootPath() . 'public/static/font/Alibaba-PuHuiTi-Regular.otf', //字体文件
'fontSize' => 22, //字号
'fontColor' => '40,40,40', //字体颜色
'angle' => 0,
)
),
'image'=>array(
'image' => array(
array(
'url'=>$data['image'], //图片
'stream'=>0,
'left'=>120,
'top'=>340,
'right'=>0,
'bottom'=>0,
'width'=>450,
'height'=>450,
'opacity'=>100
'url' => $data['image'], //图片
'stream' => 0,
'left' => 120,
'top' => 340,
'right' => 0,
'bottom' => 0,
'width' => 450,
'height' => 450,
'opacity' => 100
),
array(
'url'=>$data['url'], //二维码资源
'stream'=>0,
'left'=>260,
'top'=>890,
'right'=>0,
'bottom'=>0,
'width'=>160,
'height'=>160,
'opacity'=>100
'url' => $data['url'], //二维码资源
'stream' => 0,
'left' => 260,
'top' => 890,
'right' => 0,
'bottom' => 0,
'width' => 160,
'height' => 160,
'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(strlen($data['title']) < 36){
if (!file_exists($config['background'])) exception('缺少系统预设背景图片');
if (strlen($data['title']) < 36) {
$text = array(
'text'=>$data['title'],//TODO 标题
'left'=>76,
'top'=>100,
'fontPath'=>app()->getRootPath().'public/static/font/Alibaba-PuHuiTi-Regular.otf', //字体文件
'fontSize'=>32, //字号
'fontColor'=>'0,0,0', //字体颜色
'angle'=>0,
'text' => $data['title'],//TODO 标题
'left' => 76,
'top' => 100,
'fontPath' => app()->getRootPath() . 'public/static/font/Alibaba-PuHuiTi-Regular.otf', //字体文件
'fontSize' => 32, //字号
'fontColor' => '0,0,0', //字体颜色
'angle' => 0,
);
array_push($config['text'],$text);
}else{
array_push($config['text'], $text);
} else {
$titleOne = array(
'text'=>mb_substr($data['title'], 0, 12),//TODO 标题
'left'=>76,
'top'=>70,
'fontPath'=>app()->getRootPath().'public/static/font/Alibaba-PuHuiTi-Regular.otf', //字体文件
'fontSize'=>32, //字号
'fontColor'=>'0,0,0', //字体颜色
'angle'=>0,
'text' => mb_substr($data['title'], 0, 12),//TODO 标题
'left' => 76,
'top' => 70,
'fontPath' => app()->getRootPath() . 'public/static/font/Alibaba-PuHuiTi-Regular.otf', //字体文件
'fontSize' => 32, //字号
'fontColor' => '0,0,0', //字体颜色
'angle' => 0,
);
$titleTwo = array(
'text'=> mb_substr($data['title'], 12, 12),//TODO 标题
'left'=>76,
'top'=>120,
'fontPath'=>app()->getRootPath().'public/static/font/Alibaba-PuHuiTi-Regular.otf', //字体文件
'fontSize'=>32, //字号
'fontColor'=>'0,0,0', //字体颜色
'angle'=>0,
'text' => mb_substr($data['title'], 12, 12),//TODO 标题
'left' => 76,
'top' => 120,
'fontPath' => app()->getRootPath() . 'public/static/font/Alibaba-PuHuiTi-Regular.otf', //字体文件
'fontSize' => 32, //字号
'fontColor' => '0,0,0', //字体颜色
'angle' => 0,
);
array_push($config['text'],$titleOne);
array_push($config['text'],$titleTwo);
array_push($config['text'], $titleOne);
array_push($config['text'], $titleTwo);
}
return self::setSharePoster($config, $path);
}
@ -443,70 +447,71 @@ class UtilService
* @return array|bool|string
* @throws \Exception
*/
public static function setSharePoster($config = array(), $path){
public static function setSharePoster($config = array(), $path)
{
$imageDefault = array(
'left'=>0,
'top'=>0,
'right'=>0,
'bottom'=>0,
'width'=>100,
'height'=>100,
'opacity'=>100
'left' => 0,
'top' => 0,
'right' => 0,
'bottom' => 0,
'width' => 100,
'height' => 100,
'opacity' => 100
);
$textDefault = array(
'text'=>'',
'left'=>0,
'top'=>0,
'fontSize'=>32, //字号
'fontColor'=>'255,255,255', //字体颜色
'angle'=>0,
'text' => '',
'left' => 0,
'top' => 0,
'fontSize' => 32, //字号
'fontColor' => '255,255,255', //字体颜色
'angle' => 0,
);
$background = $config['background'];//海报最底层得背景
$backgroundInfo = getimagesize($background);
$background = imagecreatefromstring(file_get_contents($background));
$backgroundWidth = $backgroundInfo[0]; //背景宽度
$backgroundHeight = $backgroundInfo[1]; //背景高度
$imageRes = imageCreatetruecolor($backgroundWidth,$backgroundHeight);
$imageRes = imageCreatetruecolor($backgroundWidth, $backgroundHeight);
$color = imagecolorallocate($imageRes, 0, 0, 0);
imagefill($imageRes, 0, 0, $color);
imagecopyresampled($imageRes,$background,0,0,0,0,imagesx($background),imagesy($background),imagesx($background),imagesy($background));
if(!empty($config['image'])){
imagecopyresampled($imageRes, $background, 0, 0, 0, 0, imagesx($background), imagesy($background), imagesx($background), imagesy($background));
if (!empty($config['image'])) {
foreach ($config['image'] as $key => $val) {
$val = array_merge($imageDefault,$val);
$val = array_merge($imageDefault, $val);
$info = getimagesize($val['url']);
$function = 'imagecreatefrom'.image_type_to_extension($info[2], false);
if($val['stream']){
$function = 'imagecreatefrom' . image_type_to_extension($info[2], false);
if ($val['stream']) {
$info = getimagesizefromstring($val['url']);
$function = 'imagecreatefromstring';
}
$res = $function($val['url']);
$resWidth = $info[0];
$resHeight = $info[1];
$canvas=imagecreatetruecolor($val['width'], $val['height']);
$canvas = imagecreatetruecolor($val['width'], $val['height']);
imagefill($canvas, 0, 0, $color);
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['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']);//左,上,右,下,宽度,高度,透明度
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['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']);//左,上,右,下,宽度,高度,透明度
}
}
if(isset($config['text']) && !empty($config['text'])){
if (isset($config['text']) && !empty($config['text'])) {
foreach ($config['text'] as $key => $val) {
$val = array_merge($textDefault,$val);
list($R,$G,$B) = explode(',', $val['fontColor']);
$val = array_merge($textDefault, $val);
list($R, $G, $B) = explode(',', $val['fontColor']);
$fontColor = imagecolorallocate($imageRes, $R, $G, $B);
$val['left'] = $val['left']<0?$backgroundWidth- abs($val['left']):$val['left'];
$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']);
$val['left'] = $val['left'] < 0 ? $backgroundWidth - abs($val['left']) : $val['left'];
$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']);
}
}
ob_start();
imagejpeg ($imageRes);
imagejpeg($imageRes);
imagedestroy($imageRes);
$res = ob_get_contents();
ob_end_clean();
$key = substr(md5(rand(0, 9999)) , 0, 5). date('YmdHis') . rand(0, 999999) . '.jpg';
return UploadService::getInstance()->setUploadPath($path)->imageStream($key,$res);
$key = substr(md5(rand(0, 9999)), 0, 5) . date('YmdHis') . rand(0, 999999) . '.jpg';
return UploadService::getInstance()->setUploadPath($path)->imageStream($key, $res);
}
/*
@ -516,7 +521,7 @@ class UtilService
* */
public static function getCurrentController()
{
return strtolower(app('http')->getName().'/'.request()->controller().'/'.request()->action());
return strtolower(app('http')->getName() . '/' . request()->controller() . '/' . request()->action());
}
/**
@ -530,32 +535,35 @@ class UtilService
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curl);
$result = json_decode($result,true);
if(is_array($result)) return ['status'=>false,'msg'=>$result['errcode'].'---'.$result['errmsg']];
return ['status'=>true];
$result = json_decode($result, true);
if (is_array($result)) return ['status' => false, 'msg' => $result['errcode'] . '---' . $result['errmsg']];
return ['status' => true];
}
/**
* TODO 修改 https http
* @param $url $url 域名
* @param int $type 0 返回https 1 返回 http
* @param int $type 0 返回https 1 返回 http
* @return string
*/
public static function setHttpType($url, $type = 0)
{
$domainTop = substr($url,0,5);
if($type){ if($domainTop == 'https') $url = 'http'.substr($url,5,strlen($url)); }
else{ if($domainTop != 'https') $url = 'https:'.substr($url,5,strlen($url)); }
$domainTop = substr($url, 0, 5);
if ($type) {
if ($domainTop == 'https') $url = 'http' . substr($url, 5, strlen($url));
} else {
if ($domainTop != 'https') $url = 'https:' . substr($url, 5, strlen($url));
}
return $url;
}
public static function setSiteUrl($image, $siteUrl = '')
{
if(!strlen(trim($siteUrl))) $siteUrl = sysConfig('site_url');
$domainTop = substr($image,0,4);
if($domainTop == 'http') return $image;
if (!strlen(trim($siteUrl))) $siteUrl = sysConfig('site_url');
$domainTop = substr($image, 0, 4);
if ($domainTop == 'http') return $image;
$image = str_replace('\\', '/', $image);
return $siteUrl.$image;
return $siteUrl . $image;
}
/**
@ -566,16 +574,16 @@ class UtilService
public static function CurlFileExist($url)
{
$ch = curl_init();
try{
curl_setopt ($ch, CURLOPT_URL, $url);
try {
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
$contents = curl_exec($ch);
if (preg_match("/404/", $contents)) return false;
if (preg_match("/403/", $contents)) return false;
return true;
}catch (\Exception $e){
} catch (\Exception $e) {
return false;
}
}
@ -588,26 +596,26 @@ class UtilService
*/
public static function getQRCodePath($url, $name)
{
if(!strlen(trim($url)) || !strlen(trim($name))) return false;
try{
if (!strlen(trim($url)) || !strlen(trim($name))) return false;
try {
$uploadType = sysConfig('upload_type');
//TODO 没有选择默认使用本地上传
if (!$uploadType) $uploadType = 1;
$siteUrl = sysConfig('site_url');
if(!$siteUrl) return '请前往后台设置->系统设置->网站域名 填写您的域名格式为http://域名';
if (!$siteUrl) return '请前往后台设置->系统设置->网站域名 填写您的域名格式为http://域名';
$info = [];
$outfile = Config::get('qrcode.cache_dir');
$code = new QRcode();
$wapCodePath = $code->png($url, $outfile.'/'.$name)->getPath(); //获取二维码生成的地址
$content = file_get_contents('.'.$wapCodePath);
$wapCodePath = $code->png($url, $outfile . '/' . $name)->getPath(); //获取二维码生成的地址
$content = file_get_contents('.' . $wapCodePath);
switch ($uploadType) {
case 1 :
$info["code"] = 200;
$info["name"] = $name;
$info["dir"] = $wapCodePath;
$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['type'] = $headerArray['Content-Type'];
$info["image_type"] = 1;
@ -620,7 +628,7 @@ class UtilService
if (is_array($item)) {
$info = Qiniu::imageUrl($item['key']);
$info['dir'] = UtilService::setHttpType($info['dir']);
$headerArray = UploadService::getImageHeaders( $info['dir']);
$headerArray = UploadService::getImageHeaders($info['dir']);
$info['size'] = $headerArray['Content-Length'];
$info['type'] = $headerArray['Content-Type'];
$info['image_type'] = 2;
@ -638,14 +646,14 @@ class UtilService
$serverImageInfo['info']['url'] = UtilService::setHttpType($serverImageInfo['info']['url']);
$info['dir'] = $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['type'] = $headerArray['Content-Type'];
$info['time'] = time();
$info['image_type'] = 3;
break;
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_object($serverImageInfo)) $serverImageInfo = $serverImageInfo->toArray();
$serverImageInfo['ObjectURL'] = $imageUrl;
@ -653,7 +661,7 @@ class UtilService
$info['name'] = substr(strrchr($serverImageInfo['ObjectURL'], '/'), 1);
$info['dir'] = $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['type'] = $headerArray['Content-Type'];
$info['time'] = time();
@ -663,7 +671,7 @@ class UtilService
return '上传类型错误,请先选择文件上传类型';
}
return $info;
}catch (\Exception $e){
} catch (\Exception $e) {
return $e->getMessage();
}
}
@ -673,19 +681,20 @@ class UtilService
* @param string $avatar
* @return bool|string
*/
public static function setImageBase64($avatar = '',$timeout=9){
try{
$url=parse_url($avatar);
$url=$url['host'];
public static function setImageBase64($avatar = '', $timeout = 9)
{
try {
$url = parse_url($avatar);
$url = $url['host'];
$header = [
'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-Encoding: gzip, deflate',
'Host:'.$url
'Host:' . $url
];
$dir= pathinfo($url);
$dir = pathinfo($url);
$host = $dir['dirname'];
$refer= $host.'/';
$refer = $host . '/';
$curl = curl_init();
curl_setopt($curl, CURLOPT_REFERER, $refer);
curl_setopt($curl, CURLOPT_URL, $avatar);
@ -697,9 +706,9 @@ class UtilService
$data = curl_exec($curl);
$code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
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;
}catch (\Exception $e){
} catch (\Exception $e) {
return false;
}
}

View File

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

View File

@ -50,7 +50,7 @@ class WechatTemplateService implements ProviderInterface
const ORDER_USER_GROUPS_SUCCESS = 'OPENTM407456411';
//拼团失败通知
const ORDER_USER_GROUPS_LOSE = 'OPENTM401113750';
const ORDER_USER_GROUPS_LOSE = 'OPENTM401113750';
//开团成功
const OPEN_PINK_SUCCESS = 'OPENTM414349441';
@ -58,10 +58,11 @@ class WechatTemplateService implements ProviderInterface
//砍价成功
const BARGAIN_SUCCESS = 'OPENTM410292733';
public static function getConstants($code='') {
public static function getConstants($code = '')
{
$oClass = new \ReflectionClass(__CLASS__);
$stants=$oClass->getConstants();
if($code) return isset($stants[$code]) ? $stants[$code] : '';
$stants = $oClass->getConstants();
if ($code) return isset($stants[$code]) ? $stants[$code] : '';
else return $stants;
}
@ -79,13 +80,13 @@ class WechatTemplateService implements ProviderInterface
* @param string $defaultColor
* @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');
if(!$tempid) return false;
try{
return WechatService::sendTemplate($openid,$tempid,$data,$url,$defaultColor);
}catch (\Exception $e){
$tempid = WechatTemplateModel::where('tempkey', $templateId)->where('status', 1)->value('tempid');
if (!$tempid) return false;
try {
return WechatService::sendTemplate($openid, $tempid, $data, $url, $defaultColor);
} catch (\Exception $e) {
dump($e->getMessage());
return false;
}
@ -97,24 +98,24 @@ class WechatTemplateService implements ProviderInterface
* @param string $defaultColor
* @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')));
$kefuIds = ServiceModel::where('notify',1)->column('uid','uid');
if(empty($adminIds[0])){
$adminIds = explode(',', trim(sysConfig('site_store_admin_uids')));
$kefuIds = ServiceModel::where('notify', 1)->column('uid', 'uid');
if (empty($adminIds[0])) {
$adminList = array_unique($kefuIds);
}else{
$adminList = array_unique(array_merge($adminIds,$kefuIds));
} else {
$adminList = array_unique(array_merge($adminIds, $kefuIds));
}
if(!is_array($adminList) || empty($adminList)) return false;
foreach ($adminList as $uid){
try{
if (!is_array($adminList) || empty($adminList)) return false;
foreach ($adminList as $uid) {
try {
$openid = WechatUser::uidToOpenid($uid, 'openid');
if(!$openid) continue;
}catch (\Exception $e){
if (!$openid) continue;
} catch (\Exception $e) {
continue;
}
self::sendTemplate($openid,self::ADMIN_NOTICE,$data,$url,$defaultColor);
self::sendTemplate($openid, self::ADMIN_NOTICE, $data, $url, $defaultColor);
}
}
@ -129,48 +130,48 @@ class WechatTemplateService implements ProviderInterface
/**
* 修改账号所属行业
* 主行业 副行业 代码
* IT科技 互联网/电子商务 1
* IT科技 IT软件与服务 2
* IT科技 IT硬件与设备 3
* IT科技 电子技术 4
* IT科技 通信与运营商 5
* IT科技 网络游戏 6
* 金融业 银行 7
* 金融业 基金|理财|信托 8
* 金融业 保险 9
* 餐饮 餐饮 10
* 酒店旅游 酒店 11
* 酒店旅游 旅游 12
* 运输与仓储 快递 13
* 运输与仓储 物流 14
* 运输与仓储 仓储 15
* 教育 培训 16
* 教育 院校 17
* 政府与公共事业 学术科研 18
* 政府与公共事业 交警 19
* 政府与公共事业 博物馆 20
* 政府与公共事业 公共事业|非盈利机构 21
* 医药护理 医药医疗 22
* 医药护理 护理美容 23
* 医药护理 保健与卫生 24
* 交通工具 汽车相关 25
* 交通工具 摩托车相关 26
* 交通工具 火车相关 27
* 交通工具 飞机相关 28
* 房地产 建筑 29
* 房地产 物业 30
* 消费品 消费品 31
* 商业服务 法律 32
* 商业服务 会展 33
* 商业服务 中介服务 34
* 商业服务 认证 35
* 商业服务 审计 36
* 文体娱乐 传媒 37
* 文体娱乐 体育 38
* 文体娱乐 娱乐休闲 39
* 印刷 印刷 40
* 其它 其它 41
* 主行业 副行业 代码
* IT科技 互联网/电子商务 1
* IT科技 IT软件与服务 2
* IT科技 IT硬件与设备 3
* IT科技 电子技术 4
* IT科技 通信与运营商 5
* IT科技 网络游戏 6
* 金融业 银行 7
* 金融业 基金|理财|信托 8
* 金融业 保险 9
* 餐饮 餐饮 10
* 酒店旅游 酒店 11
* 酒店旅游 旅游 12
* 运输与仓储 快递 13
* 运输与仓储 物流 14
* 运输与仓储 仓储 15
* 教育 培训 16
* 教育 院校 17
* 政府与公共事业 学术科研 18
* 政府与公共事业 交警 19
* 政府与公共事业 博物馆 20
* 政府与公共事业 公共事业|非盈利机构 21
* 医药护理 医药医疗 22
* 医药护理 护理美容 23
* 医药护理 保健与卫生 24
* 交通工具 汽车相关 25
* 交通工具 摩托车相关 26
* 交通工具 火车相关 27
* 交通工具 飞机相关 28
* 房地产 建筑 29
* 房地产 物业 30
* 消费品 消费品 31
* 商业服务 法律 32
* 商业服务 会展 33
* 商业服务 中介服务 34
* 商业服务 认证 35
* 商业服务 审计 36
* 文体娱乐 传媒 37
* 文体娱乐 体育 38
* 文体娱乐 娱乐休闲 39
* 印刷 印刷 40
* 其它 其它 41
* @param $industryId1
* @param $industryId2
* @return \EasyWeChat\Support\Collection

View File

@ -3,48 +3,52 @@
namespace crmeb\services;
use app\models\system\Cache as CacheModel;
use crmeb\interfaces\ProviderInterface;
use crmeb\traits\LogicTrait;
/**
* Class YLYService
* @package crmeb\services
*/
class YLYService extends HttpService
class YLYService extends HttpService implements ProviderInterface
{
use LogicTrait;
/**
* 开发者创建的应用的应用ID
* @var string
*/
protected $client_id;
protected $client_id;
/**
* 开发者创建的应用的秘钥
* @var string
*/
protected $apiKey;
protected $apiKey;
/**
* 开发者id
* @var string
*/
protected $partner;
protected $partner;
/**
* 易联云token
* @var null
*/
protected $access_token=null;
protected $access_token = null;
/**
* 订单编号
* @var null
*/
protected $order_id=null;
protected $order_id = null;
/**
* 终端号码
* @var string
*/
protected $terminal;
protected $terminal;
/**
* 打印内容
@ -56,57 +60,48 @@ class YLYService extends HttpService
* 请求地址
* @var string
*/
protected $apiUrl = 'https://open-api.10ss.net/';
protected $apiUrl = 'https://open-api.10ss.net/';
/**
* 本类实例化句柄
* @var
*/
protected static $instance;
public function register($congig = [])
{
}
/**
* YLYService constructor.
*/
protected function __construct()
{
$system = SystemConfigService::more(['develop_id','printing_api_key','printing_client_id','terminal_number']);
$this->partner = $system['develop_id'] ?? '';
$this->apiKey = $system['printing_api_key'] ?? '';
$system = SystemConfigService::more(['develop_id', 'printing_api_key', 'printing_client_id', 'terminal_number']);
$this->partner = $system['develop_id'] ?? '';
$this->apiKey = $system['printing_api_key'] ?? '';
$this->client_id = $system['printing_client_id'] ?? '';
$this->terminal = $system['terminal_number'] ?? '';
$this->terminal = $system['terminal_number'] ?? '';
$this->getAccessToken();
}
/**
* 实例化本类
* @return YLYService
*/
public static function getInstance()
{
if(is_null(self::$instance)) self::$instance = new self();
return self::$instance;
}
/**
* 获取AccessToken
* */
protected function getAccessToken(){
protected function getAccessToken()
{
$token = CacheModel::getDbCache('YLY_access_token');
if(!$token){
$request = self::postRequest($this->apiUrl.'oauth/oauth',[
if (!$token) {
$request = self::postRequest($this->apiUrl . 'oauth/oauth', [
'client_id' => $this->client_id,
'grant_type'=> 'client_credentials',
'sign' => strtolower(md5($this->client_id.time().$this->apiKey)),
'scope' => 'all',
'grant_type' => 'client_credentials',
'sign' => strtolower(md5($this->client_id . time() . $this->apiKey)),
'scope' => 'all',
'timestamp' => time(),
'id' => $this->createUuid(),
'id' => $this->createUuid(),
]);
$request = json_decode($request,true);
$request['error'] = $request['error'] ?? 0;
$request = json_decode($request, true);
$request['error'] = $request['error'] ?? 0;
$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'] ?? '';
CacheModel::setDbCache('YLY_access_token',$token);
CacheModel::setDbCache('YLY_access_token', $token);
}
}
$this->access_token = $token;
@ -116,9 +111,10 @@ class YLYService extends HttpService
* 生成UUID4
* @return string
*/
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 ));
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));
}
/**
@ -129,18 +125,18 @@ class YLYService extends HttpService
*/
public function orderPrinting(string $order_id = '')
{
$request=self::postRequest($this->apiUrl.'print/index',[
'client_id' => $this->client_id,
'access_token' => $this->access_token,
'machine_code' => $this->terminal,
'content' => $this->content,
'origin_id' => $order_id ? $order_id : $this->order_id,
'sign' => strtolower(md5($this->client_id.time().$this->apiKey)),
'id' => $this->createUuid(),
'timestamp' => time()
$request = self::postRequest($this->apiUrl . 'print/index', [
'client_id' => $this->client_id,
'access_token' => $this->access_token,
'machine_code' => $this->terminal,
'content' => $this->content,
'origin_id' => $order_id ? $order_id : $this->order_id,
'sign' => strtolower(md5($this->client_id . time() . $this->apiKey)),
'id' => $this->createUuid(),
'timestamp' => time()
]);
if($request === false) return false;
return json_decode($request,true);
if ($request === false) return false;
return json_decode($request, true);
}
/**
@ -150,16 +146,16 @@ class YLYService extends HttpService
*/
public function deletePrinter($machine_code)
{
$request = self::postRequest($this->apiUrl.'printer/deleteprinter',[
'client_id' => $this->client_id,
'access_token' => $this->access_token,
'machine_code' => $machine_code,
'sign' => strtolower(md5($this->client_id.time().$this->apiKey)),
'id' => $this->createUuid(),
'timestamp' => time(),
$request = self::postRequest($this->apiUrl . 'printer/deleteprinter', [
'client_id' => $this->client_id,
'access_token' => $this->access_token,
'machine_code' => $machine_code,
'sign' => strtolower(md5($this->client_id . time() . $this->apiKey)),
'id' => $this->createUuid(),
'timestamp' => time(),
]);
if($request === false) return false;
return json_decode($request,true);
if ($request === false) return false;
return json_decode($request, true);
}
/**
@ -169,18 +165,19 @@ class YLYService extends HttpService
* @param array $product 订单详情
* @return $this
*/
public function setContent(string $name,array $orderInfo,array $product){
$timeYmd = date('Y-m-d',time());
$timeHis = date('H:i:s',time());
public function setContent(string $name, array $orderInfo, array $product)
{
$timeYmd = date('Y-m-d', time());
$timeHis = date('H:i:s', time());
$goodsStr = '<table><tr><td>商品名称</td><td>数量</td><td>单价</td><td>金额</td></tr>';
foreach ($product as $item){
$goodsStr.='<tr>';
$goodsStr.="<td>{$item['productInfo']['store_name']}</td><td>{$item['cart_num']}</td><td>{$item['productInfo']['price']}</td><td>{$item['truePrice']}</td>";
$goodsStr.='</tr>';
foreach ($product as $item) {
$goodsStr .= '<tr>';
$goodsStr .= "<td>{$item['productInfo']['store_name']}</td><td>{$item['cart_num']}</td><td>{$item['productInfo']['price']}</td><td>{$item['truePrice']}</td>";
$goodsStr .= '</tr>';
}
$goodsStr.='</table>';
$goodsStr .= '</table>';
$this->order_id = $orderInfo['order_id'];
$count=<<<CONTENT
$count = <<<CONTENT
<FB><center> ** {$name} **</center></FB>
<FH2><FW2>----------------</FW2></FH2>
订单编号:{$orderInfo['order_id']}\r
@ -212,8 +209,8 @@ 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
namespace crmeb\services\storage;
use crmeb\services\SystemConfigService;
@ -32,34 +33,35 @@ class COS
* @return null|Client
* @throws \Exception
*/
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'))){
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'))) {
self::$accessKey = $accessKey;
self::$secretKey = $secretKey;
self::$uploadUrl = $uploadUrl;
self::$storageName = $storageName;
self::$storageRegion = $storageRegion;
}else{
} else {
self::$accessKey = trim(sysConfig('accessKey'));
self::$secretKey = trim(sysConfig('secretKey'));
self::$uploadUrl = trim(sysConfig('uploadUrl')).'/';
self::$uploadUrl = trim(sysConfig('uploadUrl')) . '/';
self::$storageName = trim(sysConfig('storage_name'));
self::$storageRegion = trim(sysConfig('storage_region'));
Cache::set('accessKey',self::$accessKey);
Cache::set('secretKey',self::$secretKey);
Cache::set('uploadUrl',self::$uploadUrl);
Cache::set('storageName',self::$storageName);
Cache::set('storageRegion',self::$storageRegion);
Cache::set('accessKey', self::$accessKey);
Cache::set('secretKey', self::$secretKey);
Cache::set('uploadUrl', self::$uploadUrl);
Cache::set('storageName', self::$storageName);
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 和 空间域名 和 存储空间名称');
}
if(self::$auth == null) {
if (self::$auth == null) {
self::$auth = new Client([
'region'=>self::$storageRegion,
'credentials'=>[
'secretId'=>self::$accessKey,
'secretKey'=>self::$secretKey,
'region' => self::$storageRegion,
'credentials' => [
'secretId' => self::$accessKey,
'secretKey' => self::$secretKey,
]
]);
}
@ -71,21 +73,22 @@ class COS
* @param string $filename
* @return string
*/
public static function uploadImage($filename = 'image'){
public static function uploadImage($filename = 'image')
{
$request = app('request');
$file = $request->file($filename);
$filePath = $file->getRealPath();
$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 {
self::autoInfo();
return [self::$uploadUrl.$key,self::$auth->putObject([
return [self::$uploadUrl . $key, self::$auth->putObject([
'Bucket' => self::$storageName,
'Key' => $key,
'Body' => fopen($filePath, 'rb')
])];
} catch (\Exception $e) {
return [false,$e->getMessage()];
return [false, $e->getMessage()];
}
}
@ -95,16 +98,17 @@ class COS
* @param $content
* @return string
*/
public static function uploadImageStream($key, $content){
public static function uploadImageStream($key, $content)
{
try {
self::autoInfo();
return [self::$uploadUrl.$key,self::$auth->putObject([
return [self::$uploadUrl . $key, self::$auth->putObject([
'Bucket' => self::$storageName,
'Key' => $key,
'Body' => $content
])];
} catch (\Exception $e) {
return [false,$e->getMessage()];
return [false, $e->getMessage()];
}
}
@ -113,7 +117,8 @@ class COS
* @param $key
* @return mixed
*/
public static function delete($key){
public static function delete($key)
{
try {
self::autoInfo();
return self::$auth->deleteObject([

View File

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

View File

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

View File

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

View File

@ -1,4 +1,5 @@
<?php
namespace crmeb\subscribes;
use app\admin\model\wechat\WechatMessage;
@ -31,18 +32,19 @@ class MessageSubscribe
*/
public function onAdminNewPush($event)
{
try{
$data['ordernum'] = StoreOrder::where('paid',1)->where('status',0)
->where('shipping_type',1)->where('refund_status',0)
->where('is_del',0)->count();
try {
$data['ordernum'] = StoreOrder::where('paid', 1)->where('status', 0)
->where('shipping_type', 1)->where('refund_status', 0)
->where('is_del', 0)->count();
$store_stock = sysConfig('store_stock');
if($store_stock < 0) $store_stock = 2;
$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['reflectnum'] = UserExtract::where('status',0)->count();//提现
if ($store_stock < 0) $store_stock = 2;
$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['reflectnum'] = UserExtract::where('status', 0)->count();//提现
$data['msgcount'] = intval($data['ordernum']) + intval($data['inventory']) + intval($data['commentnum']) + intval($data['reflectnum']);
ChannelService::instance()->send('ADMIN_NEW_PUSH',$data);
}catch (\Exception $e){}
ChannelService::instance()->send('ADMIN_NEW_PUSH', $data);
} catch (\Exception $e) {
}
}
/**
@ -55,10 +57,10 @@ class MessageSubscribe
WechatUser::saveUser($message->FromUserName);
$event = isset($message->Event) ?
$message->MsgType.(
$message->MsgType . (
$message->Event == 'subscribe' && isset($message->EventKey) ? '_scan' : ''
).'_'.$message->Event : $message->MsgType;
WechatMessage::setMessage(json_encode($message),$message->FromUserName,strtolower($event));
) . '_' . $message->Event : $message->MsgType;
WechatMessage::setMessage(json_encode($message), $message->FromUserName, strtolower($event));
}
/**
@ -86,21 +88,22 @@ class MessageSubscribe
public function onShortMssageSend($event)
{
//$actions 可为数组
list($order_id,$actions) = $event;
try{
if(is_array($actions)){
foreach ($actions as $action){
$actionName = 'MssageSend'.$action;
if(method_exists($this,$actionName)) $this->$actionName($order_id);
list($order_id, $actions) = $event;
try {
if (is_array($actions)) {
foreach ($actions as $action) {
$actionName = 'MssageSend' . $action;
if (method_exists($this, $actionName)) $this->$actionName($order_id);
}
}else{
$actionName = 'MssageSend'.$actions;
if(method_exists($this,$actionName)) $this->$actionName($order_id);
} else {
$actionName = 'MssageSend' . $actions;
if (method_exists($this, $actionName)) $this->$actionName($order_id);
}
}catch (\Exception $e){
Log::error('短信下发事件发生系统错误,错误原因:'.$e->getMessage());
} catch (\Exception $e) {
Log::error('短信下发事件发生系统错误,错误原因:' . $e->getMessage());
}
}
/**
* 发送短信
* @param boolean $switch 发送开关
@ -109,9 +112,9 @@ class MessageSubscribe
* @param int $template 模板编号
* @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);
$res = SMSService::send($phone, $template, $data);
if ($res['status'] == 400) Log::info($logMsg);
@ -124,12 +127,12 @@ class MessageSubscribe
*/
public function MssageSendPaySuccess($order_id)
{
$storeInfo = StoreOrder::where(['order_id'=>$order_id,'paid'=>1,'refund_status'=>0])->find();
if(!$storeInfo) return;
$storeInfo = StoreOrder::where(['order_id' => $order_id, 'paid' => 1, 'refund_status' => 0])->find();
if (!$storeInfo) return;
$switch = sysConfig('lower_order_switch') ? true : false;
//模板变量
$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)
{
$storeInfo = StoreOrder::where(['order_id'=>$order_id,'paid'=>1,'refund_status'=>0,'status'=>1])->find();
if(!$storeInfo) return;
$storeInfo = StoreOrder::where(['order_id' => $order_id, 'paid' => 1, 'refund_status' => 0, 'status' => 1])->find();
if (!$storeInfo) return;
$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);
$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)
{
$storeInfo = StoreOrder::where(['order_id'=>$order_id,'paid'=>1,'refund_status'=>0,'status'=>2])->find();
if(!$storeInfo) return;
$storeInfo = StoreOrder::where(['order_id' => $order_id, 'paid' => 1, 'refund_status' => 0, 'status' => 2])->find();
if (!$storeInfo) return;
$switch = sysConfig('confirm_take_over_switch') ? true : false;
//模板变量
$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)
{
$storeInfo = StoreOrder::where(['order_id'=>$order_id,'paid'=>0,'refund_status'=>0,'status'=>0])->find();
if(!$storeInfo) return;
$storeInfo = StoreOrder::where(['order_id' => $order_id, 'paid' => 0, 'refund_status' => 0, 'status' => 0])->find();
if (!$storeInfo) return;
$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;
$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)
{
$storeInfo = StoreOrder::where(['order_id'=>$order_id,'paid'=>1,'refund_status'=>0,'status'=>0])->find();
if(!$storeInfo) return;
$storeInfo = StoreOrder::where(['order_id' => $order_id, 'paid' => 1, 'refund_status' => 0, 'status' => 0])->find();
if (!$storeInfo) return;
$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;
$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)
{
$storeInfo = StoreOrder::where(['order_id'=>$order_id,'paid'=>1,'refund_status'=>0,'status'=>2])->find();
if(!$storeInfo) return;
$storeInfo = StoreOrder::where(['order_id' => $order_id, 'paid' => 1, 'refund_status' => 0, 'status' => 2])->find();
if (!$storeInfo) return;
$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;
$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)
{
$storeInfo = StoreOrder::where(['order_id'=>$order_id,'paid'=>1,'refund_status'=>1])->find();
if(!$storeInfo) return;
$storeInfo = StoreOrder::where(['order_id' => $order_id, 'paid' => 1, 'refund_status' => 1])->find();
if (!$storeInfo) return;
$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;
$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 回调函数
@ -235,10 +239,10 @@ class MessageSubscribe
public function getAdminNoticeAuth(callable $callable)
{
$serviceOrderNotice = StoreService::getStoreServiceOrderNotice();
if(count($serviceOrderNotice)) {
if (count($serviceOrderNotice)) {
foreach ($serviceOrderNotice as $uid) {
$userInfo= User::where('uid',$uid)->field('phone,nickname')->find();
if($userInfo && is_callable($callable)) $callable($userInfo);
$userInfo = User::where('uid', $uid)->field('phone,nickname')->find();
if ($userInfo && is_callable($callable)) $callable($userInfo);
}
}
}

View File

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

View File

@ -1,4 +1,5 @@
<?php
namespace crmeb\subscribes;
/**
@ -21,28 +22,30 @@ class ProductSubscribe
*/
public function onStoreProductSetCartAfter($event)
{
list($cartInfo, $userInfo) = $event;
//$cartInfo 购物车信息
//$userInfo 用户信息
list($cartInfo, $userInfo) = $event;
//$cartInfo 购物车信息
//$userInfo 用户信息
}
/**
* 用户操作产品添加事件 用户点赞产品 用户收藏产品
* @param $event
*/
public function onStoreProductUserOperationConfirmAfter($event){
list($category, $productId, $relationType, $uid) = $event;
//$category 产品类型
//$productId 产品编号
//$relationType 操作类型 like 点赞 collect 收藏
//$uid 用户编号
public function onStoreProductUserOperationConfirmAfter($event)
{
list($category, $productId, $relationType, $uid) = $event;
//$category 产品类型
//$productId 产品编号
//$relationType 操作类型 like 点赞 collect 收藏
//$uid 用户编号
}
/**
* 用户操作产品取消事件 用户取消点赞产品 用户取消收藏产品
* @param $event
*/
public function onStoreProductUserOperationCancelAfter($event){
public function onStoreProductUserOperationCancelAfter($event)
{
list($category, $productId, $relationType, $uid) = $event;
//$category 产品类型
//$productId 产品编号

View File

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

View File

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

View File

@ -41,24 +41,24 @@ class UserSubscribe
*/
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;
$wechatInfo['nickname'] = filterEmoji($wechatInfo['nickname']);
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');
if (!User::be(['uid' => $uid])) {
$wechatInfo = WechatUser::where('uid', $uid)->find();
User::setWechatUser($wechatInfo, $spreadId);
} else {
if($login_type) $wechatInfo['login_type'] = $login_type;
if ($login_type) $wechatInfo['login_type'] = $login_type;
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');
if($login_type) $wechatInfo['login_type'] = $login_type;
if ($login_type) $wechatInfo['login_type'] = $login_type;
User::updateWechatUser($wechatInfo, $uid);
} else {
if (isset($wechatInfo['subscribe_scene'])) unset($wechatInfo['subscribe_scene']);
@ -80,7 +80,7 @@ class UserSubscribe
// User::where('uid', $wechatInfo['uid'])
// ->limit(1)->update(['openid' => $wechatInfo['openid']]);
// else
User::setWechatUser($wechatInfo, $spreadId);
User::setWechatUser($wechatInfo, $spreadId);
}
$uid = WechatUser::openidToUid($openid, 'openid');
// 设置推广关系

View File

@ -29,19 +29,19 @@ trait LogicTrait
* @param $params 参数
* @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
*/
protected function setConfig(array $config=[])
protected function setConfig(array $config = [])
{
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()
{
if (property_exists($this,'providers'))
{
foreach ($this->providers as $key=>$provider)
{
$this->register(new $provider(),$key);
if (property_exists($this, 'providers')) {
foreach ($this->providers as $key => $provider) {
$this->register(new $provider(), $key);
}
}
}
@ -86,14 +84,14 @@ trait LogicTrait
* @param object $pimple
* @return $this
* */
protected function register($pimple,$key)
protected function register($pimple, $key)
{
$response=$pimple->register($this->items);
if(is_array($response)) {
list($key,$provider)=$response;
$this->$key= $provider;
}else if(is_string($key)){
$this->$key= $pimple;
$response = $pimple->register($this->items);
if (is_array($response)) {
[$key, $provider] = $response;
$this->$key = $provider;
} else if (is_string($key)) {
$this->$key = $pimple;
}
return $this;
}
@ -103,13 +101,14 @@ trait LogicTrait
* @param array $config
* @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->setConfig($config);
self::$instance->registerProviders();
self::$instance->bool();
if (method_exists(self::$instance, 'bool'))
self::$instance->bool();
}
return self::$instance;
}
@ -144,36 +143,35 @@ trait LogicTrait
* @param $ages
* @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];
$type = $propsRuleValeu[1] ?? 'string';
$callable = $propsRuleValeu[2] ?? null;
$type = $propsRuleValeu[1] ?? 'string';
$callable = $propsRuleValeu[2] ?? null;
if ($type == 'callable' && $callable) {
$callable = $propsRuleValeu[2];
if (method_exists($this,$callable))
$ages[0] = $this->{$callable}($ages[0],$ages[1] ?? '');
if (method_exists($this, $callable))
$ages[0] = $this->{$callable}($ages[0], $ages[1] ?? '');
} else if($type) {
$ages[0] = $this->toType($ages[0],$type) ?? null;
} else if ($type) {
$ages[0] = $this->toType($ages[0], $type) ?? null;
}
$this->{$attribute} = $ages[0];
return $this;
}
} else if(in_array($method,$keys)) {
} else if (in_array($method, $keys)) {
$this->sendType = $method;
return $this;
} 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 setSendType($sendType) 设置发送类型句柄 1 = 小程序 2 = 公众号
* @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 wechat() 设置当前发送类型句柄为 公众号
*/
@ -34,9 +34,9 @@ class Template
* 注册服务 会自动添加$providers对应的key名称方法方便设置$sendType
* @var array
*/
protected $providers = [
'routine' => \crmeb\services\ProgramTemplateService::class,
'wechat' => \crmeb\services\WechatTemplateService::class,
protected $providers = [
'routine' => \crmeb\services\ProgramTemplateService::class,
'wechat' => \crmeb\services\WechatTemplateService::class,
];
/**
@ -44,14 +44,14 @@ class Template
* @var array 'defaultData'=>[[],'array'] 生成的方法为 setDefaultData(array $value)
*/
protected $propsRule = [
'defaultData' => [null, 'string'],
'templateCode' => [null, 'string'],
'templateData' => [[],'array'],
'templateUrl' => [null, 'callable', 'postpositionUrl'],
'templateFormId' => [null, 'string'],
'sendType' => [null, 'string'],
'templateOpenId' => [null, 'string'],
'templateOpenId' => [null, 'string'],
'defaultData' => [null, 'string'],
'templateCode' => [null, 'string'],
'templateData' => [[], 'array'],
'templateUrl' => [null, 'callable', 'postpositionUrl'],
'templateFormId' => [null, 'string'],
'sendType' => [null, 'string'],
'templateOpenId' => [null, 'string'],
'templateOpenId' => [null, 'string'],
];
/**
@ -82,7 +82,7 @@ class Template
* 模板消息formid 为小程序提供
* @var string
*/
protected $templateFormId ='';
protected $templateFormId = '';
/**
* 发送类型 对应 $providers key
@ -116,7 +116,7 @@ class Template
* @param string $suffix
* @return string
*/
public function postpositionUrl(Url $url,string $suffix = '')
public function postpositionUrl(Url $url, string $suffix = '')
{
return $url->suffix($suffix)->domain(true)->build();
}
@ -128,21 +128,21 @@ class Template
{
$keys = array_keys($this->providers);
if (is_string($this->sendType)) {
if(!in_array($this->sendType,$keys))
throw new AuthException('设置的发送类型句柄不存在:'.$this->sendType);
if (!in_array($this->sendType, $keys))
throw new AuthException('设置的发送类型句柄不存在:' . $this->sendType);
} elseif (is_int($this->sendType)) {
if($this->sendType > count($keys))
throw new AuthException('设置的发送类型句柄不存在:'.$this->sendType);
if ($this->sendType > count($keys))
throw new AuthException('设置的发送类型句柄不存在:' . $this->sendType);
$this->sendType = $keys[$this->sendType - 1];
}
if (!$this->sendType)
throw new AuthException('请设置发送类型句柄');
if(!$this->templateData)
if (!$this->templateData)
throw new AuthException('请设置发送模板数据');
if(!$this->templateOpenId)
if (!$this->templateOpenId)
throw new AuthException('请设置发送模板OPENID');
}
@ -153,12 +153,12 @@ class Template
*/
public function send(bool $excep = false)
{
try{
try {
$this->validate();
$resource = null;
switch ($this->sendType){
switch ($this->sendType) {
case 'routine':
$resource = self::$instance->routine->sendTemplate(
$this->templateCode,
@ -186,8 +186,8 @@ class Template
$this->clear();
return $resource;
}catch (\Throwable $e){
if($excep)
} catch (\Throwable $e) {
if ($excep)
throw new AuthException($e->getMessage());
return false;
}
@ -199,14 +199,14 @@ class Template
*/
protected function clear()
{
$this->templateOpenId = null;
$this->defaultData = null;
$this->templateOpenId = null;
$this->defaultData = null;
$this->templateDefaultColor = null;
$this->templateData = [];
$this->templateUrl = null;
$this->sendType = null;
$this->templateFormId = null;
$this->templateCode = null;
$this->templateData = [];
$this->templateUrl = null;
$this->sendType = null;
$this->templateFormId = null;
$this->templateCode = null;
return $this;
}