格式化服务类

This commit is contained in:
liaofei 2019-11-28 18:40:49 +08:00
parent d236a9da93
commit 5fead1d61a
23 changed files with 1046 additions and 1009 deletions

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

@ -19,7 +19,7 @@ class ExpressService
public static function query($no, $type = '')
{
$appCode = SystemConfigService::config('system_express_app_code');
$appCode = sysConfig('system_express_app_code');
if (!$appCode) return false;
$res = HttpService::getRequest(self::$api['query'], compact('no', 'type'), ['Authorization:APPCODE ' . $appCode]);
$result = json_decode($res, true) ?: false;

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,$cacheName);
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,8 +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;
@ -20,41 +18,38 @@ use app\models\user\UserRecharge;
* Class WechatMinService
* @package service
*/
class MiniProgramService implements ProviderInterface
class MiniProgramService
{
private static $instance = null;
public function register($config)
{
return ['mini_program',new self()];
}
public static function options()
{
$wechat = SystemConfigService::more(['site_url','routine_appId','routine_appsecret']);
$payment = SystemConfigService::more(['pay_routine_mchid','pay_routine_key','pay_routine_client_cert','pay_routine_client_key','pay_weixin_open']);
$wechat = SystemConfigService::more(['site_url', 'routine_appId', 'routine_appsecret']);
$payment = SystemConfigService::more(['pay_routine_mchid', 'pay_routine_key', 'pay_routine_client_cert', 'pay_routine_client_key', 'pay_weixin_open']);
$config = [];
$config['mini_program'] = [
'app_id'=>isset($wechat['routine_appId']) ? trim($wechat['routine_appId']):'',
'secret'=>isset($wechat['routine_appsecret']) ? trim($wechat['routine_appsecret']):'',
'token'=>isset($wechat['wechat_token']) ? trim($wechat['wechat_token']):'',
'aes_key'=> isset($wechat['wechat_encodingaeskey']) ? trim($wechat['wechat_encodingaeskey']):''
'app_id' => isset($wechat['routine_appId']) ? trim($wechat['routine_appId']) : '',
'secret' => isset($wechat['routine_appsecret']) ? trim($wechat['routine_appsecret']) : '',
'token' => isset($wechat['wechat_token']) ? trim($wechat['wechat_token']) : '',
'aes_key' => isset($wechat['wechat_encodingaeskey']) ? trim($wechat['wechat_encodingaeskey']) : ''
];
$config['payment'] = [
'app_id'=>isset($wechat['routine_appId']) ? trim($wechat['routine_appId']) :'',
'merchant_id'=>trim($payment['pay_routine_mchid']),
'key'=>trim($payment['pay_routine_key']),
'cert_path'=>realpath('.'.$payment['pay_routine_client_cert']),
'key_path'=>realpath('.'.$payment['pay_routine_client_key']),
'notify_url'=>$wechat['site_url'].Url::buildUrl('/api/routine/notify')
'app_id' => isset($wechat['routine_appId']) ? trim($wechat['routine_appId']) : '',
'merchant_id' => trim($payment['pay_routine_mchid']),
'key' => trim($payment['pay_routine_key']),
'cert_path' => realpath('.' . $payment['pay_routine_client_cert']),
'key_path' => realpath('.' . $payment['pay_routine_client_key']),
'notify_url' => $wechat['site_url'] . Url::buildUrl('/api/routine/notify')
];
return $config;
}
public static function application($cache = false)
{
(self::$instance === null || $cache === true) && (self::$instance = new Application(self::options()));
return self::$instance;
}
/**
* 小程序接口
* @return \EasyWeChat\MiniProgram\MiniProgram
@ -82,7 +77,8 @@ class MiniProgramService implements ProviderInterface
* @param $encryptData
* @return $userInfo
*/
public static function encryptor($sessionKey, $iv, $encryptData){
public static function encryptor($sessionKey, $iv, $encryptData)
{
return self::miniprogram()->encryptor->decryptData($sessionKey, $iv, $encryptData);
}
@ -124,7 +120,7 @@ class MiniProgramService implements ProviderInterface
*/
public static function appCodeUnlimitService($scene, $page = null, $width = 430, $autoColor = false, $lineColor = ['r' => 0, 'g' => 0, 'b' => 0])
{
return self::qrcodeService()->appCodeUnlimit($scene,$page,$width,$autoColor,$lineColor);
return self::qrcodeService()->appCodeUnlimit($scene, $page, $width, $autoColor, $lineColor);
}
@ -145,12 +141,12 @@ class MiniProgramService implements ProviderInterface
* @param null $defaultColor
* @return mixed
*/
public static function sendTemplate($openid,$templateId,array $data,$form_id,$link = null,$defaultColor = null)
public static function sendTemplate($openid, $templateId, array $data, $form_id, $link = null, $defaultColor = null)
{
$notice = self::noticeService()->to($openid)->template($templateId)->formId($form_id)->andData($data);
$message = [];
if($link !== null) $message = ['page'=>$link];
if($defaultColor !== null) $notice->defaultColor($defaultColor);
if ($link !== null) $message = ['page' => $link];
if ($defaultColor !== null) $notice->defaultColor($defaultColor);
return $notice->send($message);
}
@ -176,11 +172,11 @@ class MiniProgramService implements ProviderInterface
* @param array $options
* @return Order
*/
protected static function paymentOrder($openid,$out_trade_no,$total_fee,$attach,$body,$detail='',$trade_type='JSAPI',$options = [])
protected static function paymentOrder($openid, $out_trade_no, $total_fee, $attach, $body, $detail = '', $trade_type = 'JSAPI', $options = [])
{
$total_fee = bcmul($total_fee,100,0);
$order = array_merge(compact('openid','out_trade_no','total_fee','attach','body','detail','trade_type'),$options);
if($order['detail'] == '') unset($order['detail']);
$total_fee = bcmul($total_fee, 100, 0);
$order = array_merge(compact('openid', 'out_trade_no', 'total_fee', 'attach', 'body', 'detail', 'trade_type'), $options);
if ($order['detail'] == '') unset($order['detail']);
return new Order($order);
}
@ -196,21 +192,22 @@ class MiniProgramService implements ProviderInterface
* @param array $options
* @return mixed
*/
public static function paymentPrepare($openid, $out_trade_no, $total_fee, $attach, $body, $detail='', $trade_type='JSAPI', $options = [])
public static function paymentPrepare($openid, $out_trade_no, $total_fee, $attach, $body, $detail = '', $trade_type = 'JSAPI', $options = [])
{
$order = self::paymentOrder($openid,$out_trade_no,$total_fee,$attach,$body,$detail,$trade_type,$options);
$order = self::paymentOrder($openid, $out_trade_no, $total_fee, $attach, $body, $detail, $trade_type, $options);
$result = self::paymentService()->prepare($order);
if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
try{
if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS') {
try {
PaymentRepositories::wechatPaymentPrepareProgram($order, $result->prepay_id);
}catch (\Exception $e){}
} catch (\Exception $e) {
}
return $result->prepay_id;
}else{
if($result->return_code == 'FAIL'){
exception('微信支付错误返回:'.$result->return_msg);
}else if(isset($result->err_code)){
exception('微信支付错误返回:'.$result->err_code_des);
}else{
} else {
if ($result->return_code == 'FAIL') {
exception('微信支付错误返回:' . $result->return_msg);
} else if (isset($result->err_code)) {
exception('微信支付错误返回:' . $result->err_code_des);
} else {
exception('没有获取微信支付的预支付ID请重新发起支付!');
}
exit;
@ -230,9 +227,9 @@ class MiniProgramService implements ProviderInterface
* @param array $options
* @return array|string
*/
public static function jsPay($openid, $out_trade_no, $total_fee, $attach, $body, $detail='', $trade_type='JSAPI', $options = [])
public static function jsPay($openid, $out_trade_no, $total_fee, $attach, $body, $detail = '', $trade_type = 'JSAPI', $options = [])
{
return self::paymentService()->configForJSSDKPayment(self::paymentPrepare($openid,$out_trade_no,$total_fee,$attach,$body,$detail,$trade_type,$options));
return self::paymentService()->configForJSSDKPayment(self::paymentPrepare($openid, $out_trade_no, $total_fee, $attach, $body, $detail, $trade_type, $options));
}
/**
@ -246,11 +243,11 @@ class MiniProgramService implements ProviderInterface
* @param string $type
* @param string $refundAccount
*/
public static function refund($orderNo, $refundNo, $totalFee, $refundFee = null, $opUserId = null, $refundReason = '' , $type = 'out_trade_no', $refundAccount = 'REFUND_SOURCE_UNSETTLED_FUNDS')
public static function refund($orderNo, $refundNo, $totalFee, $refundFee = null, $opUserId = null, $refundReason = '', $type = 'out_trade_no', $refundAccount = 'REFUND_SOURCE_UNSETTLED_FUNDS')
{
$totalFee = floatval($totalFee);
$refundFee = floatval($refundFee);
return self::paymentService()->refund($orderNo,$refundNo,$totalFee,$refundFee,$opUserId,$type,$refundAccount,$refundReason);
return self::paymentService()->refund($orderNo, $refundNo, $totalFee, $refundFee, $opUserId, $type, $refundAccount, $refundReason);
}
/** 根据订单号退款
@ -260,9 +257,9 @@ class MiniProgramService implements ProviderInterface
*/
public static function payOrderRefund($orderNo, array $opt)
{
if(!isset($opt['pay_price'])) exception('缺少pay_price');
$totalFee = floatval(bcmul($opt['pay_price'],100,0));
$refundFee = isset($opt['refund_price']) ? floatval(bcmul($opt['refund_price'],100,0)) : null;
if (!isset($opt['pay_price'])) exception('缺少pay_price');
$totalFee = floatval(bcmul($opt['pay_price'], 100, 0));
$refundFee = isset($opt['refund_price']) ? floatval(bcmul($opt['refund_price'], 100, 0)) : null;
$refundReason = isset($opt['desc']) ? $opt['desc'] : '';
$refundNo = isset($opt['refund_id']) ? $opt['refund_id'] : $orderNo;
$opUserId = isset($opt['op_user_id']) ? $opt['op_user_id'] : null;
@ -271,11 +268,11 @@ class MiniProgramService implements ProviderInterface
REFUND_SOURCE_UNSETTLED_FUNDS---未结算资金退款(默认使用未结算资金退款)
REFUND_SOURCE_RECHARGE_FUNDS---可用余额退款*/
$refundAccount = isset($opt['refund_account']) ? $opt['refund_account'] : 'REFUND_SOURCE_UNSETTLED_FUNDS';
try{
$res = (self::refund($orderNo,$refundNo,$totalFee,$refundFee,$opUserId,$refundReason,$type,$refundAccount));
if($res->return_code == 'FAIL') exception('退款失败:'.$res->return_msg);
if(isset($res->err_code)) exception('退款失败:'.$res->err_code_des);
}catch (\Exception $e){
try {
$res = (self::refund($orderNo, $refundNo, $totalFee, $refundFee, $opUserId, $refundReason, $type, $refundAccount));
if ($res->return_code == 'FAIL') exception('退款失败:' . $res->return_msg);
if (isset($res->err_code)) exception('退款失败:' . $res->err_code_des);
} catch (\Exception $e) {
exception($e->getMessage());
}
return true;
@ -286,24 +283,24 @@ class MiniProgramService implements ProviderInterface
*/
public static function handleNotify()
{
self::paymentService()->handleNotify(function($notify, $successful){
if($successful && isset($notify->out_trade_no)){
if(isset($notify->attach) && $notify->attach){
if(($count = strpos($notify->out_trade_no,'_')) !== false){
$notify->out_trade_no = substr($notify->out_trade_no,$count+1);
self::paymentService()->handleNotify(function ($notify, $successful) {
if ($successful && isset($notify->out_trade_no)) {
if (isset($notify->attach) && $notify->attach) {
if (($count = strpos($notify->out_trade_no, '_')) !== false) {
$notify->out_trade_no = substr($notify->out_trade_no, $count + 1);
}
if(strtolower($notify->attach) == 'productr'){//TODO 商品订单支付成功后
try{
if(StoreOrderRoutineModel::be(['order_id'=>$notify->out_trade_no,'paid'=>1])) return true;
if (strtolower($notify->attach) == 'productr') {//TODO 商品订单支付成功后
try {
if (StoreOrderRoutineModel::be(['order_id' => $notify->out_trade_no, 'paid' => 1])) return true;
return StoreOrderRoutineModel::paySuccess($notify->out_trade_no);
}catch (\Exception $e){
} catch (\Exception $e) {
return false;
}
}else if(strtolower($notify->attach) == 'user_recharge'){
try{
if(UserRecharge::be(['order_id'=>$notify->out_trade_no,'paid'=>1])) return true;
} else if (strtolower($notify->attach) == 'user_recharge') {
try {
if (UserRecharge::be(['order_id' => $notify->out_trade_no, 'paid' => 1])) return true;
return UserRecharge::rechargeSuccess($notify->out_trade_no);
}catch (\Exception $e){
} catch (\Exception $e) {
return false;
}
}
@ -324,11 +321,8 @@ 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

@ -8,6 +8,7 @@
namespace crmeb\services;
use app\admin\model\system\SystemAttachment;
use app\admin\model\wechat\WechatQrcode as QrcodeModel;
class QrcodeService
@ -15,22 +16,63 @@ 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);
}
/**
* 获取二维码完整路径,不存在则自动生成
* @param string $name 路径名
* @param string $link 需要生成二维码的跳转路径
* @param int $type https 1 = http , 0 = https
* @param bool $force 是否返回false
* @return bool|mixed|string
*/
public static function getWechatQrcodePath(string $name, string $link, int $type = 1, bool $force = false)
{
try {
$imageInfo = SystemAttachment::getInfo($name, 'name');
$siteUrl = sysConfig('site_url');
if (!$imageInfo) {
$codeUrl = UtilService::setHttpType($siteUrl . $link, $type);//二维码链接
$imageInfo = UtilService::getQRCodePath($codeUrl, $name);
if (is_string($imageInfo) && $force)
return false;
if (is_array($imageInfo)) {
SystemAttachment::attachmentAdd($imageInfo['name'], $imageInfo['size'], $imageInfo['type'], $imageInfo['dir'], $imageInfo['thumb_path'], 1, $imageInfo['image_type'], $imageInfo['time'], 2);
$url = $imageInfo['dir'];
} else {
$url = '';
$imageInfo = ['image_type' => 0];
}
} else $url = $imageInfo['att_dir'];
if ($imageInfo['image_type'] == 1) $url = $siteUrl . $url;
return $url;
} catch (\Throwable $e) {
if ($force)
return false;
else
return '';
}
}
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

@ -10,13 +10,23 @@ namespace crmeb\services;
use crmeb\services\storage\COS;
use crmeb\services\storage\OSS;
use crmeb\services\storage\Qiniu;
use crmeb\services\SystemConfigService;
use crmeb\traits\LogicTrait;
use think\exception\ValidateException;
use think\facade\Filesystem;
use think\File;
/**
* Class UploadService
* @package crmeb\services
* @method $this setReturnErr(bool $returnErr) 设置发生错误时是否返回错误信息
* @method $this setAutoValidate(bool $autoValidate) 设置是否校验上传文件
* @method $this setUploadType(int $uploadType) 设置上传类型
* @method $this setImageValidate(string $imageValidate) 设置上传图片大小等验证信息
* @method $this setUploadPath(string $uploadPath) 设置文件上传路径
*/
class UploadService
{
use LogicTrait;
/**
* 文件校验
* @var bool
@ -46,13 +56,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,
];
/**
@ -61,87 +71,24 @@ class UploadService
*/
private static $uploadStatus;
/**
* 本类实例化
* @var
*/
protected static $instance;
/**
* 上传图片的大小 2MB 单位字节
* @var string
*/
protected $imageValidate = 'filesize:2097152|fileExt:jpg,jpeg,png,gif,pem|fileMime:image/jpeg,image/gif,image/png,text/plain';
protected $propsRule = [
'returnErr' => false,
'autoValidate' => false,
'uploadPath' => null,
'uploadType' => null,
];
protected function __construct()
{
self::init();
}
/**
* @return UploadService
*/
public static function getInstance()
{
if(is_null(self::$instance)) self::$instance = new self();
return self::$instance;
}
/**
* 设置上传图片大小等验证信息
* @param string $imageValidate
* @return $this
*/
public function setImageValidate(string $imageValidate)
{
$this->imageValidate = $imageValidate;
return $this;
}
/**
* 设置是否校验上传文件
* @param bool $autoValidate
* @return $this
*/
public function setAutoValidate(bool $autoValidate)
{
$this->autoValidate = $autoValidate;
return $this;
}
/**
* 设置上传路径
* @param string $uploadPath
* @return $this
*/
public function setUploadPath(string $uploadPath)
{
$this->uploadPath = $uploadPath;
return $this;
}
/**
* 设置上传类型
* @param int $uploadType
* @return $this
*/
public function setUploadType(int $uploadType)
{
$this->uploadType = $uploadType;
return $this;
}
/**
* 设置发生错误时是否返回错误信息
* @param bool $returnErr
* @return $this
*/
public function serReturnErr(bool $returnErr)
{
$this->returnErr = $returnErr;
return $this;
}
/**
* 初始化
*/
@ -192,8 +139,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 +151,17 @@ 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;
if (!$uploadType)
$uploadType = 1;
if (!is_int($uploadType))
$uploadType = (int)$uploadType;
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 +169,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 +177,19 @@ 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 +202,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 +212,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 +233,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 +245,11 @@ 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()
$this->uploadPath = '';
$this->autoValidate = false;
return $this->setUploadInfo($url, 1, $fileInfo->getFilename(), self::thumb('.' . $url), [
'Content-Length' => $fileInfo->getSize(),
'Content-Type' => $fileInfo->getMime()
]);
}
@ -310,7 +260,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 +271,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 +284,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 +292,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 +302,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 +312,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 +337,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 +371,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 +380,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,12 +411,12 @@ 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;
}
protected function __clone()
protected function __destruct()
{
// TODO: Implement __clone() method.
// TODO: Implement __destruct() method.
}
}

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::instance()->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,14 +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){
dump($e->getMessage());
$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) {
return false;
}
}
@ -97,24 +97,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 +129,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);
}
}