feat(balance): 新增余额支付方式;fix(hosting_shop): 修复订单页表单渲染
6 个文件变更
+298
-9
13172193298@163.com
| •app_plugins/balance/bootstrap.php | +169 -2 |
| •app_plugins/balance/lib/balance.php | +84 -0 |
| •app_plugins/balance/plugin.json | +1 -1 |
| •app_plugins/hosting_shop/assets/style.css | +14 -0 |
| •app_plugins/hosting_shop/views/layout.php | +1 -0 |
| •app_plugins/hosting_shop/views/order.php | +29 -6 |
变更内容
diff --git a/app_plugins/balance/bootstrap.php b/app_plugins/balance/bootstrap.php
index ebddc55..846cb44 100644
--- a/app_plugins/balance/bootstrap.php
+++ b/app_plugins/balance/bootstrap.php
@@ -75,10 +75,16 @@ mnbt_register_route('GET', '/balance', function ($params, $ctx) {
mnbt_register_route('GET', '/balance/recharge', function ($params, $ctx) {
$user = balance_require_user();
- // 获取已启用的支付方式
+ // 获取已启用的支付方式,排除余额支付自身(充值不能用余额付,循环)
$methods = [];
if (function_exists('mnbt_get_enabled_payment_methods')) {
- $methods = mnbt_get_enabled_payment_methods();
+ $all = mnbt_get_enabled_payment_methods();
+ foreach ($all as $m) {
+ if (($m['plugin'] ?? '') === 'balance') {
+ continue;
+ }
+ $methods[] = $m;
+ }
}
balance_render('recharge', [
@@ -114,6 +120,11 @@ mnbt_register_route('POST', '/balance/api/create_recharge', function ($params, $
if ($type === '' || !function_exists('mnbt_pay_parse_type') || !mnbt_pay_parse_type($type)) {
balance_json('请选择有效的支付方式');
}
+ // 充值订单禁止使用余额支付(循环)
+ $parsed_type = mnbt_pay_parse_type($type);
+ if ($parsed_type && $parsed_type['plugin'] === 'balance') {
+ balance_json('充值订单不能使用余额支付');
+ }
// 创建订单(MN_dd 表)
$out_trade_no = date("YmdHis") . mt_rand(100, 999);
@@ -153,6 +164,162 @@ mnbt_register_route('POST', '/balance/api/create_recharge', function ($params, $
balance_json('正在跳转到支付页面', ['html' => $html]);
});
+/* ============================================================
+ * 余额支付(作为支付插件注册)
+ * ============================================================
+ * 把"余额扣款"做成标准支付方式(type = balance__balance),
+ * 供 hosting_shop 等业务插件在下单页直接选用。
+ *
+ * 流程:
+ * 1. 业务插件创建 MN_dd 订单 → mnbt_pay_dispatch_gateway('balance__balance', ...)
+ * 2. 本插件 build 回调预检(登录、余额、非充值单)后返回自动提交表单
+ * 3. 表单 POST 到 /pay/balance/pay → 校验订单归属 → 原子扣款 → mnbt_pay_settle_order()
+ * 4. 结算成功后 order.paid 钩子触发业务插件处理(如 hosting_shop 开通主机)
+ * 5. 展示支付结果页
+ */
+mnbt_register_payment('balance', [
+ 'name' => '余额支付',
+ 'description' => '使用账户余额直接付款(需先充值)',
+ 'icon' => 'mdi-wallet',
+ 'methods' => [
+ 'balance' => ['name' => '余额支付', 'icon' => 'mdi-cash'],
+ ],
+ 'build' => function ($method, $order, $plugin_config) {
+ // 1. 充值订单禁止使用余额支付(循环)
+ if (($order['pay_lx'] ?? '') === 'recharge') {
+ return balance_pay_render_error('充值订单不能使用余额支付');
+ }
+ // 2. 依赖 user_info 插件
+ if (!function_exists('user_info_auth_current')) {
+ return balance_pay_render_error('需要先启用 user_info 插件');
+ }
+ $user = user_info_auth_current();
+ if (!$user) {
+ // 未登录 → 跳转登录页
+ $loginUrl = balance_url('account/login');
+ return '<!DOCTYPE html><html><head><meta charset="UTF-8"></head><body><script>window.location.href="' . $loginUrl . '";</script></body></html>';
+ }
+ // 3. 余额预检
+ $amount_cents = (int)round((float)($order['money'] ?? 0) * 100);
+ $balance = balance_get($user['id']);
+ if ($amount_cents <= 0) {
+ return balance_pay_render_error('订单金额异常');
+ }
+ if ($balance < $amount_cents) {
+ return balance_pay_render_error(
+ '余额不足,当前余额 ¥' . balance_format($balance) . ',本次需支付 ¥' . balance_format($amount_cents),
+ balance_url('balance/recharge')
+ );
+ }
+ // 4. 构造自动提交表单 → /pay/balance/pay
+ $outTradeNo = htmlspecialchars($order['out_trade_no'], ENT_QUOTES, 'UTF-8');
+ $payUrl = balance_url('pay/balance/pay');
+ return <<<HTML
+<!DOCTYPE html>
+<html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>余额支付</title></head>
+<body style="font-family:sans-serif;text-align:center;padding:60px;background:#f5f7fa;">
+<p style="color:#475569;">正在使用余额支付,请稍候...</p>
+<form id="payform" method="POST" action="{$payUrl}">
+<input type="hidden" name="out_trade_no" value="{$outTradeNo}">
+<noscript><button type="submit">点击继续</button></noscript>
+</form>
+<script>document.getElementById('payform').submit();</script>
+</body></html>
+HTML;
+ },
+]);
+
+/* 余额支付处理路由:原子扣款 + 统一结算 */
+mnbt_register_route('POST', '/pay/balance/pay', function ($params, $ctx) {
+ global $DB;
+
+ // 1. 登录校验
+ if (!function_exists('user_info_auth_current')) {
+ balance_pay_show_result('error', '需要先启用 user_info 插件');
+ return;
+ }
+ $user = user_info_auth_current();
+ if (!$user) {
+ balance_pay_show_result('error', '请先登录', ['redirect' => balance_url('account/login'), 'redirect_text' => '去登录']);
+ return;
+ }
+
+ // 2. 取订单号并查单
+ $out_trade_no = isset($_POST['out_trade_no']) ? trim((string)$_POST['out_trade_no']) : '';
+ if ($out_trade_no === '') {
+ balance_pay_show_result('error', '订单号缺失');
+ return;
+ }
+ $order = $DB->get_row_prepare("SELECT * FROM MN_dd WHERE ddh=? LIMIT 1", [$out_trade_no]);
+ if (!$order) {
+ balance_pay_show_result('error', '订单不存在');
+ return;
+ }
+
+ // 3. 订单状态校验
+ if ((string)$order['qk'] === 'true') {
+ balance_pay_show_result('error', '订单已支付,无需重复付款');
+ return;
+ }
+
+ // 4. 支付方式校验:必须为 balance__balance,防止伪造请求用余额去结其他支付方式的单
+ $parsed = function_exists('mnbt_pay_parse_type') ? mnbt_pay_parse_type($order['zffs']) : false;
+ if (!$parsed || $parsed['plugin'] !== 'balance') {
+ balance_pay_show_result('error', '订单支付方式非余额支付');
+ return;
+ }
+
+ // 5. 订单归属校验:cs.user_id 必须等于当前用户 id
+ $cs = json_decode($order['cs'] ?? '', true);
+ if (!is_array($cs) || (int)($cs['user_id'] ?? 0) !== (int)$user['id']) {
+ balance_pay_show_result('error', '订单不属于当前用户');
+ return;
+ }
+
+ // 6. 充值单拒绝(双保险,build 已挡过一次)
+ if (($order['lx'] ?? '') === 'recharge') {
+ balance_pay_show_result('error', '充值订单不能使用余额支付');
+ return;
+ }
+
+ // 7. 原子扣款(WHERE balance >= ? 保证余额不足时失败)
+ $amount_cents = (int)round((float)$order['je'] * 100);
+ if ($amount_cents <= 0) {
+ balance_pay_show_result('error', '订单金额异常');
+ return;
+ }
+ $ok = balance_deduct(
+ $user['id'],
+ $amount_cents,
+ 'consume',
+ $out_trade_no,
+ '余额支付:' . ($order['lx'] ?? '')
+ );
+ if (!$ok) {
+ balance_pay_show_result(
+ 'error',
+ '余额不足,扣款失败',
+ ['redirect' => balance_url('balance/recharge'), 'redirect_text' => '去充值']
+ );
+ return;
+ }
+
+ // 8. 统一结算:标记订单完成 + 触发 order.paid 钩子(由业务插件处理后续业务)
+ $result = mnbt_pay_settle_order($out_trade_no, 'TRADE_SUCCESS', (string)$order['je']);
+ if (empty($result['ok'])) {
+ // 扣款成功但结算异常 → 记录日志并提示联系管理员(余额已扣,需人工处理)
+ @error_log('[balance] settle failed but deducted: order=' . $out_trade_no . ' user=' . $user['id'] . ' amount=' . $amount_cents . ' msg=' . ($result['msg'] ?? ''));
+ balance_pay_show_result('error', '扣款成功但订单结算异常,请联系管理员。订单号:' . $out_trade_no);
+ return;
+ }
+
+ // 9. 成功
+ balance_pay_show_result('success', '支付成功', [
+ 'order_no' => $out_trade_no,
+ 'amount' => (string)$order['je'],
+ ]);
+});
+
/* ============================================================
* 管理员端页面注册
* ============================================================ */
diff --git a/app_plugins/balance/lib/balance.php b/app_plugins/balance/lib/balance.php
index 73003b9..3b467ac 100644
--- a/app_plugins/balance/lib/balance.php
+++ b/app_plugins/balance/lib/balance.php
@@ -311,3 +311,87 @@ function balance_admin_logs($page = 1, $per_page = 30, $filters = [])
return ['list' => $list, 'total' => $total, 'page' => $page, 'per_page' => $per_page];
}
+
+/* ============================================================
+ * 余额支付(作为支付插件)
+ * ============================================================ */
+
+/**
+ * 渲染余额支付错误页(用于 build 回调返回的 HTML 字符串)。
+ *
+ * @param string $msg 错误信息
+ * @param string $rechargeUrl 可选,"去充值"按钮链接
+ * @return string 完整 HTML 文档
+ */
+function balance_pay_render_error($msg, $rechargeUrl = '')
+{
+ $msgEsc = htmlspecialchars($msg, ENT_QUOTES, 'UTF-8');
+ $rechargeLink = '';
+ if ($rechargeUrl) {
+ $u = htmlspecialchars($rechargeUrl, ENT_QUOTES, 'UTF-8');
+ $rechargeLink = '<a href="' . $u . '" style="display:inline-block;padding:10px 24px;background:#1677ff;color:#fff;text-decoration:none;border-radius:8px;margin:8px;">去充值</a>';
+ }
+ $backUrl = balance_url('balance');
+ return <<<HTML
+<!DOCTYPE html>
+<html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>余额支付</title></head>
+<body style="font-family:-apple-system,BlinkMacSystemFont,'Segoe UI','PingFang SC','Microsoft YaHei',sans-serif;text-align:center;padding:60px 16px;background:#f5f7fa;color:#1e293b;">
+<div style="max-width:440px;margin:0 auto;background:#fff;border-radius:16px;padding:40px 32px;box-shadow:0 4px 24px rgba(15,23,42,.06);">
+<div style="width:64px;height:64px;border-radius:50%;background:#b91c1c15;color:#b91c1c;font-size:32px;line-height:64px;margin:0 auto 16px;">✕</div>
+<h1 style="font-size:22px;font-weight:600;margin:0 0 8px;color:#b91c1c;">余额支付失败</h1>
+<p style="color:#475569;margin:0 0 8px;">{$msgEsc}</p>
+<div style="margin-top:24px;">{$rechargeLink}<a href="{$backUrl}" style="display:inline-block;padding:10px 24px;background:#fff;color:#475569;text-decoration:none;border-radius:8px;margin:8px;border:1px solid #e2e8f0;">返回余额页</a></div>
+</div>
+</body></html>
+HTML;
+}
+
+/**
+ * 输出余额支付结果页并退出。
+ *
+ * @param string $type success / error
+ * @param string $msg 结果说明
+ * @param array $extra ['order_no'=>..., 'amount'=>..., 'redirect'=>..., 'redirect_text'=>...]
+ */
+function balance_pay_show_result($type, $msg, $extra = [])
+{
+ @header('Content-Type: text/html; charset=UTF-8');
+ $isSuccess = $type === 'success';
+ $title = $isSuccess ? '支付成功' : '支付失败';
+ $color = $isSuccess ? '#16a34a' : '#b91c1c';
+ $icon = $isSuccess ? '✓' : '✕';
+ $msgEsc = htmlspecialchars($msg, ENT_QUOTES, 'UTF-8');
+
+ $orderNo = isset($extra['order_no']) ? (string)$extra['order_no'] : '';
+ $amount = isset($extra['amount']) ? (string)$extra['amount'] : '';
+ $redirect = isset($extra['redirect']) ? (string)$extra['redirect'] : '';
+ $redirectText = isset($extra['redirect_text']) ? (string)$extra['redirect_text'] : '继续';
+
+ $orderLine = $orderNo ? '<div style="font-size:12px;color:#94a3b8;margin-top:12px;">订单号:' . htmlspecialchars($orderNo, ENT_QUOTES, 'UTF-8') . '</div>' : '';
+ $amountLine = $amount ? '<div style="font-size:14px;color:#475569;margin-top:8px;">支付金额:¥' . htmlspecialchars($amount, ENT_QUOTES, 'UTF-8') . '</div>' : '';
+
+ $links = '';
+ if ($redirect) {
+ $u = htmlspecialchars($redirect, ENT_QUOTES, 'UTF-8');
+ $t = htmlspecialchars($redirectText, ENT_QUOTES, 'UTF-8');
+ $links .= '<a href="' . $u . '" style="display:inline-block;padding:10px 24px;background:#1677ff;color:#fff;text-decoration:none;border-radius:8px;margin:8px;">' . $t . '</a>';
+ }
+ $backUrl = balance_url('balance');
+ $links .= '<a href="' . $backUrl . '" style="display:inline-block;padding:10px 24px;background:#fff;color:#475569;text-decoration:none;border-radius:8px;margin:8px;border:1px solid #e2e8f0;">返回余额页</a>';
+
+ echo <<<HTML
+<!DOCTYPE html>
+<html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>{$title}</title></head>
+<body style="font-family:-apple-system,BlinkMacSystemFont,'Segoe UI','PingFang SC','Microsoft YaHei',sans-serif;text-align:center;padding:60px 16px;background:#f5f7fa;color:#1e293b;">
+<div style="max-width:440px;margin:0 auto;background:#fff;border-radius:16px;padding:40px 32px;box-shadow:0 4px 24px rgba(15,23,42,.06);">
+<div style="width:64px;height:64px;border-radius:50%;background:{$color}15;color:{$color};font-size:32px;line-height:64px;margin:0 auto 16px;">{$icon}</div>
+<h1 style="font-size:22px;font-weight:600;margin:0 0 8px;color:{$color};">{$title}</h1>
+<p style="color:#475569;margin:0 0 8px;">{$msgEsc}</p>
+{$amountLine}
+{$orderLine}
+<div style="margin-top:24px;">{$links}</div>
+</div>
+</body></html>
+HTML;
+ exit;
+}
diff --git a/app_plugins/balance/plugin.json b/app_plugins/balance/plugin.json
index 425f31c..b74045f 100644
--- a/app_plugins/balance/plugin.json
+++ b/app_plugins/balance/plugin.json
@@ -3,7 +3,7 @@
"name": "余额管理",
"version": "1.0.0",
"author": "MNBT",
- "description": "用户余额系统:余额查询、充值(调用支付插件 API)、消费、流水记录。依赖 user_info 插件。",
+ "description": "用户余额系统:余额查询、充值(调用支付插件 API)、消费、流水记录。同时可作为支付插件,在下单页使用余额直接付款。依赖 user_info 插件。",
"requires_mnbt": "1.81",
"requires_plugins": ["user_info"],
"type": ["business"]
diff --git a/app_plugins/hosting_shop/assets/style.css b/app_plugins/hosting_shop/assets/style.css
index 7d39ebc..39363f7 100644
--- a/app_plugins/hosting_shop/assets/style.css
+++ b/app_plugins/hosting_shop/assets/style.css
@@ -48,3 +48,17 @@
.ly-pager a:hover{border-color:#1e9fff;background:#f0f8ff;}
.ly-pager-info{color:#888;}
@media(max-width:600px){.hs-plan-grid{grid-template-columns:1fr;}}
+
+/* 订单页原生表单样式(不依赖 layui.form.render) */
+.hs-order-form .layui-form-label{width:90px;padding:9px 10px;text-align:right;box-sizing:border-box;}
+.hs-order-form .layui-input-block{margin-left:110px;min-height:36px;line-height:36px;}
+.hs-form-choices{display:flex;flex-wrap:wrap;gap:10px;align-items:center;}
+.hs-choice{display:inline-flex;align-items:center;gap:6px;padding:6px 12px;background:#f7f9fa;border:1px solid #e4e7ed;border-radius:6px;cursor:pointer;font-size:14px;color:#333;transition:border-color .15s,background .15s;}
+.hs-choice:hover{border-color:#1e9fff;background:#f0f8ff;}
+.hs-choice input[type="radio"]{margin:0;cursor:pointer;}
+.hs-choice.active{border-color:#1e9fff;background:#e6f4ff;color:#1e9fff;}
+@media(max-width:600px){
+ .hs-order-form .layui-form-label{width:auto;display:block;text-align:left;padding-left:0;}
+ .hs-order-form .layui-input-block{margin-left:0;}
+ .hs-form-choices{gap:8px;}
+}
diff --git a/app_plugins/hosting_shop/views/layout.php b/app_plugins/hosting_shop/views/layout.php
index caa4b3f..d80215a 100644
--- a/app_plugins/hosting_shop/views/layout.php
+++ b/app_plugins/hosting_shop/views/layout.php
@@ -39,5 +39,6 @@ $content = $content ?? '';
<div class="ly-page-wide"><?= $content ?></div>
+<script src="https://unpkg.com/layui@2.9.8/dist/layui.js"></script>
</body>
</html>
diff --git a/app_plugins/hosting_shop/views/order.php b/app_plugins/hosting_shop/views/order.php
index fff1e82..f5eb100 100644
--- a/app_plugins/hosting_shop/views/order.php
+++ b/app_plugins/hosting_shop/views/order.php
@@ -21,15 +21,18 @@ ob_start();
<li><span>域名绑定</span><b><?= (int)$plan['spec_domain'] ?> 个</b></li>
</ul>
- <form class="layui-form" id="orderForm">
+ <form class="hs-order-form" id="orderForm">
<div class="layui-form-item">
<label class="layui-form-label">购买周期</label>
- <div class="layui-input-block" style="padding-top:8px;">
+ <div class="layui-input-block hs-form-choices" style="padding-top:8px;">
<?php if ((int)$plan['price_month_cents'] > 0): ?>
- <input type="radio" name="period" value="month" title="月付 ¥<?= hosting_format_cents($plan['price_month_cents']) ?>" <?= (int)$plan['price_year_cents']<=0?'checked':'') ?>>
+ <label class="hs-choice"><input type="radio" name="period" value="month" <?= (int)$plan['price_year_cents']<=0?'checked':'' ?>> 月付 ¥<?= hosting_format_cents($plan['price_month_cents']) ?></label>
<?php endif; ?>
<?php if ((int)$plan['price_year_cents'] > 0): ?>
- <input type="radio" name="period" value="year" title="年付 ¥<?= hosting_format_cents($plan['price_year_cents']) ?>" <?= (int)$plan['price_month_cents']<=0?'checked':'') ?>>
+ <label class="hs-choice"><input type="radio" name="period" value="year" <?= (int)$plan['price_month_cents']<=0?'checked':'' ?>> 年付 ¥<?= hosting_format_cents($plan['price_year_cents']) ?></label>
+ <?php endif; ?>
+ <?php if ((int)$plan['price_month_cents'] <= 0 && (int)$plan['price_year_cents'] <= 0): ?>
+ <span style="color:#999;">该套餐未设置价格</span>
<?php endif; ?>
</div>
</div>
@@ -53,9 +56,9 @@ ob_start();
<?php if (!empty($methods)): ?>
<div class="layui-form-item">
<label class="layui-form-label">支付方式</label>
- <div class="layui-input-block" style="padding-top:6px;">
+ <div class="layui-input-block hs-form-choices" style="padding-top:6px;">
<?php foreach ($methods as $m): ?>
- <input type="radio" name="type" value="<?= htmlspecialchars($m['plugin'].'__'.$m['method']) ?>" title="<?= htmlspecialchars($m['display_name'] ?: ($m['plugin'].' / '.$m['method'])) ?>" required>
+ <label class="hs-choice"><input type="radio" name="type" value="<?= htmlspecialchars($m['plugin'].'__'.$m['method']) ?>" required> <?= htmlspecialchars($m['display_name'] ?: ($m['plugin'].' / '.$m['method'])) ?></label>
<?php endforeach; ?>
</div>
</div>
@@ -76,9 +79,29 @@ ob_start();
<script>
(function(){
+ // 确保单选框有默认选中项(layui 不渲染原生表单时也生效)
+ var periodRadios = document.querySelectorAll('input[name="period"]');
+ if (periodRadios.length && !document.querySelector('input[name="period"]:checked')) {
+ periodRadios[0].checked = true;
+ }
+ var typeRadios = document.querySelectorAll('input[name="type"]');
+ if (typeRadios.length && !document.querySelector('input[name="type"]:checked')) {
+ typeRadios[0].checked = true;
+ }
+
var form=document.getElementById('orderForm');if(!form)return;
var msg=document.getElementById('msg'),btn=document.getElementById('submitBtn');
function showMsg(text,type){msg.textContent=text;msg.className='ly-msg show '+(type==='success'?'ly-msg-success':'ly-msg-error');}
+ // 单选框选中态样式(兼容不支持 :has() 的浏览器)
+ function updateChoiceStyles(){
+ form.querySelectorAll('.hs-choice').forEach(function(l){l.classList.remove('active');});
+ form.querySelectorAll('input[type="radio"]:checked').forEach(function(r){
+ var p=r.closest('.hs-choice');if(p)p.classList.add('active');
+ });
+ }
+ form.addEventListener('change',updateChoiceStyles);
+ updateChoiceStyles();
+
form.addEventListener('submit',function(e){
e.preventDefault();if(!btn)return;btn.disabled=true;btn.textContent='正在创建订单...';msg.className='ly-msg';
var body=new URLSearchParams();