Lae/app/Jobs/User/CheckAndChargeBalanceJob.php

71 lines
1.7 KiB
PHP
Raw Normal View History

2022-09-18 06:28:29 +00:00
<?php
2023-01-13 14:11:56 +00:00
namespace App\Jobs\User;
2022-09-18 06:28:29 +00:00
2023-01-13 14:11:56 +00:00
use App\Jobs\Job;
2022-11-06 11:28:22 +00:00
use App\Models\Balance;
2023-01-13 14:11:56 +00:00
use Illuminate\Contracts\Queue\ShouldQueue;
2022-11-16 10:06:51 +00:00
use Yansongda\LaravelPay\Facades\Pay;
2023-01-10 13:42:27 +00:00
use Yansongda\Pay\Exception\ContainerException;
use Yansongda\Pay\Exception\InvalidParamsException;
use Yansongda\Pay\Exception\ServiceNotFoundException;
2022-09-18 06:28:29 +00:00
2023-01-13 14:11:56 +00:00
class CheckAndChargeBalanceJob extends Job implements ShouldQueue
2022-09-18 06:28:29 +00:00
{
/**
* Create a new job instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Execute the job.
*
* @return void
*/
2022-12-11 12:59:17 +00:00
public function handle(): void
2022-09-18 06:28:29 +00:00
{
2023-01-10 13:42:27 +00:00
(new Balance)->where('paid_at', null)->chunk(100, function ($balances) {
2022-09-18 06:28:29 +00:00
foreach ($balances as $balance) {
2022-11-16 10:06:51 +00:00
if (!$this->checkAndCharge($balance, true)) {
2022-09-18 06:28:29 +00:00
if (now()->diffInDays($balance->created_at) > 1) {
$balance->delete();
}
}
}
});
2023-01-10 13:42:27 +00:00
(new Balance)->where('paid_at', null)->where('created_at', '<', now()->subDays(2))->delete();
2022-09-18 06:28:29 +00:00
}
2022-11-16 10:06:51 +00:00
public function checkAndCharge(Balance $balance, $check = false): bool
{
if ($check) {
2023-01-10 13:42:27 +00:00
try {
$alipay = Pay::alipay()->find(['out_trade_no' => $balance->order_id]);
} catch (ContainerException|InvalidParamsException|ServiceNotFoundException) {
return false;
}
2022-11-16 10:06:51 +00:00
if ($alipay->trade_status !== 'TRADE_SUCCESS') {
return false;
}
}
if ($balance->paid_at !== null) {
return true;
}
2023-01-10 13:42:27 +00:00
$balance->update([
'paid_at' => now()
]);
2022-11-16 10:06:51 +00:00
return true;
}
2022-09-18 06:28:29 +00:00
}