Skip to content

Commit

Permalink
关闭未支付订单
Browse files Browse the repository at this point in the history
  • Loading branch information
summerblue committed Mar 9, 2021
1 parent 4d5850f commit 56ad650
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
3 changes: 3 additions & 0 deletions app/Http/Controllers/OrdersController.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use App\Models\Order;
use Carbon\Carbon;
use App\Exceptions\InvalidRequestException;
use App\Jobs\CloseOrder;

class OrdersController extends Controller
{
Expand Down Expand Up @@ -64,6 +65,8 @@ public function store(OrderRequest $request)
return $order;
});

$this->dispatch(new CloseOrder($order, config('app.order_ttl')));

return $order;
}
}
46 changes: 46 additions & 0 deletions app/Jobs/CloseOrder.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Models\Order;

// 代表这个类需要被放到队列中执行,而不是触发时立即执行
class CloseOrder implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

protected $order;

public function __construct(Order $order, $delay)
{
$this->order = $order;
// 设置延迟的时间,delay() 方法的参数代表多少秒之后执行
$this->delay($delay);
}

// 定义这个任务类具体的执行逻辑
// 当队列处理器从队列中取出任务时,会调用 handle() 方法
public function handle()
{
// 判断对应的订单是否已经被支付
// 如果已经支付则不需要关闭订单,直接退出
if ($this->order->paid_at) {
return;
}
// 通过事务执行 sql
\DB::transaction(function() {
// 将订单的 closed 字段标记为 true,即关闭订单
$this->order->update(['closed' => true]);
// 循环遍历订单中的商品 SKU,将订单中的数量加回到 SKU 的库存中去
foreach ($this->order->items as $item) {
$item->productSku->addStock($item->amount);
}
});
}
}
2 changes: 2 additions & 0 deletions config/app.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

return [

'order_ttl' => 1800,

/*
|--------------------------------------------------------------------------
| Application Name
Expand Down

0 comments on commit 56ad650

Please sign in to comment.