Browse Source

fix: 增加一个商品评论统计接口

super-yimizi 1 month ago
parent
commit
97170f94d1

+ 24 - 0
addons/epay/certs/apiclient_cert.pem

@@ -0,0 +1,24 @@
+-----BEGIN CERTIFICATE-----
+MIID8DCCAtigAwIBAgIUXEI0eINJLIZwzaC7dT4FbMaHfJAwDQYJKoZIhvcNAQEL
+BQAwXjELMAkGA1UEBhMCQ04xEzARBgNVBAoTClRlbnBheS5jb20xHTAbBgNVBAsT
+FFRlbnBheS5jb20gQ0EgQ2VudGVyMRswGQYDVQQDExJUZW5wYXkuY29tIFJvb3Qg
+Q0EwHhcNMjMwMTEwMDgxNjI1WhcNMjgwMTA5MDgxNjI1WjCBgTETMBEGA1UEAwwK
+MTYyNTc3NDQ4MjEbMBkGA1UECgwS5b6u5L+h5ZWG5oi357O757ufMS0wKwYDVQQL
+DCTlsbHkuJzomY7ll4XnvZHnu5znp5HmioDmnInpmZDlhazlj7gxCzAJBgNVBAYM
+AkNOMREwDwYDVQQHDAhTaGVuWmhlbjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC
+AQoCggEBAL+vaoS43lew36AswuEVeDSNiQh/jP6toZgaPLoyZubXL4oZPbYVmcRh
+Az/yoyJtyCOThnE9j0xHMY/cLlq1gNxcoKVoMT2TOamJ1ynhCBzLA7sz1gcs2S6S
+BiEEzvcvvStDh8lKZqjNgolLqvGmTsfNtMS+Mtmxe+2mavI34KPAn82+BZwb6ylp
+Nrx7oBwWUFosODIwoAjl6O7Vc1TRmlUXtyqSitWPyLu5FKPDFg4W1eYdlG6vgPOK
+H7fi4isxZVRY+z9RqUTV7PyyNJmSBYTDOoJX9N6IHdFL3CH4Ih3RzewyNd/i9JtP
+/mVwpX8VslOPkYKLBgQJ4jShoJG+nzkCAwEAAaOBgTB/MAkGA1UdEwQCMAAwCwYD
+VR0PBAQDAgP4MGUGA1UdHwReMFwwWqBYoFaGVGh0dHA6Ly9ldmNhLml0cnVzLmNv
+bS5jbi9wdWJsaWMvaXRydXNjcmw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xmiunwr0iEbY84z9Wg3WLWFJUPlu2wvOAk2B8
+HJvlm+E3u0HsHrViLD+0ntI=
+-----END PRIVATE KEY-----

+ 6 - 4
addons/epay/config.php

@@ -22,18 +22,20 @@ return [
             'appid' => '',
             'app_id' => '',
             'app_secret' => '',
-            'miniapp_id' => '',
+            'miniapp_id' => 'wx9a7153e5b40d9663',
             'mch_id' => '1625774482',
             'key' => 'DRs2yi80exLRn6tI4cBhISMfj7SPYMQG',
             'key_v3' => 'vnQynXQo9kp5hh0pvlfjN03uiQZ222AS',
+            'public_key_id' => '',
+            'public_key' => '',
+            'cert_client' => '/addons/epay/certs/apiclient_cert.pem',
+            'cert_key' => '/addons/epay/certs/apiclient_key.pem',
             'mode' => 'normal',
             'sub_mch_id' => '',
             'sub_appid' => '',
             'sub_app_id' => '',
             'sub_miniapp_id' => '',
             'notify_url' => '',
-            'cert_client' => '/addons/epay/certs/apiclient_cert.pem',
-            'cert_key' => '/addons/epay/certs/apiclient_key.pem',
             'log' => '1',
         ],
         'rule' => 'required',
@@ -53,11 +55,11 @@ return [
             'app_id' => '',
             'notify_url' => '/addons/epay/api/notifyx/type/alipay',
             'return_url' => '/addons/epay/api/returnx/type/alipay',
-            'private_key' => '',
             'signtype' => 'cert',
             'ali_public_key' => '',
             'app_cert_public_key' => '',
             'alipay_root_cert' => '',
+            'private_key' => '',
             'log' => '1',
             'scanpay' => '0',
         ],

+ 4 - 2
application/api/controller/Comment.php

@@ -11,13 +11,14 @@ use app\api\validate\Comment as CommentValidate;
 use app\common\Enum\CommentEnum;
 use think\Db;
 use app\common\Enum\OrderEnum;
+use app\common\Enum\StatusEnum;
 
 /**
  * 评论
  */
 class Comment extends Base
 {
-    protected $noNeedLogin = ['index'];
+    protected $noNeedLogin = ['index','stats'];
 
     /**
      * 评论列表
@@ -137,10 +138,11 @@ class Comment extends Base
     {
         $data = [
             'evaluate_status' => CommentEnum::getEvaluateStatusList(),
-            'status' => CommentEnum::getStatusList(),
+            'status' => StatusEnum::getMap(),
             'has_picture' => CommentEnum::getHasPictureList(),
         ];
         
         $this->success('获取成功', $data);
     }
+  
 }

+ 18 - 15
application/api/controller/Order.php

@@ -14,6 +14,7 @@ use think\Db;
 use app\common\Service\OrderService;
 use app\common\Enum\OrderEnum;
 use app\common\Service\CartService;
+use app\common\Service\Pay\PayOperService;
 /**
  * 订单接口
  */
@@ -21,6 +22,12 @@ class Order extends Base
 {
     protected $noNeedLogin = [];
 
+    public function __construct()
+    {
+        parent::__construct();
+        set_addon_config('epay', ['version'=>'v3'], false);
+    }
+
     //计算邮费,判断商品 - 支持购物车和商品规格两种模式
     public function calculate()
     {
@@ -248,44 +255,40 @@ class Order extends Base
         $validate = new \app\api\validate\Order();
         if (!$validate->scene('pay')->check($this->request->post())) {
             $this->error($validate->getError());
-        }
-        
+        }        
         $order_sn = $this->request->post('order_sn');
-        $paytype = $this->request->post('paytype');
+        $pay_type = $this->request->post('pay_type');
         $method = $this->request->post('method');
         $appid = $this->request->post('appid'); //为APP的应用id
         $returnurl = $this->request->post('returnurl', '', 'trim');
         $openid = $this->request->post('openid', '', null);
         $logincode = $this->request->post('logincode', '', null);
-
-        $orderInfo = OrderModel::getByOrderSn($order_sn);
+        $userId = $this->auth->id;
+        $orderInfo = OrderService::getByOrderSn($order_sn);
         if (!$orderInfo) {
             $this->error("未找到指定的订单");
         }
-        if ($orderInfo) {
+        if ($orderInfo->isPayStatus()) {
             $this->error("订单已经支付,请勿重复支付");
         }
-        if (OrderModel::isExpired($order_sn)) {
-            $this->error("订单已经失效");
-        }
+        // if (OrderService::isExpired($order_sn)) {
+        //     $this->error("订单已经失效");
+        // }
+
 
         //如果有传递logincode,则直接使用code换openid
         if (!$openid && $logincode) {
             $json = (new \app\common\library\Wechat\Service())->getWechatSession($logincode);
             $openid = $json['openid'] ?? $openid;
         }
-
         //必须传递openid
         if (in_array($method, ['miniapp', 'mp', 'mini']) && !$openid) {
             $this->error("未找到第三方用户信息", 'bind');
         }
 
         $response = null;
-        try {
-            $response = OrderModel::pay($order_sn, $this->auth->id, $paytype, $method, $openid, '', $returnurl);
-        } catch (\Exception $e) {
-            $this->error($e->getMessage());
-        }
+        $response = PayOperService::pay($order_sn, $userId, $pay_type, $method, $openid, '', $returnurl);
+       
         $this->success("请求成功", $response);
     }
 

+ 3 - 3
application/api/controller/Pay.php

@@ -7,7 +7,7 @@ use think\Log;
 use think\Exception;
 use think\exception\HttpResponseException;
 use app\common\Service\Pay\PayService;
-use app\common\Service\PayOperService;
+use app\common\Service\Pay\PayOperService;
 use app\common\Enum\ChannelEnum;
 use app\common\Service\OrderService;
 /**
@@ -47,8 +47,8 @@ class Pay extends Base
             echo $pay->success();
         }//  pc 支付
          elseif ($type == 'return') {
-            $order_sn = $this->request->param('order_sn');
-            $this->redirect("index/shop.order/detail", ['orderid' => $order_sn]);
+            // $order_sn = $this->request->param('order_sn');
+            // $this->redirect("index/shop.order/detail", ['orderid' => $order_sn]);
         }
         return;
     }

+ 2 - 2
application/api/validate/Comment.php

@@ -8,7 +8,7 @@ use app\common\Enum\CommentEnum;
 class Comment extends Validate
 {
     protected $rule = [
-        'goods_id' => 'integer|>=:0',
+        'goods_id' => 'integer|>:0',
         'pid' => 'integer|>=:0',
         'page' => 'integer|>:0',
         'page_size' => 'integer|between:1,50',
@@ -53,7 +53,7 @@ class Comment extends Validate
         'index' => ['goods_id', 'pid', 'page', 'page_size', 'order_by', 'order_way','has_picture'],
         'add' => ['order_id', 'remark', 'pid'],
         'myList' => ['page', 'page_size'],
-        'stats' => ['goods_id'],
+        'stats' => ['goods_id' => 'require|integer|>:0'],
         'audit' => ['comment_id', 'evaluate_status'],
     ];
 

+ 5 - 5
application/api/validate/Order.php

@@ -34,7 +34,7 @@ class Order extends Validate
         // 订单操作相关
         'order_sn'        => 'require|alphaNum',
         'orderId'        => 'require|integer|gt:0',
-        'paytype'         => 'require|in:alipay,wechat,unionpay,balance',
+        'pay_type'         => 'require|in:alipay,wechat,unionpay,balance',
         'method'          => 'require|in:web,wap,app,miniapp,mp,mini',
         
         // 订单列表查询相关
@@ -84,11 +84,11 @@ class Order extends Validate
         'orderId.require'       => '订单ID不能为空',
         'orderId.integer'       => '订单ID必须是整数',
         'orderId.gt'            => '订单ID必须大于0',
-        'paytype.require'       => '支付方式不能为空',
-        'paytype.in'            => '支付方式不支持',
+        'pay_type.require'       => '支付方式不能为空',
+        'pay_type.in'            => '支付方式不支持',
         'method.require'        => '支付方法不能为空',
         'method.in'             => '支付方法不支持',
-        
+
         // 订单列表查询相关
         'page.integer'          => '页码必须是整数',
         'page.egt'              => '页码必须大于等于1',
@@ -112,7 +112,7 @@ class Order extends Validate
         // 取消订单
         'cancel'            => ['orderId'],
         // 订单支付
-        'pay'               => ['orderId', 'paytype', 'method'],
+        'pay'               => ['order_sn', 'pay_type', 'method'],
         // 订单列表
         'lists'             => ['page', 'pageSize', 'status', 'keywords', 'start_time', 'end_time', 'time_range'],
     ];

+ 1 - 42
application/common/Enum/CommentEnum.php

@@ -11,11 +11,6 @@ class CommentEnum
     const EVALUATE_STATUS_APPROVED = 2;    // 审核通过
     const EVALUATE_STATUS_REJECTED = 3;    // 审核失败
 
-    /**
-     * 显示状态
-     */
-    const STATUS_NORMAL = 'normal';        // 正常显示
-    const STATUS_HIDDEN = 'hidden';        // 隐藏
 
     /**
      * 是否有图片
@@ -39,20 +34,7 @@ class CommentEnum
         return isset($statusMap[$status]) ? $statusMap[$status] : '未知状态';
     }
 
-    /**
-     * 获取显示状态文本
-     * @param string $status
-     * @return string
-     */
-    public static function getStatusText($status)
-    {
-        $statusMap = [
-            self::STATUS_NORMAL => '正常显示',
-            self::STATUS_HIDDEN => '隐藏'
-        ];
-
-        return isset($statusMap[$status]) ? $statusMap[$status] : '未知状态';
-    }
+  
 
     /**
      * 获取有图片状态文本
@@ -82,17 +64,6 @@ class CommentEnum
         ];
     }
 
-    /**
-     * 获取所有显示状态
-     * @return array
-     */
-    public static function getStatusList()
-    {
-        return [
-            self::STATUS_NORMAL => '正常显示',
-            self::STATUS_HIDDEN => '隐藏'
-        ];
-    }
 
     /**
      * 获取所有有图片状态
@@ -120,18 +91,6 @@ class CommentEnum
         ]);
     }
 
-    /**
-     * 验证显示状态
-     * @param string $status
-     * @return bool
-     */
-    public static function isValidStatus($status)
-    {
-        return in_array($status, [
-            self::STATUS_NORMAL,
-            self::STATUS_HIDDEN
-        ]);
-    }
 
     /**
      * 验证有图片状态

+ 18 - 0
application/common/Enum/OrderEnum.php

@@ -168,6 +168,24 @@ class OrderEnum
         self::STATUS_COMMENT => "已评价",
     ];
 
+    const STATUS_TIME_MAP = [
+        self::STATUS_CREATE => 'createtime',
+        self::STATUS_PAY => 'pay_time',
+        self::STATUS_SHIP => 'shipping_time',
+        self::STATUS_CONFIRM => 'receive_time',
+        self::STATUS_AUTO_CONFIRM => 'receive_time',
+        self::STATUS_COMMENT => 'evaluate_time',
+        self::STATUS_REFUND => 'refund_time',
+        self::STATUS_REFUND_CONFIRM => 'refund_time',
+        self::STATUS_AUTO_CANCEL => 'expire_time',
+        self::STATUS_CANCEL => 'cancel_time',
+    ];
+
+    public static function isValidOrderStatus($status)
+    {
+        return isset(self::STATUS_TEXT_MAP[$status]);
+    }
+
     public static function getOrderStatusList()
     {
         return self::STATUS_TEXT_MAP;

+ 8 - 7
application/common/Service/Goods/CommentService.php

@@ -11,6 +11,7 @@ use think\Db;
 use think\Exception;
 use app\common\exception\BusinessException;
 use app\common\Enum\StatusEnum;
+use think\console\output\formatter\Stack;
 
 class CommentService
 {
@@ -74,13 +75,13 @@ class CommentService
         $total = Comment::where('goods_id', $goods_id)
             ->where('pid', 0)
             ->where('evaluate_status', CommentEnum::EVALUATE_STATUS_APPROVED)
-            ->where('status', CommentEnum::STATUS_NORMAL)
+            ->where('status', StatusEnum::ENABLED)
             ->sum('star');
             
         $favorable = Comment::where('goods_id', $goods_id)
             ->where('pid', 0)
             ->where('evaluate_status', CommentEnum::EVALUATE_STATUS_APPROVED)
-            ->where('status', CommentEnum::STATUS_NORMAL)
+            ->where('status', StatusEnum::ENABLED)
             ->where('star', '>', 3)
             ->sum('star');
             
@@ -135,7 +136,7 @@ class CommentService
             ->where('user_id', $user_id)
             ->where('pid', 0)
             ->where('evaluate_status', CommentEnum::EVALUATE_STATUS_APPROVED)
-            ->where('status', CommentEnum::STATUS_NORMAL)
+            ->where('status', StatusEnum::ENABLED)
             ->order('createtime desc')
             ->paginate($pagesize, false, ['page' => $page]);
             
@@ -263,7 +264,7 @@ class CommentService
         }
         
         $status = $evaluate_status == CommentEnum::EVALUATE_STATUS_APPROVED ? 
-                  CommentEnum::STATUS_NORMAL : CommentEnum::STATUS_HIDDEN;
+                  StatusEnum::ENABLED : StatusEnum::DISABLED;
         
         return $comment->save([
             'evaluate_status' => $evaluate_status,
@@ -281,7 +282,7 @@ class CommentService
         $total = Comment::where('goods_id', $goods_id)
             ->where('pid', 0)
             ->where('evaluate_status', CommentEnum::EVALUATE_STATUS_APPROVED)
-            ->where('status', CommentEnum::STATUS_NORMAL)
+            ->where('status', StatusEnum::ENABLED)
             ->count();
             
         $star_counts = [];
@@ -289,7 +290,7 @@ class CommentService
             $star_counts[$i] = Comment::where('goods_id', $goods_id)
                 ->where('pid', 0)
                 ->where('evaluate_status', CommentEnum::EVALUATE_STATUS_APPROVED)
-                ->where('status', CommentEnum::STATUS_NORMAL)
+                ->where('status', StatusEnum::ENABLED)
                 ->where('star', $i)
                 ->count();
         }
@@ -298,7 +299,7 @@ class CommentService
         $picture_count = Comment::where('goods_id', $goods_id)
             ->where('pid', 0)
             ->where('evaluate_status', CommentEnum::EVALUATE_STATUS_APPROVED)
-            ->where('status', CommentEnum::STATUS_NORMAL)
+            ->where('status', StatusEnum::ENABLED)
             ->where('has_picture', CommentEnum::HAS_PICTURE_YES)
             ->count();
         

+ 30 - 0
application/common/Service/OrderService.php

@@ -17,6 +17,7 @@ use think\Db;
 use think\Exception;
 use app\common\model\OrderAddress;
 use app\common\Enum\OrderEnum;
+use app\common\exception\BusinessException;
 /**
  * 订单服务类
  * 封装订单创建相关逻辑
@@ -536,6 +537,13 @@ class OrderService
         ->find();
     }
 
+    public static function getDetailByOrderSn($orderSn)
+    {
+        return Order::with(['orderGoods'])
+        ->where('order_sn', $orderSn)
+        ->find();
+    }
+
     // 查询地址信息
     public static function getAddressInfo($orderId)
     {
@@ -595,6 +603,28 @@ class OrderService
         return $info;
     }
 
+    // 更新订单状态
+    public static function updateOrderStatus($orderId = 0, $userId = 0, $status = 0)
+    {
+    
+        $order = self::getDetail($orderId, $userId);
+        if (!$order) {
+            throw new BusinessException('订单不存在!');
+        }
+        // 验证状态
+        if (!OrderEnum::isValidOrderStatus($status)) {
+            throw new BusinessException('状态不合法!');
+        }
+        //  要处理每个状态对应的时间字段在枚举类中
+        $timeField = OrderEnum::STATUS_TIME_MAP[$status];
+        $updateData = [
+            'order_status' => $status,
+            $timeField => time()
+        ];
+        Order::where('id', $orderId)->update($updateData);
+        return $order;
+    }
+
 
 
 } 

+ 86 - 24
application/common/Service/Pay/PayOperService.php

@@ -1,11 +1,18 @@
 <?php
 
-namespace app\common\Service;
+namespace app\common\Service\Pay;
 
 
 use think\Db;
 use think\Exception;
 use app\common\model\User;
+use app\common\exception\BusinessException;
+use app\common\Enum\OrderEnum;
+use app\common\Service\OrderService;
+use addons\epay\library\Service;
+use Yansongda\Pay\Exceptions\GatewayException;
+use app\common\Service\Order\OrderGoodsService;
+use app\common\model\OrderAction;
 /**
  * 支付服务类
  * 封装订单创建相关逻辑
@@ -13,6 +20,72 @@ use app\common\model\User;
 class PayOperService
 {
 
+
+     /**
+     * @ 支付
+     * @param string $orderid
+     * @param int    $user_id
+     * @param string $paytype
+     * @param string $method
+     * @param string $openid
+     * @param string $notifyurl
+     * @param string $returnurl
+     * @return \addons\epay\library\Collection|\addons\epay\library\RedirectResponse|\addons\epay\library\Response|null
+     * @throws \Exception
+     */
+    public static function pay($orderSn = "", $userId = 0, $paytype="", $method = '', $openid = '', $notifyurl = null, $returnurl = null)
+    {
+        $request = \think\Request::instance();
+        $order = OrderService::getDetailByOrderSn($orderSn);
+        if (!$order) {
+            throw new BusinessException('订单不存在!');
+        }
+        if (!$order->canPayHandle()) {
+            throw new BusinessException('该订单无法支付!');
+        }
+      
+        //支付金额为0,无需支付
+        if ($order->amount == 0) {
+            //  走orderService 更新订单状态方法  穿订单状态 已支付 和支付时间
+           $Order =  OrderService::updateOrderStatus($order->id, $userId, OrderEnum::STATUS_PAY);
+            if ($Order) {
+                return $Order;
+            }
+        }
+        $order_sn = $order->order_sn;       
+           
+        $order->allowField(true)->save(['pay_type' => $paytype, 'open_id' => $openid]);
+       
+        $response = null;
+        $epay = get_addon_info('epay');
+
+        if ($epay && $epay['state']) {
+            $notifyurl = $notifyurl ? $notifyurl : $request->root(true) . '/api/shop/pay/notify/type/notify/paytype/' . $paytype;
+            $returnurl = $returnurl ? $returnurl : $request->root(true) . '/api/shop/pay/notify/type/return/paytype/' . $paytype . '/order_sn/' . $order_sn;
+
+            //保证取出的金额一致,不一致将导致订单重复错误
+            $amount = sprintf("%.2f", $order->amount);
+
+            $params = [
+                'amount'    => $amount,
+                'orderid'   => $order_sn,
+                'type'      => $paytype,
+                'title'     => "支付{$amount}元",
+                'notifyurl' => $notifyurl,
+                'returnurl' => $returnurl,
+                'method'    => $method,
+                'openid'    => $openid
+            ];
+            try {
+                $response = Service::submitOrder($params);
+            } catch (GatewayException $e) {
+                throw new \Exception(config('app_debug') ? $e->getMessage() : "支付失败,请稍后重试");
+            }
+        } else {
+            throw new \Exception("请在后台安装配置微信支付宝整合插件");
+        }
+        return $response;
+    }
     /**
      *
      * @ 订单结算
@@ -21,40 +94,29 @@ class PayOperService
      * @param string $transactionid 流水号
      * @return bool
      */
-    public static function settle($order_sn, $payamount, $transactionid = '')
+    public static function settle($orderSn, $payamount, $transactionid = '')
     {
-        $order = self::with(['orderGoods'])->where('order_sn', $order_sn)->find();
-        if (!$order || $order->paystate == 1) {
+        $order = OrderService::getDetailByOrderSn($orderSn);
+        if (!$order->canPayHandle()) {
             return false;
         }
 
-        if ($payamount != $order->saleamount) {
-            \think\Log::write("[shop][pay][{$order_sn}][订单支付金额不一致]");
+        if ($payamount != $order->amount) {
+            \think\Log::write("支付失败,订单支付金额不一致[{$orderSn}][{$payamount}][{$order->amount}]");
             return false;
         }
 
         // 启动事务
         Db::startTrans();
         try {
-            $order->paystate = 1;
-            $order->transactionid = $transactionid;
-            $order->payamount = $payamount;
-            $order->paytime = time();
-            $order->paytype = !$order->paytype ? 'system' : $order->paytype;
-            $order->method = !$order->method ? 'system' : $order->method;
+            $order->status = OrderEnum::STATUS_PAY;
+            // $order->transaction_id = $transactionid;
+            $order->pay_amount = $payamount;
+            $order->pay_time = time();
             $order->save();
-            if ($order->payamount == $order->saleamount) {
+            if ($order->pay_amount == $order->amount) {
                 //支付完成后,商品销量+1
-                foreach ($order->order_goods as $item) {
-                    $goods = $item->goods;
-                    $sku = $item->sku;
-                    if ($goods) {
-                        $goods->setInc('sales', $item->nums);
-                    }
-                    if ($sku) {
-                        $sku->setInc('sales', $item->nums);
-                    }
-                }
+               OrderGoodsService::setGoodsSalesInc($orderSn);
             }
             // 提交事务
             Db::commit();
@@ -64,7 +126,7 @@ class PayOperService
             return false;
         }
         //记录操作
-        OrderAction::push($order_sn, '系统', '订单支付成功');
+        OrderAction::push($orderSn, '系统', '订单支付成功');
         return true;
     }
 

+ 30 - 0
application/common/service/OrderService.php

@@ -17,6 +17,7 @@ use think\Db;
 use think\Exception;
 use app\common\model\OrderAddress;
 use app\common\Enum\OrderEnum;
+use app\common\exception\BusinessException;
 /**
  * 订单服务类
  * 封装订单创建相关逻辑
@@ -536,6 +537,13 @@ class OrderService
         ->find();
     }
 
+    public static function getDetailByOrderSn($orderSn)
+    {
+        return Order::with(['orderGoods'])
+        ->where('order_sn', $orderSn)
+        ->find();
+    }
+
     // 查询地址信息
     public static function getAddressInfo($orderId)
     {
@@ -595,6 +603,28 @@ class OrderService
         return $info;
     }
 
+    // 更新订单状态
+    public static function updateOrderStatus($orderId = 0, $userId = 0, $status = 0)
+    {
+    
+        $order = self::getDetail($orderId, $userId);
+        if (!$order) {
+            throw new BusinessException('订单不存在!');
+        }
+        // 验证状态
+        if (!OrderEnum::isValidOrderStatus($status)) {
+            throw new BusinessException('状态不合法!');
+        }
+        //  要处理每个状态对应的时间字段在枚举类中
+        $timeField = OrderEnum::STATUS_TIME_MAP[$status];
+        $updateData = [
+            'order_status' => $status,
+            $timeField => time()
+        ];
+        Order::where('id', $orderId)->update($updateData);
+        return $order;
+    }
+
 
 
 }