From 5dd04b2f24a22d968856ecc90fa6d049c21dea15 Mon Sep 17 00:00:00 2001 From: MiAn Date: Thu, 19 Nov 2026 16:22:14 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=96=B0=E5=A2=9E=E5=90=8E=E5=8F=B0?= =?UTF-8?q?=E4=BA=BA=E5=B7=A5=E5=85=85=E5=80=BC=E5=8A=9F=E8=83=BD=E5=8F=8A?= =?UTF-8?q?=E6=94=AF=E4=BB=98=E7=BB=93=E6=9E=9C=E9=A1=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增后台人工充值模块,支持上传支付凭证 - 新增支付结果查询接口及页面 - 新增订单支付成功跳转结果页逻辑 - 更新钱包流水类型标签区分充值方式 - 新增插件路由 PHP 8 兼容错误报告设置 --- db/schema_admin_user_recharge.sql | 16 +++ server/addons/cos/controller/Index.php | 3 + .../admin/controller/WalletLog.php | 2 + .../admin/controller/user/User.php | 29 +++++ server/application/admin/model/WalletLog.php | 2 +- .../admin/view/user/user/detail.html | 4 +- .../admin/view/user/user/index.html | 1 + .../admin/view/user/user/recharge.html | 18 +++ .../admin/view/wallet_log/detail.html | 5 +- server/application/api/controller/Order.php | 14 +++ server/application/api/controller/User.php | 23 ++-- .../common/library/AdminRechargeService.php | 53 +++++++++ .../library/OrderPaymentResultService.php | 40 +++++++ server/application/extra/site.php | 2 +- server/application/extra/upload.php | 1 + server/public/assets/js/backend/user/user.js | 12 ++ tests/admin_recharge_test.php | 35 ++++++ tests/order_payment_result_test.php | 36 ++++++ tests/wallet_bills_api_test.js | 38 +++++++ yjyf-app/components/user/UserOrdersView.vue | 7 +- yjyf-app/pages.json | 4 + yjyf-app/pages/order/create.vue | 10 +- yjyf-app/pages/order/detail.vue | 22 ++-- yjyf-app/pages/order/payment-success.vue | 106 ++++++++++++++++++ yjyf-app/pages/order/quick.vue | 14 +-- .../static/icons/order-payment-success.svg | 1 + yjyf-app/utils/api.js | 1 + yjyf-app/utils/pay.js | 13 ++- 28 files changed, 468 insertions(+), 44 deletions(-) create mode 100644 db/schema_admin_user_recharge.sql create mode 100644 server/application/admin/view/user/user/recharge.html create mode 100644 server/application/common/library/AdminRechargeService.php create mode 100644 server/application/common/library/OrderPaymentResultService.php create mode 100644 tests/admin_recharge_test.php create mode 100644 tests/order_payment_result_test.php create mode 100644 tests/wallet_bills_api_test.js create mode 100644 yjyf-app/pages/order/payment-success.vue create mode 100644 yjyf-app/static/icons/order-payment-success.svg diff --git a/db/schema_admin_user_recharge.sql b/db/schema_admin_user_recharge.sql new file mode 100644 index 0000000..ead84ae --- /dev/null +++ b/db/schema_admin_user_recharge.sql @@ -0,0 +1,16 @@ +-- 后台人工充值凭证及独立操作权限。先部署此脚本,再部署代码。 +CREATE TABLE IF NOT EXISTS `fa_admin_recharge` ( + `id` int unsigned NOT NULL AUTO_INCREMENT, + `wallet_log_id` int unsigned NOT NULL, + `admin_id` int unsigned NOT NULL, + `voucher` varchar(255) NOT NULL, + `request_id` char(32) NOT NULL, + `createtime` bigint DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `uk_wallet_log` (`wallet_log_id`), + UNIQUE KEY `uk_request_id` (`request_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='后台人工充值凭证'; + +INSERT INTO `fa_auth_rule` (`type`,`pid`,`name`,`title`,`icon`,`ismenu`,`createtime`,`updatetime`,`weigh`,`status`) +SELECT 'file', `id`, 'user/user/recharge', '用户余额充值', 'fa fa-circle-o', 0, UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), 0, 'normal' +FROM `fa_auth_rule` WHERE `name` = 'user/user' AND NOT EXISTS (SELECT 1 FROM (SELECT `name` FROM `fa_auth_rule`) existing WHERE existing.`name` = 'user/user/recharge'); diff --git a/server/addons/cos/controller/Index.php b/server/addons/cos/controller/Index.php index a0c7650..2d9b836 100644 --- a/server/addons/cos/controller/Index.php +++ b/server/addons/cos/controller/Index.php @@ -21,6 +21,9 @@ class Index extends Controller public function _initialize() { + // 插件路由不经过后台模块的 PHP 8 兼容设置;保留真实错误,避免 SDK 弃用提示中断上传。 + error_reporting(E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED & ~E_NOTICE); + //跨域检测 check_cors_request(); diff --git a/server/application/admin/controller/WalletLog.php b/server/application/admin/controller/WalletLog.php index 153160c..a35c195 100644 --- a/server/application/admin/controller/WalletLog.php +++ b/server/application/admin/controller/WalletLog.php @@ -134,12 +134,14 @@ class WalletLog extends Backend $order = (int)$row['order_id'] > 0 ? Db::name('order')->where('id', (int)$row['order_id'])->find() : null; $settle = (int)$row['order_id'] > 0 ? Db::name('settle')->where('order_id', (int)$row['order_id'])->find() : null; + $recharge = Db::name('admin_recharge')->alias('r')->join('admin a', 'a.id = r.admin_id', 'LEFT')->where('r.wallet_log_id', (int)$row['id'])->field('r.*, a.username as admin_name')->find(); $this->view->assign([ 'row' => $row, 'owner' => $owner, 'order' => $order ?: [], 'settle' => $settle ?: [], + 'recharge' => $recharge ?: [], ]); return $this->view->fetch(); } diff --git a/server/application/admin/controller/user/User.php b/server/application/admin/controller/user/User.php index e7be0b1..c145df7 100755 --- a/server/application/admin/controller/user/User.php +++ b/server/application/admin/controller/user/User.php @@ -4,6 +4,7 @@ namespace app\admin\controller\user; use app\common\controller\Backend; use app\common\library\Auth; +use app\common\library\AdminRechargeService; use think\Db; /** @@ -189,6 +190,12 @@ class User extends Backend ->order('id desc') ->limit(6) ->select(); + $logIds = array_column($recentWalletLogs, 'id'); + $rechargeMap = $logIds ? Db::name('admin_recharge')->where('wallet_log_id', 'in', $logIds)->column('voucher', 'wallet_log_id') : []; + foreach ($recentWalletLogs as &$walletLog) { + $walletLog['voucher'] = $rechargeMap[$walletLog['id']] ?? ''; + } + unset($walletLog); $this->view->assign([ 'row' => $row, @@ -205,6 +212,28 @@ class User extends Backend return $this->view->fetch(); } + /** 后台凭支付凭证为用户充值。 */ + public function recharge($ids = null) + { + $row = $this->model->get($ids); + if (!$row) { + $this->error(__('No Results were found')); + } + if ($this->request->isPost()) { + $this->token(); + $params = $this->request->post('row/a', []); + try { + AdminRechargeService::credit((int)$row['id'], (int)$this->auth->id, $params['amount'] ?? '', $params['voucher'] ?? '', $params['request_id'] ?? ''); + } catch (\Throwable $e) { + $this->error($e instanceof \RuntimeException ? $e->getMessage() : '充值失败,请联系管理员检查服务日志'); + } + $this->success('充值成功'); + } + $this->view->assign('row', $row); + $this->view->assign('requestId', bin2hex(random_bytes(16))); + return $this->view->fetch(); + } + /** * 添加 */ diff --git a/server/application/admin/model/WalletLog.php b/server/application/admin/model/WalletLog.php index 626da51..197087c 100644 --- a/server/application/admin/model/WalletLog.php +++ b/server/application/admin/model/WalletLog.php @@ -24,7 +24,7 @@ class WalletLog extends Model public function getTypeList() { return [ - 'recharge' => '微信充值', + 'recharge' => '账户充值', 'consume' => '余额消费', 'refund' => '退回/退款', 'settle' => '佣金结算', diff --git a/server/application/admin/view/user/user/detail.html b/server/application/admin/view/user/user/detail.html index 08efa84..9544c33 100644 --- a/server/application/admin/view/user/user/detail.html +++ b/server/application/admin/view/user/user/detail.html @@ -151,7 +151,7 @@ #WL{$wl.id} - {if $wl.type=='recharge'}微信充值 + {if $wl.type=='recharge'}{if !empty($wl.voucher)}后台充值{else/}微信充值{/if} {elseif $wl.type=='consume'/}余额消费 {elseif $wl.type=='refund'/}原路退款 {else/}{$wl.type}{/if} @@ -161,7 +161,7 @@ ¥{:number_format($wl.balance, 2)} {if $wl.order_id > 0}#{$wl.order_id}{else/}-{/if} - {$wl.remark|htmlentities} + {$wl.remark|htmlentities} {if !empty($wl.voucher)}查看凭证{/if} {$wl.createtime|datetime} {/foreach} diff --git a/server/application/admin/view/user/user/index.html b/server/application/admin/view/user/user/index.html index 112e238..dbf9654 100755 --- a/server/application/admin/view/user/user/index.html +++ b/server/application/admin/view/user/user/index.html @@ -17,6 +17,7 @@ diff --git a/server/application/admin/view/user/user/recharge.html b/server/application/admin/view/user/user/recharge.html new file mode 100644 index 0000000..5d53ab1 --- /dev/null +++ b/server/application/admin/view/user/user/recharge.html @@ -0,0 +1,18 @@ + + {:token()} + +
+

用户余额充值

+
+

{$row.nickname|htmlentities}(ID:{$row.id},账号:{$row.username|htmlentities})

+

¥{$row.money|htmlentities}

+
+
+
+
    +

    请核实实际收款后上传凭证;提交成功后余额立即到账。

    +
    +
    + +
    + diff --git a/server/application/admin/view/wallet_log/detail.html b/server/application/admin/view/wallet_log/detail.html index f647dd8..4cd25ef 100644 --- a/server/application/admin/view/wallet_log/detail.html +++ b/server/application/admin/view/wallet_log/detail.html @@ -11,7 +11,7 @@
    资金流水审计凭证 #WL{$row.id} - {$typeList[$row.type]|default=$row.type} + {if !empty($recharge)}后台充值{else/}{$typeList[$row.type]|default=$row.type}{/if}
    @@ -33,6 +33,9 @@
    + {if !empty($recharge)} +
    后台充值支付凭证
    操作管理员:{$recharge.admin_name|default='已删除'|htmlentities}(ID:{$recharge.admin_id})
    查看支付凭证
    + {/if}
    变动账户主体信息
    diff --git a/server/application/api/controller/Order.php b/server/application/api/controller/Order.php index 91642c1..89b7013 100644 --- a/server/application/api/controller/Order.php +++ b/server/application/api/controller/Order.php @@ -6,6 +6,7 @@ use app\common\library\CommissionService; use app\common\library\FinanceConfigService; use app\common\library\OrderStatus; use app\common\library\OrderServiceSnapshot; +use app\common\library\OrderPaymentResultService; use app\common\library\PaymentService; use app\common\library\TiandituService; use think\Db; @@ -658,6 +659,19 @@ class Order extends Base $this->success($msg, $res); } + /** 查询已确认的单笔订单支付结果。 */ + public function paymentResult() + { + $order = $this->ownOrder((int)$this->request->get('order_id'), 'user'); + try { + $result = OrderPaymentResultService::getResult($order, $this->request->get('out_trade_no', '')); + } catch (\InvalidArgumentException $e) { + $this->error($e->getMessage()); + return; + } + $this->success('', $result); + } + /** * 小程序端完成 wx.requestPayment 后主动查单幂等核销(与异步回调双保险闭环) * @ApiMethod (POST) diff --git a/server/application/api/controller/User.php b/server/application/api/controller/User.php index aba6755..654b2a8 100755 --- a/server/application/api/controller/User.php +++ b/server/application/api/controller/User.php @@ -318,16 +318,19 @@ class User extends Api $page = max(1, (int)$this->request->get('page', 1)); $limit = min(50, max(1, (int)$this->request->get('limit', 20))); - $query = Db::name('wallet_log') - ->where('user_type', 'user') - ->where('user_id', $uid); + // count() 会清空查询条件,因此统计和列表必须分别创建查询。 + $makeQuery = function () use ($uid, $type) { + $query = Db::name('wallet_log') + ->where('user_type', 'user') + ->where('user_id', $uid); + if (in_array($type, ['recharge', 'consume', 'refund'], true)) { + $query->where('type', $type); + } + return $query; + }; - if (in_array($type, ['recharge', 'consume', 'refund'], true)) { - $query->where('type', $type); - } - - $total = $query->count(); - $rows = $query->order('id desc')->page($page, $limit)->select(); + $total = $makeQuery()->count(); + $rows = $makeQuery()->order('id desc')->page($page, $limit)->select(); $orderIds = []; foreach ($rows as $r) { @@ -350,7 +353,7 @@ class User extends Api $list[] = [ 'id' => (int)$r['id'], 'type' => $r['type'], - 'type_label' => $this->formatWalletTypeLabel($r['type']), + 'type_label' => $r['type'] === 'recharge' && $r['remark'] === '后台人工充值' ? '后台人工充值' : $this->formatWalletTypeLabel($r['type']), 'amount' => (float)$r['amount'], 'balance' => (float)$r['balance'], 'order_id' => $oid, diff --git a/server/application/common/library/AdminRechargeService.php b/server/application/common/library/AdminRechargeService.php new file mode 100644 index 0000000..83bba9f --- /dev/null +++ b/server/application/common/library/AdminRechargeService.php @@ -0,0 +1,53 @@ + 255 || !Db::name('attachment')->where('url', $voucher)->where('admin_id', (int)$adminId)->where('category', 'recharge')->where('mimetype', 'in', ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/bmp'])->find()) { + throw new \RuntimeException('请上传本次支付凭证图片'); + } + $amount = bcadd($amount, '0', 2); + Db::startTrans(); + try { + $user = Db::name('user')->where('id', (int)$userId)->lock(true)->find(); + if (!$user) { + throw new \RuntimeException('充值用户不存在'); + } + if (Db::name('admin_recharge')->where('request_id', $requestId)->find()) { + throw new \RuntimeException('该充值请求已提交,请勿重复充值'); + } + $balance = bcadd((string)$user['money'], $amount, 2); + if (bccomp($balance, '99999999.99', 2) > 0) { + throw new \RuntimeException('充值后余额超出允许范围'); + } + $now = time(); + Db::name('user')->where('id', (int)$userId)->update(['money' => $balance, 'updatetime' => $now]); + $logId = Db::name('wallet_log')->insertGetId([ + 'user_type' => 'user', 'user_id' => (int)$userId, 'type' => 'recharge', + 'amount' => $amount, 'balance' => $balance, 'order_id' => 0, + 'remark' => '后台人工充值', 'createtime' => $now, + ]); + Db::name('admin_recharge')->insert([ + 'wallet_log_id' => $logId, 'admin_id' => (int)$adminId, + 'voucher' => $voucher, 'request_id' => $requestId, 'createtime' => $now, + ]); + Db::commit(); + return ['wallet_log_id' => $logId, 'balance' => $balance]; + } catch (\Throwable $e) { + Db::rollback(); + throw $e; + } + } +} diff --git a/server/application/common/library/OrderPaymentResultService.php b/server/application/common/library/OrderPaymentResultService.php new file mode 100644 index 0000000..dac06a8 --- /dev/null +++ b/server/application/common/library/OrderPaymentResultService.php @@ -0,0 +1,40 @@ +where('order_id', (int)$order['id']) + ->where('out_trade_no', $outTradeNo)->where('status', 'paid') + ->where('scene', 'in', ['order', 'quote', 'diff'])->find(); + if (!$payment) { + throw new \InvalidArgumentException('未找到已确认的支付记录'); + } + return self::format($order, (string)$payment['amount'], $payment['openid'] === 'BALANCE' ? 'balance' : 'wechat', $payment['scene'], (int)$payment['pay_time']); + } + + private static function format(array $order, $amount, $payType, $scene, $payTime) + { + return [ + 'order_id' => (int)$order['id'], + 'order_no' => (string)$order['order_no'], + 'service_name' => (string)$order['service_name'], + 'amount' => number_format((float)$amount, 2, '.', ''), + 'pay_type' => $payType, + 'scene' => $scene, + 'pay_time' => $payTime, + ]; + } +} diff --git a/server/application/extra/site.php b/server/application/extra/site.php index 771a77e..b01d8f0 100755 --- a/server/application/extra/site.php +++ b/server/application/extra/site.php @@ -4,7 +4,7 @@ return array ( 'name' => '优匠优服', 'beian' => '', 'cdnurl' => '', - 'version' => '1.0.89', + 'version' => '1.0.90', 'timezone' => 'Asia/Shanghai', 'forbiddenip' => '', 'languages' => diff --git a/server/application/extra/upload.php b/server/application/extra/upload.php index 859cb4c..70f73f2 100755 --- a/server/application/extra/upload.php +++ b/server/application/extra/upload.php @@ -55,6 +55,7 @@ return [ 'category_map' => [ 'order' => 'user', // 订单相关凭证(用户端) 'cert' => 'user', // 入驻/资质证书(用户端) + 'recharge' => 'user', // 后台充值支付凭证 'dispute' => 'user', // 争议/投诉凭证(用户端) 'avatar' => 'user', // 头像(用户端与后台共用分类,后台无token自动落公共目录) 'icon' => 'common', // 图标(后台) diff --git a/server/public/assets/js/backend/user/user.js b/server/public/assets/js/backend/user/user.js index 7ae7d63..eedfeff 100644 --- a/server/public/assets/js/backend/user/user.js +++ b/server/public/assets/js/backend/user/user.js @@ -19,6 +19,7 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'backend/admin-table-layout', table.on('post-body.bs.table', function () { $(".btn-detail-usr", this).data("area", ["1020px", "86%"]); $(".btn-editone", this).data("area", ["820px", "78%"]); + $(".btn-recharge-usr", this).data("area", ["650px", "620px"]); }); $(".btn-edit").data("area", ["820px", "78%"]); @@ -88,6 +89,14 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'backend/admin-table-layout', events: Table.api.events.operate, formatter: Table.api.formatter.operate, buttons: [ + { + name: 'recharge', + text: '充值', + title: '用户余额充值', + classname: 'btn btn-xs btn-success btn-dialog btn-recharge-usr', + url: 'user/user/recharge', + visible: function () { return !!table.data('operate-recharge'); } + }, { name: 'detail', text: '详情', @@ -114,6 +123,9 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'backend/admin-table-layout', }, detail: function () { }, + recharge: function () { + Controller.api.bindevent(); + }, api: { bindevent: function () { Form.api.bindevent($("form[role=form]")); diff --git a/tests/admin_recharge_test.php b/tests/admin_recharge_test.php new file mode 100644 index 0000000..97018b9 --- /dev/null +++ b/tests/admin_recharge_test.php @@ -0,0 +1,35 @@ +insertGetId(['username' => 'recharge_test_' . time(), 'money' => '10.10']); + $url = '/uploads/test-recharge-' . time() . '.png'; + Db::name('attachment')->insert(['admin_id' => 1, 'url' => $url, 'category' => 'recharge', 'mimetype' => 'image/png']); + $nonce = bin2hex(random_bytes(16)); + rejected(function () use ($uid, $nonce) { AdminRechargeService::credit($uid, 1, '2.00', '', $nonce); }, 'Missing receipt accepted'); + rejected(function () use ($uid, $url, $nonce) { AdminRechargeService::credit($uid, 1, '0.001', $url, $nonce); }, 'Invalid amount accepted'); + rejected(function () use ($uid, $url, $nonce) { AdminRechargeService::credit($uid, 1, '0', $url, $nonce); }, 'Zero amount accepted'); + rejected(function () use ($uid, $url, $nonce) { AdminRechargeService::credit($uid, 1, '99999999.99', $url, $nonce); }, 'Balance overflow accepted'); + rejected(function () use ($uid, $url, $nonce) { AdminRechargeService::credit($uid, 2, '2.00', $url, $nonce); }, 'Another administrator receipt accepted'); + $result = AdminRechargeService::credit($uid, 1, '2.20', $url, $nonce); + check($result['balance'] === '12.30', 'Balance incorrect'); + check(Db::name('user')->where('id', $uid)->value('money') === '12.30', 'User balance not saved'); + $log = Db::name('wallet_log')->where('id', $result['wallet_log_id'])->find(); + check($log && $log['type'] === 'recharge' && $log['amount'] === '2.20' && $log['balance'] === '12.30', 'Wallet log incorrect'); + $audit = Db::name('admin_recharge')->where('wallet_log_id', $result['wallet_log_id'])->find(); + check($audit && $audit['voucher'] === $url && (int)$audit['admin_id'] === 1, 'Receipt or operator not saved'); + rejected(function () use ($uid, $url, $nonce) { AdminRechargeService::credit($uid, 1, '2.20', $url, $nonce); }, 'Duplicate request accepted'); + check(Db::name('user')->where('id', $uid)->value('money') === '12.30', 'Duplicate changed balance'); + echo "Admin recharge integration checks passed\n"; +} finally { + Db::rollback(); +} diff --git a/tests/order_payment_result_test.php b/tests/order_payment_result_test.php new file mode 100644 index 0000000..14f9d34 --- /dev/null +++ b/tests/order_payment_result_test.php @@ -0,0 +1,36 @@ + 2147483000, 'order_no' => 'RESULT-TEST', 'service_name' => '测试服务', 'pay_status' => 1, 'pay_type' => 'balance', 'pay_amount' => '120.00', 'pay_time' => time()]; + $trade = 'RESULT' . bin2hex(random_bytes(10)); + Db::name('pay_order')->insert(['out_trade_no' => $trade, 'order_id' => $order['id'], 'order_no' => $order['order_no'], 'user_id' => 1, 'scene' => 'diff', 'openid' => 'BALANCE', 'amount' => '12.34', 'status' => 'paid', 'pay_time' => time()]); + $result = OrderPaymentResultService::getResult($order, $trade); + verifyResult($result['amount'] === '12.34' && $result['pay_type'] === 'balance' && $result['scene'] === 'diff', 'Must use the actual payment transaction'); + Db::name('pay_order')->where('out_trade_no', $trade)->update(['openid' => 'WX_TEST_OPENID', 'scene' => 'quote']); + $wechat = OrderPaymentResultService::getResult($order, $trade); + verifyResult($wechat['pay_type'] === 'wechat' && $wechat['scene'] === 'quote' && $wechat['amount'] === '12.34', 'WeChat payment result incorrect'); + mustReject(function () use ($order, $trade) { $other = $order; $other['id']--; OrderPaymentResultService::getResult($other, $trade); }, 'Another order transaction accepted'); + Db::name('pay_order')->where('out_trade_no', $trade)->update(['status' => 'pending']); + mustReject(function () use ($order, $trade) { OrderPaymentResultService::getResult($order, $trade); }, 'Unpaid transaction accepted'); + Db::name('pay_order')->where('out_trade_no', $trade)->update(['status' => 'refunded']); + mustReject(function () use ($order, $trade) { OrderPaymentResultService::getResult($order, $trade); }, 'Refunded transaction shown as successful'); + mustReject(function () use ($order) { OrderPaymentResultService::getResult($order, ''); }, 'Missing transaction accepted for nonzero payment'); + $order['pay_type'] = 'coupon'; $order['pay_amount'] = '0.00'; + $zero = OrderPaymentResultService::getResult($order, ''); + verifyResult($zero['amount'] === '0.00' && $zero['pay_type'] === 'coupon', 'Zero payment not recognized'); + $order['pay_status'] = 0; + mustReject(function () use ($order) { OrderPaymentResultService::getResult($order, ''); }, 'Unpaid zero order accepted'); + echo "Order payment result checks passed\n"; +} finally { + Db::rollback(); +} diff --git a/tests/wallet_bills_api_test.js b/tests/wallet_bills_api_test.js new file mode 100644 index 0000000..1e0cb9e --- /dev/null +++ b/tests/wallet_bills_api_test.js @@ -0,0 +1,38 @@ +const assert = require('assert'); +const { execFileSync } = require('child_process'); +const http = require('http'); +const mysql = process.env.MYSQL_BIN; +const base = process.env.API_BASE || 'http://yjyf:9560/api'; +function sql(query) { + return execFileSync(mysql, ['-h127.0.0.1', '-u' + process.env.DB_USER, '-D' + process.env.DB_NAME, '-N', '-B', '-e', query], { encoding: 'utf8' }).trim(); +} +function request(path, data, token) { + return new Promise((resolve, reject) => { + const body = data && new URLSearchParams(data).toString(); + const url = new URL(base + path); + const req = http.request(url, { method: body ? 'POST' : 'GET', headers: { ...(body ? {'content-type': 'application/x-www-form-urlencoded', 'content-length': Buffer.byteLength(body)} : {}), ...(token ? {token} : {}) } }, res => { + let text = ''; res.on('data', chunk => text += chunk); res.on('end', () => { try { resolve(JSON.parse(text)); } catch (e) { reject(e); } }); + }); + req.on('error', reject); if (body) req.write(body); req.end(); + }); +} +(async () => { + const login = await request('/auth/login', {mobile: process.env.TEST_MOBILE, password: process.env.TEST_PASSWORD}); + assert.strictEqual(login.code, 1, 'login failed'); + const {token, userinfo} = login.data; + const uid = Number(userinfo.id); + assert(Number.isInteger(uid) && uid > 0); + for (const type of ['all', 'recharge', 'consume', 'refund']) { + const filter = type === 'all' ? '' : ` AND type='${type}'`; + const expected = sql(`SELECT id FROM fa_wallet_log WHERE user_type='user' AND user_id=${uid}${filter} ORDER BY id DESC`); + const ids = expected ? expected.split(/\s+/).map(Number) : []; + for (const page of [1, 2]) { + const res = await request(`/user/walletLogs?type=${type}&page=${page}&limit=3`, null, token); + assert.strictEqual(res.code, 1, `${type} page ${page} request failed`); + assert.strictEqual(res.data.total, ids.length, `${type} total`); + assert.deepStrictEqual(res.data.list.map(row => row.id), ids.slice((page - 1) * 3, page * 3), `${type} page ${page} must contain only matching user records`); + assert.strictEqual(res.data.has_more, page * 3 < ids.length, `${type} has_more`); + } + } + console.log('Wallet bill user, type, count and pagination checks passed'); +})().catch(err => { console.error(err); process.exitCode = 1; }); diff --git a/yjyf-app/components/user/UserOrdersView.vue b/yjyf-app/components/user/UserOrdersView.vue index 17a8403..8f4aaab 100644 --- a/yjyf-app/components/user/UserOrdersView.vue +++ b/yjyf-app/components/user/UserOrdersView.vue @@ -269,7 +269,7 @@ import { ref, onMounted } from 'vue'; import { formatOrderServiceItems } from '@/utils/order-service-items.mjs'; import api from '@/utils/api.js'; - import { executeOrderWxPay } from '@/utils/pay.js'; + import { executeOrderWxPay, openOrderPaymentResult } from '@/utils/pay.js'; import { isLogin, toLogin } from '@/utils/request.js'; import { getNavBarMetrics } from '@/utils/system.js'; import YjyfNavBar from '@/components/YjyfNavBar.vue'; @@ -518,9 +518,8 @@ if (!o || actingOrderId.value) return; actingOrderId.value = o.id; try { - await executeOrderWxPay(api.orderPay, { order_id: o.id }); - uni.showToast({ title: '支付成功', icon: 'success' }); - await load(); + const payment = await executeOrderWxPay(api.orderPay, { order_id: o.id }); + openOrderPaymentResult(o.id, payment); } catch (e) { if (e && e.code === undefined && !e.handledToast && !e.unsupportedEnv && e.message) { uni.showToast({ title: e.message, icon: 'none' }); diff --git a/yjyf-app/pages.json b/yjyf-app/pages.json index f5eff09..f7458b0 100644 --- a/yjyf-app/pages.json +++ b/yjyf-app/pages.json @@ -74,6 +74,10 @@ "path": "pages/order/detail", "style": { "navigationStyle": "custom", "backgroundColor": "#F5F6F8" } }, + { + "path": "pages/order/payment-success", + "style": { "navigationStyle": "custom", "backgroundColor": "#F5F6F8" } + }, { "path": "pages/order/case", "style": { "navigationStyle": "custom", "backgroundColor": "#F5F6F8" } diff --git a/yjyf-app/pages/order/create.vue b/yjyf-app/pages/order/create.vue index 83067b3..db43cea 100644 --- a/yjyf-app/pages/order/create.vue +++ b/yjyf-app/pages/order/create.vue @@ -233,7 +233,7 @@ import { ref, reactive, watch, computed } from 'vue'; import { onLoad, onShow, onUnload } from '@dcloudio/uni-app'; import api from '@/utils/api.js'; - import { executeOrderWxPay } from '@/utils/pay.js'; + import { executeOrderWxPay, openOrderPaymentResult } from '@/utils/pay.js'; import { isLogin, toLogin } from '@/utils/request.js'; import RegionPickerDrawer from '@/components/RegionPickerDrawer.vue'; @@ -546,12 +546,8 @@ } catch (pe) {} // 一口价或自主定价调起支付 - await executeOrderWxPay(api.orderPay, { order_id: createdOrderId, pay_type: payType }); - uni.showToast({ title: '下单并支付成功' }); - setTimeout(() => { - submitting.value = false; - uni.redirectTo({ url: `/pages/order/detail?id=${createdOrderId}` }); - }, 600); + const payment = await executeOrderWxPay(api.orderPay, { order_id: createdOrderId, pay_type: payType }); + openOrderPaymentResult(createdOrderId, payment, true); } catch (e) { if (createdOrderId) { if (!e || !e.unsupportedEnv) { diff --git a/yjyf-app/pages/order/detail.vue b/yjyf-app/pages/order/detail.vue index f679cf3..eb4fd97 100644 --- a/yjyf-app/pages/order/detail.vue +++ b/yjyf-app/pages/order/detail.vue @@ -427,7 +427,7 @@ import YjyfNavBar from '@/components/YjyfNavBar.vue'; import YjyfServicePopup from '@/components/YjyfServicePopup.vue'; import api from '@/utils/api.js'; - import { executeOrderWxPay } from '@/utils/pay.js'; + import { executeOrderWxPay, openOrderPaymentResult } from '@/utils/pay.js'; const order = ref(null); const loading = ref(true); @@ -636,9 +636,13 @@ return; } } - await executeOrderWxPay(api.orderChooseQuote, { order_id: orderId, quote_id: q.id, pay_type: payType }); - uni.showToast({ title: '已选定师傅' }); - await load(); + const payment = await executeOrderWxPay(api.orderChooseQuote, { order_id: orderId, quote_id: q.id, pay_type: payType }); + if (payment.out_trade_no) { + openOrderPaymentResult(orderId, payment, true); + } else { + uni.showToast({ title: '已选定师傅' }); + await load(); + } } catch (e) { if (e && e.code === undefined && !e.handledToast && !e.unsupportedEnv && e.message) { uni.showToast({ title: e.message, icon: 'none' }); @@ -665,9 +669,8 @@ actionBusy.value = false; return; } - await executeOrderWxPay(api.orderPayDiff, { order_id: orderId, pay_type: payType }); - uni.showToast({ title: '支付成功' }); - await load(); + const payment = await executeOrderWxPay(api.orderPayDiff, { order_id: orderId, pay_type: payType }); + openOrderPaymentResult(orderId, payment, true); } catch (e) { if (e && e.code === undefined && !e.handledToast && !e.unsupportedEnv && e.message) { uni.showToast({ title: e.message, icon: 'none' }); @@ -710,9 +713,8 @@ actionBusy.value = true; try { - await executeOrderWxPay(api.orderPay, { order_id: orderId, pay_type: payType }); - uni.showToast({ title: '支付成功', icon: 'success' }); - await load(); + const payment = await executeOrderWxPay(api.orderPay, { order_id: orderId, pay_type: payType }); + openOrderPaymentResult(orderId, payment, true); } catch (e) { if (e && e.code === undefined && !e.handledToast && !e.unsupportedEnv && e.message) { uni.showToast({ title: e.message, icon: 'none' }); diff --git a/yjyf-app/pages/order/payment-success.vue b/yjyf-app/pages/order/payment-success.vue new file mode 100644 index 0000000..e7ee9a2 --- /dev/null +++ b/yjyf-app/pages/order/payment-success.vue @@ -0,0 +1,106 @@ + + + + + diff --git a/yjyf-app/pages/order/quick.vue b/yjyf-app/pages/order/quick.vue index 6882546..1781222 100644 --- a/yjyf-app/pages/order/quick.vue +++ b/yjyf-app/pages/order/quick.vue @@ -1092,7 +1092,7 @@ import { ref, reactive, computed } from 'vue'; import { onLoad, onShow, onUnload } from '@dcloudio/uni-app'; import api from '@/utils/api.js'; - import { executeOrderWxPay } from '@/utils/pay.js'; + import { executeOrderWxPay, openOrderPaymentResult } from '@/utils/pay.js'; import { isLogin, toLogin } from '@/utils/request.js'; // 支付方式状态管理(优先默认勾选微信支付) @@ -2586,15 +2586,15 @@ createdOrderId = createRes.order_id; if (priceType.value === 'quote') { uni.showToast({ title: '报价单发布成功,等待师傅报价' }); + setTimeout(() => { + submitting.value = false; + uni.redirectTo({ url: `/pages/order/detail?id=${createdOrderId}` }); + }, 600); } else { const payType = (selectedPayType.value === 'balance' && isBalanceSufficient.value) ? 'balance' : 'wechat'; - await executeOrderWxPay(api.orderPay, { order_id: createdOrderId, pay_type: payType }); - uni.showToast({ title: payType === 'balance' ? '余额支付成功,正在匹配师傅' : '下单成功,正在匹配师傅' }); + const payment = await executeOrderWxPay(api.orderPay, { order_id: createdOrderId, pay_type: payType }); + openOrderPaymentResult(createdOrderId, payment, true); } - setTimeout(() => { - submitting.value = false; - uni.redirectTo({ url: `/pages/order/detail?id=${createdOrderId}` }); - }, 600); } catch (e) { if (createdOrderId) { if (!e || !e.unsupportedEnv) { diff --git a/yjyf-app/static/icons/order-payment-success.svg b/yjyf-app/static/icons/order-payment-success.svg new file mode 100644 index 0000000..2597a23 --- /dev/null +++ b/yjyf-app/static/icons/order-payment-success.svg @@ -0,0 +1 @@ + diff --git a/yjyf-app/utils/api.js b/yjyf-app/utils/api.js index 94cbe93..7596b99 100644 --- a/yjyf-app/utils/api.js +++ b/yjyf-app/utils/api.js @@ -50,6 +50,7 @@ export default { detectExpress: (data) => get('/order/detectExpress', data), orderPay: (data) => post('/order/pay', data), orderConfirmPay: (data) => post('/order/confirmPay', data, { silent: true, allowConcurrent: true }), + orderPaymentResult: (data) => get('/order/paymentResult', data, { silent: true }), orderCancel: (data) => post('/order/cancel', data), orderDelete: (data) => post('/order/delete', data), orderVerify: (data) => post('/order/verify', data), diff --git a/yjyf-app/utils/pay.js b/yjyf-app/utils/pay.js index 258cb88..7032e2f 100644 --- a/yjyf-app/utils/pay.js +++ b/yjyf-app/utils/pay.js @@ -160,7 +160,7 @@ export async function executeOrderWxPay(createPayApiFn, params = {}) { throw Object.assign(new Error(msg), { handledToast: true, unconfirmed: true, data: confirmRes }); } - return confirmRes; + return Object.assign({}, confirmRes, { out_trade_no: res.out_trade_no }); // #endif // #ifndef MP-WEIXIN @@ -174,6 +174,17 @@ export async function executeOrderWxPay(createPayApiFn, params = {}) { // #endif } +/** 支付确认后打开结果页,订单和支付详情由结果页重新向服务端核实。 */ +export function openOrderPaymentResult(orderId, result, replace = false) { + const url = `/pages/order/payment-success?order_id=${encodeURIComponent(orderId)}&out_trade_no=${encodeURIComponent((result && result.out_trade_no) || '')}`; + const options = { + url, + fail: () => uni.redirectTo({ url: `/pages/order/detail?id=${encodeURIComponent(orderId)}` }) + }; + if (replace) uni.redirectTo(options); + else uni.navigateTo(options); +} + /** * 师傅端调起微信官方「商家转账」确认收款页(wx.requestMerchantTransfer)并在返回后同步真实入账状态 *