Просмотр исходного кода

修复打印机token失效问题

liaofei 6 лет назад
Родитель
Сommit
4e0fc47144

+ 38 - 11
crmeb/app/models/system/Cache.php

@@ -1,4 +1,5 @@
 <?php
+
 namespace app\models\system;
 
 use crmeb\traits\ModelTrait;
@@ -23,13 +24,29 @@ class Cache extends BaseModel
     /**
      * 获取数据缓存
      * @param string $key
-     * @return result
+     * @param $default 默认值不存在则写入
+     * @return mixed|null
      */
-    public static function getDbCache(string $key)
+    public static function getDbCache(string $key, $default, int $expire = self::EXPIRE)
     {
         self::delectDeOverdueDbCache();
-         $result = self::where('key',$key)->value('result');
-         return json_decode($result,true);
+        $result = self::where('key', $key)->value('result');
+        if ($result) {
+            return json_decode($result, true);
+        } else {
+            if ($default instanceof \Closure) {
+                // 获取缓存数据
+                $value = $default();
+                if ($value) {
+                    self::setDbCache($key, $value, $expire);
+                    return $value;
+                }
+            } else {
+                self::setDbCache($key, $default, $expire);
+                return $default;
+            }
+            return null;
+        }
     }
 
     /**
@@ -39,14 +56,23 @@ class Cache extends BaseModel
      * @param int $expire
      * @return void
      */
-    public static function setDbCache(string $key,$result,$expire = self::EXPIRE)
+    public static function setDbCache(string $key, $result, $expire = self::EXPIRE)
     {
         self::delectDeOverdueDbCache();
         $addTime = $expire ? time() + $expire : 0;
-        if(self::be(['key'=>$key])){
-            return self::where(['key'=>$key])->update(['result'=>json_encode($result),'add_time'=>$addTime]);
-        }else{
-            return self::create(['key'=>$key,'result'=>json_encode($result),'add_time'=>$addTime]);
+        if (self::be(['key' => $key])) {
+            return self::where(['key' => $key])->update([
+                'result' => json_encode($result),
+                'expire_time' => $addTime,
+                'add_time' => time()
+            ]);
+        } else {
+            return self::create([
+                'key' => $key,
+                'result' => json_encode($result),
+                'expire_time' => $addTime,
+                'add_time' => time()
+            ]);
         }
     }
 
@@ -55,6 +81,7 @@ class Cache extends BaseModel
      */
     public static function delectDeOverdueDbCache()
     {
+        self::where('expire_time', '<>', 0)->where('expire_time', '<', time())->delete();
     }
 
     /**
@@ -63,8 +90,8 @@ class Cache extends BaseModel
      */
     public static function delectDbCache(string $key = '')
     {
-        if($key)
-            return self::where('key',$key)->delete();
+        if ($key)
+            return self::where('key', $key)->delete();
         else
             return self::delete();
     }

+ 0 - 1
crmeb/crmeb/repositories/NoticeRepositories.php

@@ -15,7 +15,6 @@ use app\models\routine\RoutineTemplate;
 use app\models\store\StoreOrderCartInfo;
 use app\models\user\User;
 use crmeb\services\YLYService;
-use think\facade\Log;
 use think\facade\Route;
 
 /** 消息通知静态类

+ 85 - 0
crmeb/crmeb/services/CustomerService.php

@@ -0,0 +1,85 @@
+<?php
+
+namespace crmeb\services;
+
+use app\models\store\StoreBargain;
+use app\models\store\StoreCart;
+use app\models\store\StoreCombination;
+use app\models\store\StoreProduct;
+use app\models\store\StoreSeckill;
+use app\models\store\StoreService;
+use app\models\user\WechatUser;
+use think\facade\Log;
+
+/**
+ * 客服消息推送
+ * Class CustomerService
+ * @package crmeb\services
+ */
+class CustomerService
+{
+
+    /**
+     * 订单支付成功后给客服发送客服消息
+     * @param $order
+     * @param int $type 1 公众号 0 小程序
+     * @return string
+     */
+    public static function sendOrderPaySuccessCustomerService($order, $type = 0)
+    {
+        $serviceOrderNotice = StoreService::getStoreServiceOrderNotice();
+        if (count($serviceOrderNotice)) {
+            foreach ($serviceOrderNotice as $key => &$item) {
+                $userInfo = WechatUser::get($item);
+                if ($userInfo) {
+                    $userInfo = $userInfo->toArray();
+                    if ($userInfo['subscribe'] && $userInfo['openid']) {
+                        $orderStatus = StoreService::orderServiceStatus($userInfo['uid']);
+                        if ($orderStatus) {
+                            // 统计管理开启  推送图文消息
+                            $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');
+                                $image = StoreSeckill::getProductField($order['seckill_id'], 'image');
+                            } 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');
+                                $image = StoreBargain::getBargainField($order['bargain_id'], 'image');
+                            } else {
+                                $productIds = StoreCart::getCartIdsProduct((array)$order['cart_id']);
+                                $storeProduct = StoreProduct::getProductStoreNameOrImage($productIds);
+                                if (count($storeProduct)) {
+                                    foreach ($storeProduct as $value) {
+                                        $description .= $value['store_name'] . '  ';
+                                        $image = $value['image'];
+                                    }
+                                }
+                            }
+                            $message = WechatService::newsMessage($head, $description, $url, $image);
+                            try {
+                                WechatService::staffService()->message($message)->to($userInfo['openid'])->send();
+                            } catch (\Exception $e) {
+                                Log::error($userInfo['nickname'] . '发送失败' . $e->getMessage());
+                            }
+                        } 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订单来源:公众号";
+                            try {
+                                WechatService::staffService()->message($head)->to($userInfo['openid'])->send();
+                            } catch (\Exception $e) {
+                                Log::error($userInfo['nickname'] . '发送失败' . $e->getMessage());
+                            }
+                        }
+                    }
+                }
+
+            }
+        }
+    }
+}

+ 33 - 24
crmeb/crmeb/services/GroupDataService.php

@@ -23,23 +23,26 @@ class GroupDataService
      */
     public static function getGroupData(string $config_name, $limit = 0, bool $isCaChe = false): array
     {
+        $callable = function () use ($config_name, $limit) {
+            $data = SystemGroupData::getGroupData($config_name, $limit);
+            if (is_object($data))
+                $data = $data->toArray();
+            return $data;
+        };
         try {
             $cacheName = $limit ? "group_data_{$config_name}_{$limit}" : "data_{$config_name}";
 
-            $callable = function () use ($config_name, $limit) {
-                $data = SystemGroupData::getGroupData($config_name, $limit);
-                if (is_object($data))
-                    $data = $data->toArray();
-                return $data;
-            };
-
             if ($isCaChe)
                 return $callable();
 
             return CacheService::get($cacheName, $callable);
 
         } catch (\Throwable $e) {
-            return [];
+            try {
+                return $callable();
+            } catch (\Exception $e) {
+                return [];
+            }
         }
     }
 
@@ -52,23 +55,26 @@ class GroupDataService
      */
     public static function getData(string $config_name, int $limit = 0, bool $isCaChe = false): array
     {
+        $callable = function () use ($config_name, $limit) {
+            $data = SystemGroupData::getAllValue($config_name, $limit);
+            if (is_object($data))
+                $data = $data->toArray();
+            return $data;
+        };
         try {
             $cacheName = $limit ? "data_{$config_name}_{$limit}" : "data_{$config_name}";
 
-            $callable = function () use ($config_name, $limit) {
-                $data = SystemGroupData::getAllValue($config_name, $limit);
-                if (is_object($data))
-                    $data = $data->toArray();
-                return $data;
-            };
-
             if ($isCaChe)
                 return $callable();
 
             return CacheService::get($cacheName, $callable);
 
         } catch (\Throwable $e) {
-            return [];
+            try {
+                return $callable();
+            } catch (\Exception $e) {
+                return [];
+            }
         }
     }
 
@@ -80,23 +86,26 @@ class GroupDataService
      */
     public static function getDataNumber(int $id, bool $isCaChe = false): array
     {
+        $callable = function () use ($id) {
+            $data = SystemGroupData::getDateValue($id);
+            if (is_object($data))
+                $data = $data->toArray();
+            return $data;
+        };
         try {
             $cacheName = "data_number_{$id}";
 
-            $callable = function () use ($id) {
-                $data = SystemGroupData::getDateValue($id);
-                if (is_object($data))
-                    $data = $data->toArray();
-                return $data;
-            };
-
             if ($isCaChe)
                 return $callable();
 
             return CacheService::get($cacheName, $callable);
 
         } catch (\Throwable $e) {
-            return [];
+            try {
+                return $callable();
+            } catch (\Exception $e) {
+                return [];
+            }
         }
     }
 }

+ 15 - 7
crmeb/crmeb/services/SystemConfigService.php

@@ -25,9 +25,17 @@ class SystemConfigService
      */
     protected static function init()
     {
-        if(!(self::$configList = CacheService::get(self::CACHE_SYSTEM))){
-            self::$configList = self::getAll();
-            CacheService::set('system_config',self::$configList);
+        $confingFun = function () {
+            return self::getAll();
+        };
+        try {
+            self::$configList = CacheService::get(self::CACHE_SYSTEM, $confingFun);
+        } catch (\Throwable $e) {
+            try {
+                self::$configList = $confingFun();
+            } catch (\Exception $e) {
+                self::$configList = [];
+            }
         }
     }
 
@@ -49,12 +57,12 @@ class SystemConfigService
      * @param bool $isCaChe 是否获取缓存配置
      * @return bool|mixed|string
      */
-    public static function get($key,$default = '',bool $isCaChe = false)
+    public static function get($key, $default = '', bool $isCaChe = false)
     {
-        if($isCaChe){
-            try{
+        if ($isCaChe) {
+            try {
                 return SystemConfig::getConfigValue($key);
-            }catch (\Throwable $e){
+            } catch (\Throwable $e) {
                 return $default;
             }
         }

+ 42 - 3
crmeb/crmeb/services/UploadService.php

@@ -75,7 +75,17 @@ class UploadService
      * 上传图片的大小 2MB 单位字节
      * @var string
      */
-    protected $imageValidate = 'filesize:2097152|fileExt:jpg,jpeg,png,gif,pem|fileMime:image/jpeg,image/gif,image/png,text/plain';
+    protected $imageValidate = null;
+
+    /**
+     * 上传规则
+     * @var array
+     */
+    protected $imageValidateArray = [
+        'filesize' => 2097152,
+        'fileExt' => ['jpg', 'jpeg', 'png', 'gif', 'pem', 'mp3', 'wma', 'wav', 'amr', 'mp4'],
+        'fileMime' => ['image/jpeg', 'image/gif', 'image/png', 'text/plain', 'audio/mpeg'],
+    ];
 
     protected $propsRule = [
         'returnErr' => false,
@@ -86,15 +96,44 @@ class UploadService
 
     protected function __construct()
     {
-        self::init();
+        $this->init();
     }
 
     /**
      * 初始化
      */
-    private static function init()
+    protected function init()
     {
         self::$uploadStatus = new \StdClass();
+        $this->extractValidate();
+    }
+
+    /**
+     * 提取上传验证
+     */
+    protected function extractValidate()
+    {
+        $imageValidate = [];
+        foreach ($this->imageValidateArray as $key => $value) {
+            $imageValidate[] = $key . ':' . (is_array($value) ? implode(',', $value) : $value);
+        }
+        $this->imageValidate = implode('|', $imageValidate);
+        unset($imageValidate);
+    }
+
+    /**
+     * 设置上传验证
+     * @param array $imageValidateArray
+     * @return $this
+     */
+    public function setImageValidateArray(array $imageValidateArray)
+    {
+        if (isset($imageValidateArray['filesize']) && !is_int($imageValidateArray['filesize'])) {
+            $imageValidateArray['filesize'] = 2097152;
+        }
+        $this->imageValidateArray = array_merge($this->imageValidateArray, $imageValidateArray);
+        $this->extractValidate();
+        return $this;
     }
 
     /**

+ 19 - 9
crmeb/crmeb/services/YLYService.php

@@ -86,8 +86,7 @@ class YLYService extends HttpService implements ProviderInterface
      * */
     protected function getAccessToken()
     {
-        $token = CacheModel::getDbCache('YLY_access_token');
-        if (!$token) {
+        $this->access_token = CacheModel::getDbCache('YLY_access_token', function () {
             $request = self::postRequest($this->apiUrl . 'oauth/oauth', [
                 'client_id' => $this->client_id,
                 'grant_type' => 'client_credentials',
@@ -100,11 +99,12 @@ class YLYService extends HttpService implements ProviderInterface
             $request['error'] = $request['error'] ?? 0;
             $request['error_description'] = $request['error_description'] ?? '';
             if ($request['error'] == 0 && $request['error_description'] == 'success') {
-                $token = $request['body']['access_token'] ?? '';
-                CacheModel::setDbCache('YLY_access_token', $token);
+                return $request['body']['access_token'] ?? '';
             }
-        }
-        $this->access_token = $token;
+            return '';
+        }, 20 * 86400);
+        if (!$this->access_token)
+            throw new AuthException('获取access_token获取失败');
     }
 
     /**
@@ -123,7 +123,7 @@ class YLYService extends HttpService implements ProviderInterface
      * @param string $order_id
      * @return bool|mixed
      */
-    public function orderPrinting(string $order_id = '')
+    public function orderPrinting(string $order_id = '', int $errorCount = 0)
     {
         $request = self::postRequest($this->apiUrl . 'print/index', [
             'client_id' => $this->client_id,
@@ -136,7 +136,13 @@ class YLYService extends HttpService implements ProviderInterface
             'timestamp' => time()
         ]);
         if ($request === false) return false;
-        return json_decode($request, true);
+        $request = json_decode($request, true);
+        if (isset($request['error']) && in_array($request['error'], [18, 14]) && $errorCount == 0) {
+            CacheModel::delectDbCache('YLY_access_token');
+            $this->getAccessToken();
+            return $this->orderPrinting($order_id, 1);
+        }
+        return $request;
     }
 
     /**
@@ -172,7 +178,11 @@ class YLYService extends HttpService implements ProviderInterface
         $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>";
+            if (isset($item['productInfo']['attrInfo'])) {
+                $price = $item['productInfo']['attrInfo']['price'] ?? $item['productInfo']['price'] ?? 0;
+                $goodsStr .= "<td>{$item['productInfo']['store_name']}</td><td>{$item['cart_num']}</td><td>{$price}</td><td>{$item['truePrice']}</td>";
+            } else
+                $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>';