OrderObserver.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. namespace App\Observers;
  3. use App\Components\Helpers;
  4. use App\Models\Coupon;
  5. use App\Models\Order;
  6. use App\Models\User;
  7. use App\Notifications\PaymentConfirm;
  8. use App\Services\OrderService;
  9. use Arr;
  10. use Notification;
  11. class OrderObserver
  12. {
  13. public function updated(Order $order): void
  14. {
  15. $changes = $order->getChanges();
  16. if (Arr::exists($changes, 'status')) {
  17. if ($changes['status'] === -1) { // 本地订单-在线订单 关闭互联
  18. if ($order->payment) {
  19. $order->payment->close(); // 关闭在线订单
  20. }
  21. if ($order->coupon && $this->returnCoupon($order->coupon)) { // 退回优惠券
  22. Helpers::addCouponLog('订单超时未支付,自动退回', $order->coupon_id, $order->goods_id, $order->id);
  23. }
  24. }
  25. if ($changes['status'] === 1) { // 待确认支付
  26. Notification::send(User::find(1), new PaymentConfirm($order));
  27. }
  28. // 本地订单-在线订单 支付成功互联
  29. if ($changes['status'] === 2 && $order->getOriginal('status') !== 3) {
  30. (new OrderService($order))->receivedPayment();
  31. }
  32. }
  33. // 套餐订单-流量包订单互联
  34. if (Arr::exists($changes, 'is_expire') && $changes['is_expire'] === 1) {
  35. // 过期生效中的加油包
  36. Order::userActivePackage($order->user_id)->update(['is_expire' => 1]);
  37. // 检查该订单对应用户是否有预支付套餐
  38. $prepaidOrder = Order::userPrepay($order->user_id)->oldest()->first();
  39. if ($prepaidOrder) {
  40. (new OrderService($prepaidOrder))->activatePrepaidPlan(); // 激活预支付
  41. }
  42. }
  43. }
  44. // 返回优惠券
  45. private function returnCoupon(Coupon $coupon): bool
  46. {
  47. if ($coupon && $coupon->type !== 3) {
  48. return $coupon->update(['usable_times' => $coupon->usable_times + 1, 'status' => 0]);
  49. }
  50. return false;
  51. }
  52. }