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;
|
|
|
|
use Yansongda\Pay\Exception\InvalidResponseException;
|
2022-09-18 06:28:29 +00:00
|
|
|
|
|
|
|
class CheckAndChargeBalance extends Job
|
|
|
|
{
|
|
|
|
/**
|
|
|
|
* Create a new job instance.
|
|
|
|
*
|
|
|
|
* @return void
|
|
|
|
*/
|
|
|
|
public function __construct()
|
|
|
|
{
|
|
|
|
//
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Execute the job.
|
|
|
|
*
|
|
|
|
* @return void
|
|
|
|
*/
|
|
|
|
public function handle()
|
|
|
|
{
|
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();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2022-09-18 06:34:54 +00:00
|
|
|
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()
|
|
|
|
]);
|
|
|
|
} catch (InvalidResponseException $e) {
|
|
|
|
Log::error($e->getMessage());
|
|
|
|
return false;
|
|
|
|
} catch (ChargeException $e) {
|
|
|
|
Log::error($e->getMessage());
|
|
|
|
return false;
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
2022-09-18 06:28:29 +00:00
|
|
|
}
|