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.
virt/web/app/Services/Payment/YipayPaymentService.php

383 lines
16 KiB
PHP

<?php
namespace App\Services\Payment;
use App\Models\CloudInvoicePayment;
use App\Models\Paylist;
use App\Models\User;
use App\Models\YipayCallbackEvent;
use App\Models\YipayOrder;
use App\Services\Cloud\CloudInvoicePaymentService;
use App\Services\Cloud\CloudMoney;
class YipayPaymentService
{
public const LEDGER_TYPE = 10007;
public function createOrder(User $user, $rawAmount, $rawMethod, $clientIp, $userAgent,
$returnBaseUrl, array $businessContext = [])
{
$method = YipayConfig::normalizeMethod($rawMethod);
$settings = YipayConfig::runtimeForUser($user, $method);
$amount = $this->validateAmount($rawAmount, $settings);
$orderNo = $this->orderNo();
$now = time();
$quote = PaymentCheckoutQuotes::prepare('yipay_' . $method, $amount, $now, null);
if (YipayOrder::where('user_id', (int) $user->id)->where('created_at', '>=', $now - 60)->count() >= 5) {
throw new \RuntimeException('易支付下单过于频繁,请稍后重试');
}
$connection = (new YipayOrder())->getConnection();
$connection->transaction(function () use (
$user, $amount, $method, $orderNo, $now, $businessContext, $quote
) {
$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 YipayOrder();
$order->order_no = $orderNo;
$order->paylist_id = (int) $paylist->id;
$order->user_id = (int) $user->id;
$order->payment_type = $method;
$order->amount = $amount;
$order->status = 'creating';
$order->created_at = $now;
$order->updated_at = $now;
$order->save();
PaymentCheckoutQuotes::persist($quote, $orderNo, (int) $user->id);
CloudInvoicePaymentService::recordAttempt(
$businessContext, $orderNo, $amount, (int) $user->id, $now
);
});
$baseUrl = rtrim((string) $settings['yipay_callback_base_url'], '/');
$payload = [
'pid' => (string) $settings['yipay_pid'],
'type' => $method,
'out_trade_no' => $orderNo,
'notify_url' => $baseUrl . '/yipay/callback',
'return_url' => rtrim((string) $returnBaseUrl, '/') . '/yipay/return',
'name' => (string) $settings['yipay_order_name'],
'money' => PaymentCheckoutQuotes::formatUnits('CNY', $quote->expected_units),
'clientip' => $this->normalizeIp($clientIp),
'device' => $this->device((string) $userAgent),
];
try {
$gateway = $this->gatewayClient($settings)->createOrder($payload);
return $this->bindGatewayOrder($orderNo, $gateway);
} catch (\Throwable $exception) {
$failedAt = time();
$effectUnknown = !($exception instanceof
PaymentOrderCreationException)
|| $exception->effectMayHaveApplied;
$failureStatus = $effectUnknown
? 'creation_unknown' : 'not_created';
$connection->transaction(function () use (
$orderNo, $businessContext, $exception, $failedAt,
$failureStatus
) {
YipayOrder::where('order_no', $orderNo)->where('status', 'creating')->update([
'status' => $failureStatus,
'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' => $failureStatus,
'updated_at' => $failedAt]);
}
});
throw $exception instanceof PaymentOrderCreationException
? $exception : PaymentOrderCreationException::unknown(
'易支付订单已发送,但本地结果未确认'
);
}
}
public function processCallback(array $payload)
{
$settings = YipayConfig::callbackCredentials();
$this->validateNotification($payload, $settings);
$orderNo = trim((string) $payload['out_trade_no']);
$tradeNo = trim((string) $payload['trade_no']);
$eventKey = hash('sha256', YipaySigner::canonical($payload));
$now = time();
$credited = false;
$duplicate = false;
$review = false;
$units = CloudMoney::cents(PaymentAmount::normalize($payload['money']));
$connection = (new YipayOrder())->getConnection();
$connection->transaction(function () use (
$payload, $orderNo, $tradeNo, $eventKey, $now, $units, &$credited, &$duplicate, &$review
) {
$order = YipayOrder::where('order_no', $orderNo)->lockForUpdate()->first();
if ($order === null) {
throw new \RuntimeException('易支付本地订单不存在');
}
if ((string) $order->payment_type !== (string) $payload['type']) {
throw new \RuntimeException('易支付回调支付方式不匹配');
}
if ((string) $order->gateway_trade_no !== '' && (string) $order->gateway_trade_no !== $tradeNo) {
throw new \RuntimeException('易支付平台订单号不匹配');
}
$sameTrade = YipayOrder::where('gateway_trade_no', $tradeNo)
->where('order_no', '<>', $orderNo)
->first();
if ($sameTrade !== null) {
throw new \RuntimeException('易支付平台订单号已绑定其他订单');
}
$invoiceProvider = 'yipay_' . (string) $order->payment_type;
if (in_array((string) $order->status, ['paid', 'refunded'], true)) {
$received = PaymentCheckoutQuotes::find($invoiceProvider, $orderNo)?->received_units
?? CloudMoney::cents((string) $order->amount);
if ($received !== $units) {
throw new \RuntimeException('易支付已支付金额与回调不一致');
}
$duplicate = true;
return;
}
$existing = YipayCallbackEvent::where('event_key', $eventKey)->first();
if ($existing !== null) {
if ((int) $existing->processed_at <= 0) {
throw new \RuntimeException('易支付重复回调事件状态异常');
}
$review = PaymentCheckoutQuotes::find($invoiceProvider, $orderNo)?->status === 'review';
$duplicate = true;
return;
}
if (!in_array((string) $order->status, ['creating', 'pending', 'creation_unknown', 'not_created', 'expired'], true)) {
throw new \RuntimeException('易支付本地订单状态无效');
}
$event = new YipayCallbackEvent();
$event->event_key = $eventKey;
$event->order_no = $orderNo;
$event->gateway_trade_no = $tradeNo;
$event->payment_type = (string) $payload['type'];
$event->trade_status = (string) $payload['trade_status'];
$event->payload = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$event->received_at = $now;
$event->processed_at = 0;
$event->save();
$quote = PaymentCheckoutQuotes::receive($invoiceProvider, $orderNo, (int) $order->user_id,
(string) $order->amount, CloudMoney::cents((string) $order->amount), $units, $tradeNo, $now,
null, strtoupper(trim((string) ($payload['currency'] ?? 'CNY'))));
if ($quote->status === 'review') {
$review = true;
$order->gateway_trade_no = $tradeNo;
$order->status = 'pending';
$order->payment_value = null;
$order->error_message = '收款凭证已保存,需人工核对';
$order->updated_at = $now;
$order->save();
$event->processed_at = $now;
$event->save();
CloudInvoicePaymentService::recordProviderReview($invoiceProvider, $orderNo, $now);
return;
}
$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('易支付关联充值订单无效');
}
$credited = RechargeCreditService::creditLocked($paylist, self::LEDGER_TYPE, true, $quote);
if (CloudInvoicePayment::where('provider', $invoiceProvider)
->where('provider_order_no', $orderNo)->exists()) {
CloudInvoicePaymentService::settleForProvider($invoiceProvider, $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, 'review' => $review, 'order_no' => $orderNo];
}
public function validateReturn(array $payload)
{
$settings = YipayConfig::callbackCredentials();
$this->validateNotification($payload, $settings);
return trim((string) $payload['out_trade_no']);
}
public function refundById($rawRecordId, $adminUserId)
{
$recordId = filter_var($rawRecordId, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
if ($recordId === false) {
throw new \InvalidArgumentException('退款记录无效');
}
$orderNo = YipayOrder::where('id', (int) $recordId)->value('order_no');
if (!is_string($orderNo) || $orderNo === '') {
throw new \InvalidArgumentException('退款记录不存在');
}
return $this->refund($orderNo, $adminUserId);
}
public function refund($rawOrderNo, $adminUserId)
{
return YipayRefundService::execute(trim((string) $rawOrderNo), (int) $adminUserId,
fn (): callable => [$this->gatewayClient(YipayConfig::runtime(false)), 'refund']);
}
private function validateNotification(array $payload, array $settings)
{
if (count($payload) > 32) {
throw new \RuntimeException('易支付回调参数过多');
}
foreach ($payload as $value) {
if (!is_scalar($value) && $value !== null) {
throw new \RuntimeException('易支付回调参数格式无效');
}
}
if (!YipaySigner::verify($payload, $settings[YipayConfig::SECRET_KEY])) {
throw new \RuntimeException('易支付回调签名错误');
}
if ((string) ($payload['pid'] ?? '') !== (string) $settings['yipay_pid']) {
throw new \RuntimeException('易支付回调 PID 不匹配');
}
if ((string) ($payload['trade_status'] ?? '') !== 'TRADE_SUCCESS') {
throw new \RuntimeException('易支付回调状态不是支付成功');
}
$orderNo = trim((string) ($payload['out_trade_no'] ?? ''));
$tradeNo = trim((string) ($payload['trade_no'] ?? ''));
if (!preg_match('/^YP\d{14}[A-F0-9]{16}$/', $orderNo)) {
throw new \RuntimeException('易支付商户订单号格式无效');
}
if (!preg_match('/^[A-Za-z0-9_-]{1,80}$/', $tradeNo)) {
throw new \RuntimeException('易支付平台订单号格式无效');
}
YipayConfig::normalizeMethod($payload['type'] ?? '');
if (!isset($payload['money']) || !preg_match('/^\d{1,10}(?:\.\d{1,2})?$/', trim((string) $payload['money']))) {
throw new \RuntimeException('易支付回调金额格式无效');
}
}
private function bindGatewayOrder($orderNo, array $gateway)
{
$tradeNo = trim((string) ($gateway['trade_no'] ?? ''));
if (!preg_match('/^[A-Za-z0-9_-]{1,80}$/', $tradeNo)) {
throw new \RuntimeException('易支付平台订单号无效');
}
[$kind, $paymentValue] = $this->paymentValue($gateway);
$order = null;
$connection = (new YipayOrder())->getConnection();
$connection->transaction(function () use ($orderNo, $tradeNo, $kind, $paymentValue, &$order) {
$order = YipayOrder::where('order_no', $orderNo)->lockForUpdate()->first();
if ($order !== null && (string) $order->gateway_trade_no === $tradeNo
&& PaymentCheckoutQuotes::find('yipay_' . $order->payment_type, $orderNo)?->receipt_ref !== null) {
return;
}
if ($order === null || (string) $order->status !== 'creating') {
throw new \RuntimeException('易支付本地订单状态无效');
}
$sameTrade = YipayOrder::where('gateway_trade_no', $tradeNo)
->where('order_no', '<>', $orderNo)
->first();
if ($sameTrade !== null) {
throw new \RuntimeException('易支付平台订单号已被使用');
}
$order->gateway_trade_no = $tradeNo;
$order->payment_kind = $kind;
$order->payment_value = $paymentValue;
$order->status = 'pending';
$order->updated_at = time();
$order->save();
}, 3);
return $order;
}
private function paymentValue(array $gateway)
{
foreach (['payurl', 'qrcode', 'urlscheme'] as $kind) {
$value = trim((string) ($gateway[$kind] ?? ''));
if ($value === '') {
continue;
}
if (strlen($value) > 2048 || !$this->safePaymentUrl($value)) {
throw new \RuntimeException('易支付返回了不安全的支付地址');
}
return [$kind, $value];
}
throw new \RuntimeException('易支付未返回支付链接或二维码');
}
private function safePaymentUrl($value)
{
return preg_match('/[\x00-\x20\x7F]/', (string) $value) !== 1
&& preg_match('#^(https://|weixin://|alipays://|alipayqr://)#i', (string) $value) === 1;
}
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['yipay_min_amount'] || (float) $amount > (float) $settings['yipay_max_amount']) {
throw new \InvalidArgumentException('充值金额必须在 $' . $settings['yipay_min_amount'] . ' 到 $' . $settings['yipay_max_amount'] . ' 之间');
}
return $amount;
}
private function normalizeIp($clientIp)
{
$clientIp = str_replace('::ffff:', '', trim((string) $clientIp));
return filter_var($clientIp, FILTER_VALIDATE_IP) !== false ? $clientIp : '127.0.0.1';
}
private function device($userAgent)
{
if (stripos($userAgent, 'MicroMessenger') !== false) {
return 'wechat';
}
if (stripos($userAgent, 'AlipayClient') !== false) {
return 'alipay';
}
if (preg_match('/\bQQ\//i', $userAgent)) {
return 'qq';
}
return preg_match('/Android|iPhone|iPad|Mobile/i', $userAgent) ? 'mobile' : 'pc';
}
private function orderNo()
{
return 'YP' . date('YmdHis') . strtoupper(bin2hex(random_bytes(8)));
}
protected function gatewayClient(array $settings)
{
return new YipayClient($settings);
}
}