6
0
Fork 0
jiqu-library-server/app/Services/PayService.php

126 lines
3.5 KiB
PHP

<?php
namespace App\Services;
use App\Exceptions\BizException;
use App\Exceptions\InvalidPaySerialNumberException;
use App\Models\{Order, OrderPre};
use App\Models\PayLog;
class PayService
{
/**
* 根据支付流水号处理支付成功业务
*
* @param string $sn
* @param array $params
* @return \App\Models\PayLog
*
* @throws \App\Exceptions\BizException
* @throws \App\Exceptions\InvalidPaySerialNumberException
*/
public function handleSuccessByPaySerialNumber(string $paySerialNumber, array $params = []): PayLog
{
$payLog = PayLog::where('pay_sn', $paySerialNumber)->lockForUpdate()->first();
if ($payLog === null) {
throw new InvalidPaySerialNumberException();
}
return $this->handleSuccess($payLog, $params);
}
/**
* 处理支付成功业务
*
* @param \App\Models\PayLog $payLog
* @param array $params
* @return \App\Models\PayLog
*
* @throws \App\Exceptions\BizException
* @throws \App\Exceptions\InvalidPaySerialNumberException
*/
public function handleSuccess(PayLog $payLog, array $params = []): PayLog
{
if (! $payLog->isPending()) {
throw new InvalidPaySerialNumberException();
}
$payLog->update([
'pay_at' => $params['pay_at'] ?? now(),
'out_trade_no' => $params['out_trade_no'] ?? null,
'status' => PayLog::STATUS_SUCCESS,
]);
$payable = $payLog->payable;
if ($payable instanceof Order) {
if ($payable->isPaid()) {
throw new BizException('订单已支付');
}
if ($payable->isCompleted()) {
throw new BizException('订单已完成');
}
$payable->update([
'pay_sn' => $payLog->pay_sn,
'pay_way' => $payLog->pay_way,
'pay_at' => $payLog->pay_at,
'out_trade_no' => $payLog->out_trade_no,
'status' => Order::STATUS_PAID,
]);
} else if ($payable instanceof \App\Models\UserVip) {
(new App\Services\VipService())->success($payable, ['pay_at' => $payLog->pay_at]);
}
return $payLog;
}
/**
* 根据支付流水号处理支付失败业务
*
* @param string $sn
* @param array $params
* @return \App\Models\PayLog
*
* @throws \App\Exceptions\BizException
* @throws \App\Exceptions\InvalidPaySerialNumberException
*/
public function handleFailedByPaySerialNumber(string $paySerialNumber, array $params = []): PayLog
{
$payLog = PayLog::where('pay_sn', $paySerialNumber)->lockForUpdate()->first();
if ($payLog === null) {
throw new InvalidPaySerialNumberException();
}
return $this->handleFailed($payLog, $params);
}
/**
* 处理支付失败业务
*
* @param \App\Models\PayLog $payLog
* @param array $params
* @return \App\Models\PayLog
*
* @throws \App\Exceptions\BizException
* @throws \App\Exceptions\InvalidPaySerialNumberException
*/
public function handleFailed(PayLog $payLog, array $params = []): PayLog
{
if (! $payLog->isPending()) {
throw new InvalidPaySerialNumberException();
}
$payLog->update([
'out_trade_no' => $params['out_trade_no'] ?? null,
'status' => PayLog::STATUS_FAILED,
'failed_reason' => $params['failed_reason'] ?? null,
]);
return $payLog;
}
}