You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
247 lines
10 KiB
PHP
247 lines
10 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Payment;
|
|
|
|
use App\Models\CloudInvoicePayment;
|
|
use App\Models\Paylist;
|
|
use App\Models\PaytaroCallbackEvent;
|
|
use App\Models\PaytaroOrder;
|
|
use App\Models\User;
|
|
use App\Services\Cloud\CloudInvoicePaymentService;
|
|
|
|
class PaytaroPaymentService
|
|
{
|
|
public const LEDGER_TYPE = 10005;
|
|
private const ORDER_PATTERN = '/^PT\d{14}[A-F0-9]{16}$/';
|
|
|
|
public function createOrder(User $user, $rawAmount, $clientIp, $userAgent, $returnBaseUrl,
|
|
array $businessContext = [])
|
|
{
|
|
$settings = PaytaroConfig::runtimeForUser($user);
|
|
$amount = $this->validateAmount($rawAmount, $settings);
|
|
$orderNo = $this->orderNo();
|
|
$now = time();
|
|
if (PaytaroOrder::where('user_id', (int) $user->id)->where('created_at', '>=', $now - 60)->count() >= 5) {
|
|
throw new \RuntimeException('Paytaro 下单过于频繁,请稍后重试');
|
|
}
|
|
|
|
$connection = (new PaytaroOrder())->getConnection();
|
|
$connection->transaction(function () use (
|
|
$user, $amount, $orderNo, $now, $businessContext
|
|
) {
|
|
$lockedUser = User::where('id', (int) $user->id)->lockForUpdate()->first();
|
|
if ($lockedUser === null) {
|
|
throw new \RuntimeException('支付账户不存在');
|
|
}
|
|
if ($businessContext !== []) {
|
|
CloudInvoicePaymentService::assertInvoicePaymentAllowed($lockedUser);
|
|
}
|
|
$paylist = new Paylist();
|
|
$paylist->userid = (int) $user->id;
|
|
$paylist->total = $amount;
|
|
$paylist->status = 0;
|
|
$paylist->tradeno = $orderNo;
|
|
$paylist->datetime = $now;
|
|
$paylist->save();
|
|
|
|
$order = new PaytaroOrder();
|
|
$order->order_no = $orderNo;
|
|
$order->paylist_id = (int) $paylist->id;
|
|
$order->user_id = (int) $user->id;
|
|
$order->amount = $amount;
|
|
$order->status = 'creating';
|
|
$order->created_at = $now;
|
|
$order->updated_at = $now;
|
|
$order->save();
|
|
|
|
CloudInvoicePaymentService::recordAttempt(
|
|
$businessContext, $orderNo, $amount, (int) $user->id, $now
|
|
);
|
|
});
|
|
|
|
$baseUrl = rtrim((string) $settings['paytaro_callback_base_url'], '/');
|
|
$payload = [
|
|
'pid' => (string) $settings['paytaro_app_id'],
|
|
'type' => (string) $settings['paytaro_method_uuid'],
|
|
'out_trade_no' => $orderNo,
|
|
'notify_url' => $baseUrl . '/paytaro/callback',
|
|
'return_url' => rtrim((string) $returnBaseUrl, '/') . '/paytaro/return',
|
|
'name' => 'Account balance recharge',
|
|
'money' => $amount,
|
|
];
|
|
try {
|
|
$gateway = $this->gatewayClient($settings)->createOrder($payload);
|
|
return $this->bindGatewayOrder($orderNo, $gateway);
|
|
} catch (\Throwable $exception) {
|
|
$failedAt = time();
|
|
$connection->transaction(function () use (
|
|
$orderNo, $businessContext, $exception, $failedAt
|
|
) {
|
|
PaytaroOrder::where('order_no', $orderNo)->where('status', 'creating')->update([
|
|
'status' => 'failed',
|
|
'error_message' => mb_substr($exception->getMessage(), 0, 500),
|
|
'updated_at' => $failedAt,
|
|
]);
|
|
if ($businessContext !== []) {
|
|
CloudInvoicePayment::where('provider_order_no', $orderNo)
|
|
->where('provider', (string) ($businessContext['provider'] ?? ''))
|
|
->where('status', 'creating')
|
|
->update(['status' => 'failed', 'updated_at' => $failedAt]);
|
|
}
|
|
});
|
|
throw $exception;
|
|
}
|
|
}
|
|
|
|
public function processCallback(array $payload)
|
|
{
|
|
$settings = PaytaroConfig::callbackCredentials();
|
|
$notification = PaytaroProtocol::notification($payload, $settings, self::ORDER_PATTERN);
|
|
$orderNo = $notification['order_no'];
|
|
$tradeNo = $notification['trade_no'];
|
|
$eventKey = $notification['event_key'];
|
|
$now = time();
|
|
$credited = false;
|
|
$duplicate = false;
|
|
|
|
$connection = (new PaytaroOrder())->getConnection();
|
|
$connection->transaction(function () use ($notification, $orderNo, $tradeNo, $eventKey, $now, &$credited, &$duplicate) {
|
|
$order = PaytaroOrder::where('order_no', $orderNo)->lockForUpdate()->first();
|
|
if ($order === null) {
|
|
throw new \RuntimeException('Paytaro 本地订单不存在');
|
|
}
|
|
if ($notification['amount_cents'] !== null
|
|
&& PaytaroProtocol::amountToCents($order->amount) !== (string) $notification['amount_cents']) {
|
|
throw new \RuntimeException('Paytaro 回调金额不匹配');
|
|
}
|
|
if ((string) $order->gateway_trade_no !== '' && (string) $order->gateway_trade_no !== $tradeNo) {
|
|
throw new \RuntimeException('Paytaro 平台订单号不匹配');
|
|
}
|
|
if (PaytaroOrder::where('gateway_trade_no', $tradeNo)->where('order_no', '<>', $orderNo)->exists()) {
|
|
throw new \RuntimeException('Paytaro 平台订单号已绑定其他订单');
|
|
}
|
|
|
|
$existing = PaytaroCallbackEvent::where('event_key', $eventKey)->first();
|
|
if ($existing !== null) {
|
|
if ((string) $order->status !== 'paid' || (int) $existing->processed_at <= 0) {
|
|
throw new \RuntimeException('Paytaro 重复回调事件状态异常');
|
|
}
|
|
$duplicate = true;
|
|
return;
|
|
}
|
|
if ((string) $order->status === 'paid') {
|
|
$duplicate = true;
|
|
return;
|
|
}
|
|
// A gateway request may time out after Paytaro accepted it. A
|
|
// later signed callback is the authoritative proof of payment,
|
|
// so a locally failed/ambiguous creation must still reconcile.
|
|
if (!in_array((string) $order->status, ['creating', 'pending', 'failed'], true)) {
|
|
throw new \RuntimeException('Paytaro 本地订单状态无效');
|
|
}
|
|
|
|
$event = new PaytaroCallbackEvent();
|
|
$event->event_key = $eventKey;
|
|
$event->order_no = $orderNo;
|
|
$event->gateway_trade_no = $tradeNo;
|
|
$event->trade_status = $this->callbackStatus($notification['payload']);
|
|
$event->payload = $notification['payload'];
|
|
$event->received_at = $now;
|
|
$event->processed_at = 0;
|
|
$event->save();
|
|
|
|
$paylist = Paylist::where('id', (int) $order->paylist_id)->lockForUpdate()->first();
|
|
if ($paylist === null || (string) $paylist->tradeno !== $orderNo || (int) $paylist->userid !== (int) $order->user_id) {
|
|
throw new \RuntimeException('Paytaro 关联充值订单无效');
|
|
}
|
|
$credited = RechargeCreditService::creditLocked($paylist, self::LEDGER_TYPE, true);
|
|
if (CloudInvoicePayment::where('provider', 'paytaro')
|
|
->where('provider_order_no', $orderNo)->exists()) {
|
|
CloudInvoicePaymentService::settleForProvider('paytaro', $orderNo);
|
|
}
|
|
$order->gateway_trade_no = $tradeNo;
|
|
$order->status = 'paid';
|
|
$order->paid_at = $now;
|
|
$order->updated_at = $now;
|
|
$order->error_message = '';
|
|
$order->save();
|
|
|
|
$event->processed_at = $now;
|
|
$event->save();
|
|
}, 3);
|
|
|
|
return ['credited' => $credited, 'duplicate' => $duplicate, 'order_no' => $orderNo];
|
|
}
|
|
|
|
public function returnOrderNo(array $payload)
|
|
{
|
|
return PaytaroProtocol::returnOrderNo($payload, self::ORDER_PATTERN);
|
|
}
|
|
|
|
protected function gatewayClient(array $settings)
|
|
{
|
|
return new PaytaroClient($settings);
|
|
}
|
|
|
|
private function bindGatewayOrder($orderNo, array $gateway)
|
|
{
|
|
$kind = trim((string) ($gateway['payment_kind'] ?? ''));
|
|
$value = trim((string) ($gateway['payment_value'] ?? ''));
|
|
$tradeNo = trim((string) ($gateway['gateway_trade_no'] ?? ''));
|
|
if ($kind !== 'payurl' || $value === '' || !preg_match('/^[A-Za-z0-9_.:-]{1,80}$/', $tradeNo)) {
|
|
throw new \RuntimeException('Paytaro 支付信息无效');
|
|
}
|
|
|
|
$order = null;
|
|
$connection = (new PaytaroOrder())->getConnection();
|
|
$connection->transaction(function () use ($orderNo, $tradeNo, $kind, $value, &$order) {
|
|
$order = PaytaroOrder::where('order_no', $orderNo)->lockForUpdate()->first();
|
|
if ($order === null || (string) $order->status !== 'creating') {
|
|
throw new \RuntimeException('Paytaro 本地订单状态无效');
|
|
}
|
|
if (PaytaroOrder::where('gateway_trade_no', $tradeNo)->where('order_no', '<>', $orderNo)->exists()) {
|
|
throw new \RuntimeException('Paytaro 平台订单号已绑定其他订单');
|
|
}
|
|
$order->gateway_trade_no = $tradeNo;
|
|
$order->payment_kind = $kind;
|
|
$order->payment_value = $value;
|
|
$order->status = 'pending';
|
|
$order->updated_at = time();
|
|
$order->save();
|
|
}, 3);
|
|
return $order;
|
|
}
|
|
|
|
private function validateAmount($rawAmount, array $settings)
|
|
{
|
|
$rawAmount = trim((string) $rawAmount);
|
|
if (!preg_match('/^\d{1,10}(?:\.\d{1,2})?$/', $rawAmount)) {
|
|
throw new \InvalidArgumentException('充值金额格式无效,最多保留两位小数');
|
|
}
|
|
$amount = PaymentAmount::normalize($rawAmount);
|
|
if ((float) $amount < (float) $settings['paytaro_min_amount'] || (float) $amount > (float) $settings['paytaro_max_amount']) {
|
|
throw new \InvalidArgumentException('充值金额必须在 $' . $settings['paytaro_min_amount'] . ' 到 $' . $settings['paytaro_max_amount'] . ' 之间');
|
|
}
|
|
return $amount;
|
|
}
|
|
|
|
private function callbackStatus($json)
|
|
{
|
|
$payload = json_decode((string) $json, true);
|
|
if (!is_array($payload)) {
|
|
return 'SUCCESS';
|
|
}
|
|
foreach (['trade_status', 'payment_status', 'status'] as $key) {
|
|
if (isset($payload[$key]) && trim((string) $payload[$key]) !== '') {
|
|
return mb_substr(trim((string) $payload[$key]), 0, 32);
|
|
}
|
|
}
|
|
return 'SUCCESS';
|
|
}
|
|
|
|
private function orderNo()
|
|
{
|
|
return 'PT' . date('YmdHis') . strtoupper(bin2hex(random_bytes(8)));
|
|
}
|
|
}
|