106 lines
2.8 KiB
PHP
106 lines
2.8 KiB
PHP
<?php
|
|
|
|
namespace App\Endpoint\Callback\Http\Controllers;
|
|
|
|
use App\Events\OrderPaid;
|
|
use App\Exceptions\BizException;
|
|
use App\Models\Order;
|
|
use App\Services\AlipayService;
|
|
use App\Services\PayService;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Carbon;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Facades\Log;
|
|
use Throwable;
|
|
|
|
class AlipayController extends Controller
|
|
{
|
|
/**
|
|
* 通知
|
|
*
|
|
* @param \Illuminate\Http\Request $request
|
|
* @param \App\Services\AlipayService $alipayService
|
|
* @return \Illuminate\Http\Response
|
|
*/
|
|
public function __invoke(Request $request, AlipayService $alipayService)
|
|
{
|
|
$this->log('notify', $request->all());
|
|
|
|
if (! $alipayService->verifyNotify($request->all())) {
|
|
throw new BizException('签名校验失败');
|
|
}
|
|
|
|
if ($request->filled('out_biz_no')) {
|
|
return $this->refundedNotify($request);
|
|
}
|
|
|
|
return $this->paidNotify($request);
|
|
}
|
|
|
|
/**
|
|
* 付款通知
|
|
*
|
|
* @param Request $request
|
|
* @return void
|
|
*/
|
|
protected function paidNotify(Request $request)
|
|
{
|
|
$input = $request->all();
|
|
|
|
try {
|
|
$payLog = DB::transaction(function () use ($input) {
|
|
$tradeStatus = data_get($input, 'trade_status');
|
|
|
|
if (in_array($tradeStatus, ['TRADE_SUCCESS', 'TRADE_FINISHED'])) {
|
|
(new PayService())->handleSuccessByPaySerialNumber($input['out_trade_no'], [
|
|
'out_trade_no' => $input['trade_no'],
|
|
'pay_at' => Carbon::parse($input['gmt_payment']),
|
|
]);
|
|
} elseif ($tradeStatus === 'TRADE_CLOSED') {
|
|
(new PayService())->handleFailedByPaySerialNumber($input['out_trade_no'], [
|
|
'out_trade_no' => $input['trade_no'] ?? null,
|
|
'failed_reason' => '未付款交易超时关闭',
|
|
]);
|
|
}
|
|
});
|
|
|
|
$payable = $payLog?->payable;
|
|
|
|
if ($payable instanceof Order) {
|
|
OrderPaid::dispatchIf($payable->isPaid(), $payable);
|
|
}
|
|
} catch (BizException $e) {
|
|
} catch (Throwable $e) {
|
|
throw $e;
|
|
}
|
|
|
|
return 'success';
|
|
}
|
|
|
|
/**
|
|
* 退款通知
|
|
*
|
|
* @param Request $request
|
|
* @return void
|
|
*/
|
|
protected function refundedNotify(Request $request)
|
|
{
|
|
return 'success';
|
|
}
|
|
|
|
/**
|
|
* 微信回调日志
|
|
*
|
|
* @param string $message
|
|
* @param array $context
|
|
* @return void
|
|
*/
|
|
protected function log(string $message, array $context = [])
|
|
{
|
|
return Log::build([
|
|
'driver' => 'daily',
|
|
'path' => storage_path('logs/alipay-notify.log'),
|
|
])->info($message, $context);
|
|
}
|
|
}
|