Lae/app/Jobs/CheckAndChargeBalanceJob.php

72 lines
1.6 KiB
PHP
Raw Normal View History

2022-09-18 06:28:29 +00:00
<?php
namespace App\Jobs;
2022-11-16 10:06:51 +00:00
use App\Exceptions\ChargeException;
2022-11-06 11:28:22 +00:00
use App\Models\Balance;
2022-11-16 10:06:51 +00:00
use App\Models\Transaction;
use Illuminate\Support\Facades\Log;
use Yansongda\LaravelPay\Facades\Pay;
2022-09-18 06:28:29 +00:00
2022-12-28 13:17:54 +00:00
class CheckAndChargeBalanceJob extends Job
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
{
2022-11-16 10:06:51 +00:00
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();
}
}
}
});
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) {
$alipay = Pay::alipay()->find(['out_trade_no' => $balance->order_id]);
if ($alipay->trade_status !== 'TRADE_SUCCESS') {
return false;
}
}
if ($balance->paid_at !== null) {
return true;
}
try {
(new Transaction)->addAmount($balance->user_id, 'alipay', $balance->amount);
$balance->update([
'paid_at' => now()
]);
2022-12-27 16:24:41 +00:00
} catch (ChargeException $e) {
2022-11-16 10:06:51 +00:00
Log::error($e->getMessage());
return false;
}
return true;
}
2022-09-18 06:28:29 +00:00
}