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.
485 lines
21 KiB
PHP
485 lines
21 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Payment;
|
|
|
|
use App\Models\CloudInvoicePayment;
|
|
use App\Models\Code;
|
|
use App\Models\Paylist;
|
|
use App\Models\Payback;
|
|
use App\Models\User;
|
|
use App\Models\YipayCallbackEvent;
|
|
use App\Models\YipayOrder;
|
|
use App\Models\YipayRefund;
|
|
use App\Services\Cloud\CloudInvoicePaymentService;
|
|
|
|
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();
|
|
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
|
|
) {
|
|
$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();
|
|
|
|
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' => $amount,
|
|
'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();
|
|
$connection->transaction(function () use (
|
|
$orderNo, $businessContext, $exception, $failedAt
|
|
) {
|
|
YipayOrder::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 = 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;
|
|
|
|
$connection = (new YipayOrder())->getConnection();
|
|
$connection->transaction(function () use ($payload, $orderNo, $tradeNo, $eventKey, $now, &$credited, &$duplicate) {
|
|
$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 (PaymentAmount::normalize($payload['money']) !== PaymentAmount::normalize($order->amount)) {
|
|
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('易支付平台订单号已绑定其他订单');
|
|
}
|
|
|
|
if ((string) $order->status === 'refunded') {
|
|
$duplicate = true;
|
|
return;
|
|
}
|
|
|
|
$existing = YipayCallbackEvent::where('event_key', $eventKey)->first();
|
|
if ($existing !== null) {
|
|
if ((string) $order->status !== 'paid' || (int) $existing->processed_at <= 0) {
|
|
throw new \RuntimeException('易支付重复回调事件状态异常');
|
|
}
|
|
$duplicate = true;
|
|
return;
|
|
}
|
|
|
|
$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();
|
|
|
|
$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);
|
|
$invoiceProvider = 'yipay_' . (string) $order->payment_type;
|
|
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, '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)
|
|
{
|
|
$orderNo = trim((string) $rawOrderNo);
|
|
if (!preg_match('/^YP\d{14}[A-F0-9]{16}$/', $orderNo)) {
|
|
throw new \InvalidArgumentException('易支付商户订单号格式无效');
|
|
}
|
|
$adminUserId = (int) $adminUserId;
|
|
if ($adminUserId <= 0) {
|
|
throw new \RuntimeException('退款管理员身份无效');
|
|
}
|
|
if (CloudInvoicePayment::where('provider_order_no', $orderNo)
|
|
->whereIn('provider', ['yipay_alipay', 'yipay_wxpay'])->exists()) {
|
|
throw new \RuntimeException('账单支付不支持自动退款,请人工核对服务期后处理');
|
|
}
|
|
|
|
$settings = YipayConfig::runtime(false);
|
|
$result = null;
|
|
$gatewaySucceeded = false;
|
|
$connection = (new YipayOrder())->getConnection();
|
|
|
|
try {
|
|
$connection->transaction(function () use ($orderNo, $adminUserId, $settings, &$result, &$gatewaySucceeded) {
|
|
$order = YipayOrder::where('order_no', $orderNo)->lockForUpdate()->first();
|
|
if ($order === null) {
|
|
throw new \RuntimeException('易支付订单不存在');
|
|
}
|
|
if ((string) $order->status === 'refunded') {
|
|
throw new \RuntimeException('该订单已经退款,不能重复操作');
|
|
}
|
|
if ((string) $order->status !== 'paid') {
|
|
throw new \RuntimeException('只有已支付订单可以退款');
|
|
}
|
|
if (CloudInvoicePayment::where('provider_order_no', $orderNo)
|
|
->whereIn('provider', ['yipay_alipay', 'yipay_wxpay'])->exists()) {
|
|
throw new \RuntimeException('账单支付不支持自动退款,请人工核对服务期后处理');
|
|
}
|
|
$tradeNo = trim((string) $order->gateway_trade_no);
|
|
if (!preg_match('/^[A-Za-z0-9_-]{1,80}$/', $tradeNo)) {
|
|
throw new \RuntimeException('易支付平台订单号无效,不能退款');
|
|
}
|
|
if (YipayRefund::where('order_no', $orderNo)->exists()) {
|
|
throw new \RuntimeException('该订单已经存在退款记录,不能重复操作');
|
|
}
|
|
|
|
$paylist = Paylist::where('id', (int) $order->paylist_id)->lockForUpdate()->first();
|
|
if ($paylist === null || (int) $paylist->status !== 1 || (string) $paylist->tradeno !== $orderNo) {
|
|
throw new \RuntimeException('订单充值记录状态异常,已阻止退款');
|
|
}
|
|
$user = User::where('id', (int) $order->user_id)->lockForUpdate()->first();
|
|
if ($user === null) {
|
|
throw new \RuntimeException('充值用户不存在,已阻止退款');
|
|
}
|
|
$amount = PaymentAmount::normalize($order->amount);
|
|
|
|
$payback = $this->matchingReferral($order);
|
|
$gateway = $this->gatewayClient($settings)->refund($tradeNo, $orderNo, $amount);
|
|
$gatewaySucceeded = true;
|
|
$now = time();
|
|
$referralAmount = '0.00';
|
|
|
|
$user->money = round((float) $user->money - (float) $amount, 2);
|
|
$user->save();
|
|
$paylist->status = 2;
|
|
$paylist->save();
|
|
|
|
if ($payback !== null) {
|
|
$referralAmount = PaymentAmount::normalize($payback->ref_get);
|
|
$referrer = User::where('id', (int) $payback->ref_by)->lockForUpdate()->first();
|
|
if ($referrer !== null) {
|
|
$referrer->aff_money = round((float) $referrer->aff_money - (float) $referralAmount, 2);
|
|
$referrer->save();
|
|
|
|
$reversal = new Payback();
|
|
$reversal->total = 0 - (float) PaymentAmount::normalize($payback->total);
|
|
$reversal->userid = (int) $payback->userid;
|
|
$reversal->ref_by = (int) $payback->ref_by;
|
|
$reversal->ref_get = 0 - (float) $referralAmount;
|
|
$reversal->datetime = $now;
|
|
$reversal->save();
|
|
}
|
|
}
|
|
|
|
$ledger = new Code();
|
|
$ledger->code = 'YPR-' . $orderNo;
|
|
$ledger->isused = 1;
|
|
$ledger->type = -2;
|
|
$ledger->number = $amount;
|
|
$ledger->usedatetime = date('Y-m-d H:i:s', $now);
|
|
$ledger->userid = (int) $user->id;
|
|
$ledger->save();
|
|
|
|
$refund = new YipayRefund();
|
|
$refund->order_no = $orderNo;
|
|
$refund->gateway_trade_no = $tradeNo;
|
|
$refund->amount = $amount;
|
|
$refund->status = 'success';
|
|
$refund->gateway_message = mb_substr(trim((string) ($gateway['msg'] ?? '退款成功')), 0, 500);
|
|
$refund->admin_user_id = $adminUserId;
|
|
$refund->referral_reversal_amount = $referralAmount;
|
|
$refund->requested_at = $now;
|
|
$refund->completed_at = $now;
|
|
$refund->updated_at = $now;
|
|
$refund->save();
|
|
|
|
$order->status = 'refunded';
|
|
$order->error_message = '';
|
|
$order->updated_at = $now;
|
|
$order->save();
|
|
|
|
$result = [
|
|
'order_no' => $orderNo,
|
|
'amount' => $amount,
|
|
'referral_reversal_amount' => $referralAmount,
|
|
];
|
|
}, 1);
|
|
} catch (\Throwable $exception) {
|
|
if ($gatewaySucceeded) {
|
|
error_log('CRITICAL: Yipay gateway refund succeeded but local transaction failed for ' . $orderNo . ': ' . $exception->getMessage());
|
|
throw new \RuntimeException('易支付已接受退款,但本地记账失败,请立即人工核对订单 ' . $orderNo);
|
|
}
|
|
throw $exception;
|
|
}
|
|
|
|
return $result;
|
|
}
|
|
|
|
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->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);
|
|
}
|
|
|
|
private function matchingReferral(YipayOrder $order)
|
|
{
|
|
if ((int) $order->paid_at <= 0) {
|
|
return null;
|
|
}
|
|
$query = Payback::where('userid', (int) $order->user_id)
|
|
->where('total', PaymentAmount::normalize($order->amount))
|
|
->where('ref_get', '>=', 0)
|
|
->whereBetween('datetime', [(int) $order->paid_at - 2, (int) $order->paid_at + 2])
|
|
->lockForUpdate();
|
|
$matches = $query->orderBy('id', 'desc')->get();
|
|
if ($matches->count() <= 1) {
|
|
return $matches->first();
|
|
}
|
|
$exact = $matches->filter(function ($payback) use ($order) {
|
|
return (int) $payback->datetime === (int) $order->paid_at;
|
|
});
|
|
if ($exact->count() === 1) {
|
|
return $exact->first();
|
|
}
|
|
throw new \RuntimeException('订单对应的邀请返利记录无法唯一识别,已阻止自动退款');
|
|
}
|
|
}
|