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.
220 lines
11 KiB
PHP
220 lines
11 KiB
PHP
<?php
|
|
|
|
namespace App\Controllers\Admin;
|
|
|
|
use App\Controllers\AdminController;
|
|
use App\Models\YipayOrder;
|
|
use App\Models\YipayRefund;
|
|
use App\Services\AdminPermission;
|
|
use App\Services\AdminDataMasker;
|
|
use App\Services\Auth;
|
|
use App\Services\Payment\PaymentAmount;
|
|
use App\Services\Payment\YipayClient;
|
|
use App\Services\Payment\YipayConfig;
|
|
use App\Services\Payment\YipayPaymentService;
|
|
|
|
class YipayController extends AdminController
|
|
{
|
|
public function index($request, $response, $args)
|
|
{
|
|
$this->setViewTheme('venix');
|
|
$config = YipayConfig::values();
|
|
$browserConfig = $config;
|
|
foreach (['yipay_gateway_base_url', 'yipay_callback_base_url', 'yipay_pid'] as $protectedKey) {
|
|
$browserConfig[$protectedKey . '_configured'] = trim((string) ($config[$protectedKey] ?? '')) !== '';
|
|
$browserConfig[$protectedKey] = '';
|
|
}
|
|
$orders = null;
|
|
$summary = ['total' => 0, 'pending' => 0, 'paid' => 0, 'refunded' => 0, 'paid_amount' => '0.00'];
|
|
$tableError = '';
|
|
$refundAvailable = false;
|
|
$keyword = trim((string) $request->getParam('keyword', ''));
|
|
$status = trim((string) $request->getParam('status', ''));
|
|
$paymentType = trim((string) $request->getParam('payment_type', ''));
|
|
|
|
try {
|
|
$query = YipayOrder::query()
|
|
->leftJoin('user', 'user.id', '=', 'yipay_orders.user_id')
|
|
->select(
|
|
'yipay_orders.id',
|
|
'yipay_orders.user_id',
|
|
'yipay_orders.payment_type',
|
|
'yipay_orders.amount',
|
|
'yipay_orders.status',
|
|
'yipay_orders.created_at',
|
|
'user.email as user_email'
|
|
);
|
|
if ($keyword !== '') {
|
|
if (AdminPermission::isSuperAdmin()) {
|
|
$query->where(function ($builder) use ($keyword) {
|
|
$builder->where('user.email', 'like', '%' . $keyword . '%');
|
|
if (ctype_digit($keyword)) {
|
|
$builder->orWhere('yipay_orders.id', (int) $keyword)
|
|
->orWhere('yipay_orders.user_id', (int) $keyword);
|
|
}
|
|
});
|
|
} elseif (ctype_digit($keyword)) {
|
|
$query->where(function ($builder) use ($keyword) {
|
|
$builder->where('yipay_orders.id', (int) $keyword)
|
|
->orWhere('yipay_orders.user_id', (int) $keyword);
|
|
});
|
|
} else {
|
|
$query->whereRaw('1 = 0');
|
|
}
|
|
}
|
|
if (in_array($status, ['creating', 'pending', 'paid', 'refunded', 'failed'], true)) {
|
|
$query->where('yipay_orders.status', $status);
|
|
}
|
|
if (in_array($paymentType, ['alipay', 'wxpay'], true)) {
|
|
$query->where('yipay_orders.payment_type', $paymentType);
|
|
}
|
|
$orders = $query->orderBy('yipay_orders.id', 'desc')->paginate(30);
|
|
$orders->setPath('/admin/yipay');
|
|
$orders->appends(['keyword' => $keyword, 'status' => $status, 'payment_type' => $paymentType]);
|
|
foreach ($orders as $order) {
|
|
$order->setAttribute('user_email', AdminDataMasker::email($order->user_email));
|
|
}
|
|
|
|
$summary['total'] = YipayOrder::count();
|
|
$summary['pending'] = YipayOrder::whereIn('status', ['creating', 'pending'])->count();
|
|
$summary['paid'] = YipayOrder::whereIn('status', ['paid', 'refunded'])->count();
|
|
$summary['refunded'] = YipayOrder::where('status', 'refunded')->count();
|
|
$summary['paid_amount'] = PaymentAmount::normalize(YipayOrder::where('status', 'paid')->sum('amount'));
|
|
YipayRefund::count();
|
|
$refundAvailable = true;
|
|
} catch (\Throwable $exception) {
|
|
$tableError = '易支付订单或退款表不可用,请导入 sql/yipay_payment.sql 和 sql/yipay_refund.sql。';
|
|
}
|
|
|
|
return $this->view()
|
|
->assign('yipay_config', $browserConfig)
|
|
->assign('yipay_orders', $orders)
|
|
->assign('yipay_summary', $summary)
|
|
->assign('yipay_table_error', $tableError)
|
|
->assign('yipay_refund_available', $refundAvailable)
|
|
->assign('yipay_filters', ['keyword' => $keyword, 'status' => $status, 'payment_type' => $paymentType])
|
|
->display('admin/yipay/index.tpl');
|
|
}
|
|
|
|
public function save($request, $response, $args)
|
|
{
|
|
$payload = $request->getParsedBody();
|
|
$payload = is_array($payload) ? $payload : [];
|
|
try {
|
|
$current = YipayConfig::values();
|
|
$values = $this->validateConfig($payload, $current);
|
|
$secret = trim((string) ($payload['yipay_secret_key'] ?? ''));
|
|
if (strlen($secret) > 256) {
|
|
throw new \InvalidArgumentException('易支付商户密钥长度不能超过 256 个字符');
|
|
}
|
|
if ($values['yipay_enabled'] === 'true') {
|
|
if ($values['yipay_alipay_enabled'] !== 'true' && $values['yipay_wxpay_enabled'] !== 'true') {
|
|
throw new \InvalidArgumentException('启用易支付前至少选择一种支付方式');
|
|
}
|
|
if ($values['yipay_gateway_base_url'] === '' || $values['yipay_callback_base_url'] === '' || $values['yipay_pid'] === '') {
|
|
throw new \InvalidArgumentException('启用易支付前必须填写网关、回调地址和商户 PID');
|
|
}
|
|
if ($secret === '' && !$current['yipay_secret_configured']) {
|
|
throw new \InvalidArgumentException('启用易支付前必须填写商户密钥');
|
|
}
|
|
if ($secret === '' && $current['yipay_secret_configured']) {
|
|
YipayConfig::callbackCredentials();
|
|
}
|
|
}
|
|
YipayConfig::save($values, $secret);
|
|
return $this->json($response, 1, '易支付配置保存成功');
|
|
} catch (\Throwable $exception) {
|
|
error_log('Yipay config save failed: ' . $exception->getMessage());
|
|
return $this->json($response, 0, $exception->getMessage(), 422);
|
|
}
|
|
}
|
|
|
|
public function test($request, $response, $args)
|
|
{
|
|
try {
|
|
$settings = YipayConfig::runtime(false);
|
|
$data = (new YipayClient($settings))->queryMerchant();
|
|
if ((string) ($data['pid'] ?? '') !== (string) $settings['yipay_pid']) {
|
|
throw new \RuntimeException('网关返回的商户 PID 不匹配');
|
|
}
|
|
if ((int) ($data['active'] ?? 0) !== 1) {
|
|
throw new \RuntimeException('易支付商户当前未启用');
|
|
}
|
|
return $this->json($response, 1, '连接成功,易支付商户状态正常');
|
|
} catch (\Throwable $exception) {
|
|
error_log('Yipay connection test failed: ' . $exception->getMessage());
|
|
return $this->json($response, 0, '连接失败,请查看服务器日志', 502);
|
|
}
|
|
}
|
|
|
|
public function refund($request, $response, $args)
|
|
{
|
|
if (strtolower($request->getHeaderLine('X-Requested-With')) !== 'xmlhttprequest') {
|
|
return $this->json($response, 0, '退款请求来源无效', 403);
|
|
}
|
|
if ((string) $request->getParam('confirm', '') !== 'REFUND') {
|
|
return $this->json($response, 0, '请确认退款操作', 422);
|
|
}
|
|
try {
|
|
$admin = Auth::getUser();
|
|
$result = (new YipayPaymentService())->refundById($request->getParam('record_id'), (int) $admin->id);
|
|
return $this->json($response, 1, '退款成功,已退回 ¥' . $result['amount'] . ' 并同步扣回用户余额');
|
|
} catch (\InvalidArgumentException $exception) {
|
|
return $this->json($response, 0, $exception->getMessage(), 422);
|
|
} catch (\Throwable $exception) {
|
|
error_log('Yipay refund failed: ' . $exception->getMessage());
|
|
return $this->json($response, 0, '退款处理失败,请查看服务器日志', 409);
|
|
}
|
|
}
|
|
|
|
private function validateConfig(array $payload, array $current)
|
|
{
|
|
$gatewayUrl = rtrim(trim((string) ($payload['yipay_gateway_base_url'] ?? '')), '/');
|
|
$callbackUrl = rtrim(trim((string) ($payload['yipay_callback_base_url'] ?? '')), '/');
|
|
$gatewayUrl = $gatewayUrl === '' ? trim((string) ($current['yipay_gateway_base_url'] ?? '')) : $gatewayUrl;
|
|
$callbackUrl = $callbackUrl === '' ? trim((string) ($current['yipay_callback_base_url'] ?? '')) : $callbackUrl;
|
|
if ($gatewayUrl !== '' && !YipayConfig::isHttpsUrl($gatewayUrl)) {
|
|
throw new \InvalidArgumentException('易支付网关地址必须是无查询参数的 HTTPS 地址');
|
|
}
|
|
if ($callbackUrl !== '' && !YipayConfig::isHttpsUrl($callbackUrl)) {
|
|
throw new \InvalidArgumentException('易支付回调地址必须是无查询参数的 HTTPS 地址');
|
|
}
|
|
|
|
$pid = trim((string) ($payload['yipay_pid'] ?? ''));
|
|
$pid = $pid === '' ? trim((string) ($current['yipay_pid'] ?? '')) : $pid;
|
|
if ($pid !== '' && !preg_match('/^\d{1,20}$/', $pid)) {
|
|
throw new \InvalidArgumentException('易支付商户 PID 必须是数字');
|
|
}
|
|
$name = trim(preg_replace('/[\x00-\x1F\x7F]/', '', (string) ($payload['yipay_order_name'] ?? '账户余额充值')));
|
|
if ($name === '' || strlen($name) > 127) {
|
|
throw new \InvalidArgumentException('商品名称不能为空且不能超过 127 字节');
|
|
}
|
|
$minimum = PaymentAmount::normalize($payload['yipay_min_amount'] ?? '1.00');
|
|
$maximum = PaymentAmount::normalize($payload['yipay_max_amount'] ?? '10000.00');
|
|
if ((float) $minimum < 0.01 || (float) $maximum > 1000000 || (float) $minimum > (float) $maximum) {
|
|
throw new \InvalidArgumentException('易支付金额范围无效');
|
|
}
|
|
|
|
return [
|
|
'yipay_enabled' => YipayConfig::truthy($payload['yipay_enabled'] ?? 'false') ? 'true' : 'false',
|
|
'yipay_test_mode' => YipayConfig::truthy($payload['yipay_test_mode'] ?? 'false') ? 'true' : 'false',
|
|
'yipay_alipay_enabled' => YipayConfig::truthy($payload['yipay_alipay_enabled'] ?? 'false') ? 'true' : 'false',
|
|
'yipay_wxpay_enabled' => YipayConfig::truthy($payload['yipay_wxpay_enabled'] ?? 'false') ? 'true' : 'false',
|
|
'yipay_gateway_base_url' => $gatewayUrl,
|
|
'yipay_callback_base_url' => $callbackUrl,
|
|
'yipay_pid' => $pid,
|
|
'yipay_order_name' => $name,
|
|
'yipay_min_amount' => $minimum,
|
|
'yipay_max_amount' => $maximum,
|
|
'yipay_request_timeout_seconds' => (string) max(3, min(60, (int) ($payload['yipay_request_timeout_seconds'] ?? 15))),
|
|
];
|
|
}
|
|
|
|
private function json($response, $ret, $msg, $status = 200)
|
|
{
|
|
$response = $response->withStatus((int) $status)->withHeader('Content-Type', 'application/json; charset=utf-8');
|
|
$response->getBody()->write(json_encode(['ret' => (int) $ret, 'msg' => (string) $msg], JSON_UNESCAPED_UNICODE));
|
|
return $response;
|
|
}
|
|
}
|