在正式接入微信支付之前,可以先用 ThinkPHP 5.1 搭建一套“模拟微信小程序商城”后端,把商品下单、金额计算、库存预占、模拟支付、订单查询和退款流程完整跑通。这样既方便前后端联调,也能提前验证订单状态机和幂等逻辑。
说明:本文是本地开发与测试用的模拟支付流程,不会调用微信支付接口,也不会产生真实资金交易。正式上线时必须替换为微信支付 API v3,并实现签名、验签、通知解密和资金对账。
一、项目实现目标
本文完成以下功能:
- 微信小程序获取模拟登录令牌;
- 查询商品与 SKU 库存;
- 服务端重新计算订单金额;
- 创建订单并预占库存;
- 模拟微信支付成功、失败或取消;
- 支付成功后确认库存扣减;
- 查询订单列表和详情;
- 发起全额或部分退款;
- 模拟退款异步完成;
- 处理重复请求和异常补偿。
二、完整业务流程
小程序选择商品
↓
POST /api/mock/orders
↓
服务端查询商品价格、校验库存、创建订单、预占库存
↓
POST /api/mock/orders/{order_no}/pay
↓
生成模拟支付单,返回 mock_prepay_id
↓
小程序展示模拟收银台并确认支付
↓
POST /api/mock/payments/{pay_no}/complete
↓
服务端模拟支付回调,幂等更新为已支付
↓
POST /api/mock/orders/{order_no}/refunds
↓
创建模拟退款单
↓
POST /api/mock/refunds/{refund_no}/complete
↓
退款完成,更新订单和退款金额
三、目录结构
application/
├── api/
│ ├── controller/
│ │ ├── MockAuth.php
│ │ ├── Product.php
│ │ ├── Order.php
│ │ └── MockPayment.php
│ ├── model/
│ │ ├── Product.php
│ │ ├── ProductSku.php
│ │ ├── ShopOrder.php
│ │ ├── ShopOrderItem.php
│ │ ├── PaymentRecord.php
│ │ └── RefundRecord.php
│ └── service/
│ ├── OrderService.php
│ └── MockPayService.php
├── route.php
└── config.php
四、创建模拟商城数据表
-- 模拟用户表:保存小程序用户与 openid 的映射
CREATE TABLE mock_user (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
openid VARCHAR(64) NOT NULL,
nickname VARCHAR(100) NOT NULL DEFAULT '',
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uk_openid (openid)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 商品主表:只保存商品公共信息,价格和库存放在 SKU 表
CREATE TABLE mock_product (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(200) NOT NULL,
cover VARCHAR(500) NOT NULL DEFAULT '',
status TINYINT UNSIGNED NOT NULL DEFAULT 1,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id),
KEY idx_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 商品 SKU 表:同一商品可以有多个规格、价格和独立库存
CREATE TABLE mock_product_sku (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
product_id BIGINT UNSIGNED NOT NULL,
sku_name VARCHAR(100) NOT NULL,
price INT UNSIGNED NOT NULL COMMENT '售价,单位分',
stock INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '可用库存',
locked_stock INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '预占库存',
sales INT UNSIGNED NOT NULL DEFAULT 0,
status TINYINT UNSIGNED NOT NULL DEFAULT 1,
version INT UNSIGNED NOT NULL DEFAULT 0,
PRIMARY KEY (id),
KEY idx_product_id (product_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 订单主表:保存订单总金额、支付状态及累计退款金额
CREATE TABLE mock_order (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
order_no VARCHAR(32) NOT NULL COMMENT '服务端生成的唯一订单号',
user_id BIGINT UNSIGNED NOT NULL,
status VARCHAR(24) NOT NULL DEFAULT 'PENDING_PAY',
total_amount INT UNSIGNED NOT NULL COMMENT '订单总金额,单位分',
paid_amount INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '实际支付金额,单位分',
refunded_amount INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '累计退款金额,单位分',
expire_at DATETIME NOT NULL COMMENT '最晚支付时间,超时后释放库存',
paid_at DATETIME DEFAULT NULL,
closed_at DATETIME DEFAULT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uk_order_no (order_no),
KEY idx_user_created (user_id, created_at),
KEY idx_status_expire (status, expire_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 订单明细表:保存下单时的商品快照,避免后续改价影响历史订单
CREATE TABLE mock_order_item (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
order_id BIGINT UNSIGNED NOT NULL,
product_id BIGINT UNSIGNED NOT NULL,
sku_id BIGINT UNSIGNED NOT NULL,
product_name VARCHAR(200) NOT NULL,
sku_name VARCHAR(100) NOT NULL,
unit_price INT UNSIGNED NOT NULL,
quantity INT UNSIGNED NOT NULL,
subtotal INT UNSIGNED NOT NULL,
PRIMARY KEY (id),
KEY idx_order_id (order_id),
KEY idx_sku_id (sku_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 模拟支付记录:一个业务订单可以保留独立的支付流水
CREATE TABLE mock_payment (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
order_id BIGINT UNSIGNED NOT NULL,
pay_no VARCHAR(32) NOT NULL,
mock_prepay_id VARCHAR(64) NOT NULL,
amount INT UNSIGNED NOT NULL,
status VARCHAR(24) NOT NULL DEFAULT 'NOTPAY',
mock_transaction_id VARCHAR(64) DEFAULT NULL,
paid_at DATETIME DEFAULT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uk_pay_no (pay_no),
UNIQUE KEY uk_prepay_id (mock_prepay_id),
UNIQUE KEY uk_transaction_id (mock_transaction_id),
KEY idx_order_id (order_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 模拟退款记录:支持一笔订单分多次退款
CREATE TABLE mock_refund (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
order_id BIGINT UNSIGNED NOT NULL,
refund_no VARCHAR(32) NOT NULL,
refund_amount INT UNSIGNED NOT NULL,
status VARCHAR(24) NOT NULL DEFAULT 'PROCESSING',
reason VARCHAR(255) NOT NULL DEFAULT '',
mock_refund_id VARCHAR(64) DEFAULT NULL,
success_at DATETIME DEFAULT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uk_refund_no (refund_no),
UNIQUE KEY uk_mock_refund_id (mock_refund_id),
KEY idx_order_id (order_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 幂等请求表:防止用户重复点击产生多张相同订单
CREATE TABLE mock_idempotency (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
user_id BIGINT UNSIGNED NOT NULL,
request_token VARCHAR(64) NOT NULL COMMENT '客户端每次业务操作生成的唯一请求标识',
business_type VARCHAR(32) NOT NULL,
business_no VARCHAR(32) DEFAULT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uk_user_token_type (user_id, request_token, business_type)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
金额统一使用整数分。订单明细保存商品快照,避免商品改名或改价后影响历史订单。
五、插入模拟商品数据
INSERT INTO mock_user (openid, nickname) VALUES
('mock_openid_10001', '测试用户');
INSERT INTO mock_product (name, cover, status) VALUES
('ThinkPHP 5.1 实战课程', '/static/product/tp51.png', 1),
('程序员机械键盘', '/static/product/keyboard.png', 1);
INSERT INTO mock_product_sku
(product_id, sku_name, price, stock, locked_stock, sales, status) VALUES
(1, '电子版', 990, 9999, 0, 0, 1),
(1, '电子版 + 源码', 1990, 9999, 0, 0, 1),
(2, '黑色青轴', 29900, 50, 0, 0, 1),
(2, '白色茶轴', 31900, 30, 0, 0, 1);
六、ThinkPHP 5.1 数据库配置
// config/database.php
return [
'type' => 'mysql',
'hostname' => '127.0.0.1',
'database' => 'mock_shop',
'username' => 'root',
'password' => 'your_password',
'hostport' => '3306',
'charset' => 'utf8mb4',
'prefix' => '',
'debug' => true,
'deploy' => 0,
'rw_separate' => false,
'auto_timestamp' => false,
'datetime_format' => 'Y-m-d H:i:s',
];
七、配置路由
// application/route.php
// 路由统一使用 /api/mock 前缀,便于与真实支付接口隔离
use think\Route;
Route::post('api/mock/login', 'api/MockAuth/login');
Route::get('api/mock/products', 'api/Product/index');
Route::get('api/mock/products/:id', 'api/Product/read');
Route::post('api/mock/orders', 'api/Order/create');
Route::get('api/mock/orders', 'api/Order/index');
Route::get('api/mock/orders/:order_no', 'api/Order/read');
Route::post('api/mock/orders/:order_no/pay', 'api/Order/pay');
Route::post('api/mock/orders/:order_no/cancel', 'api/Order/cancel');
Route::post('api/mock/orders/:order_no/refunds', 'api/Order/refund');
Route::post('api/mock/payments/:pay_no/complete', 'api/MockPayment/completePay');
Route::post('api/mock/payments/:pay_no/fail', 'api/MockPayment/failPay');
Route::post('api/mock/refunds/:refund_no/complete', 'api/MockPayment/completeRefund');
八、统一 JSON 返回与异常处理
// application/api/controller/Base.php
namespace app\api\controller;
use think\Controller;
use think\exception\HttpResponseException;
class Base extends Controller
{
// 所有 API 使用统一 JSON 格式,前端只需判断 code 是否为 0
protected function successJson($data = [], $message = 'ok')
{
return json([
'code' => 0,
'message' => $message,
'data' => $data,
]);
}
protected function failJson($message, $code = 40001, $status = 400)
{
throw new HttpResponseException(json([
'code' => $code,
'message' => $message,
'data' => null,
], $status));
}
protected function currentUserId()
{
// 此方法仅用于模拟环境;真实项目必须从已验证的 Token 中取得用户 ID
// 演示环境从请求头读取,正式项目应验证登录 Token
$userId = (int) request()->header('X-Mock-User-Id', 0);
if ($userId <= 0) {
$this->failJson('请先登录', 40101, 401);
}
return $userId;
}
}
九、模拟小程序登录
// application/api/controller/MockAuth.php
namespace app\api\controller;
use think\Db;
class MockAuth extends Base
{
// 使用模拟 code 生成稳定 openid,代替真实的微信 code2Session 调用
public function login()
{
$mockCode = input('post.code/s', 'mock_code_10001');
$openid = 'mock_openid_' . substr(md5($mockCode), 0, 12);
$user = Db::name('mock_user')->where('openid', $openid)->find();
if (!$user) {
$userId = Db::name('mock_user')->insertGetId([
'openid' => $openid,
'nickname' => '模拟用户',
'created_at' => date('Y-m-d H:i:s'),
]);
} else {
$userId = $user['id'];
}
return $this->successJson([
'user_id' => $userId,
'access_token' => base64_encode($userId . '|' . $openid),
'expires_in' => 7200,
]);
}
}
这里的 access_token 只用于演示,不能用于正式项目。生产环境应使用安全的会话或 JWT,并校验签名、有效期和撤销状态。
十、商品列表接口
// application/api/controller/Product.php
namespace app\api\controller;
use think\Db;
class Product extends Base
{
public function index()
{
// 先查询已上架商品,再为每个商品加载可售 SKU
$products = Db::name('mock_product')
->where('status', 1)
->order('id', 'desc')
->select();
foreach ($products as &$product) {
$product['skus'] = Db::name('mock_product_sku')
->where('product_id', $product['id'])
->where('status', 1)
->field('id,sku_name,price,stock')
->select();
}
unset($product);
return $this->successJson($products);
}
}
十一、生成订单号
// prefix 区分业务类型:MO=订单、MP=支付、MR=退款
function generateOrderNo($prefix = 'MO')
{
return $prefix
. date('YmdHis')
. str_pad((string) random_int(0, 999999), 6, '0', STR_PAD_LEFT);
}
数据库还必须为订单号建立唯一索引。极少数随机冲突发生时,应重新生成并重试,不能只依赖随机算法。
十二、创建订单服务
// application/api/service/OrderService.php
namespace app\api\service;
use RuntimeException;
use think\Db;
class OrderService
{
public function create($userId, array $items, $requestToken)
{
// userId 必须来自登录态,items 中只接收 SKU 和数量,不接收客户端价格
if (!$items) {
throw new RuntimeException('请选择商品');
}
// 订单、明细、库存和幂等记录必须在同一事务中提交
Db::startTrans();
try {
// 锁定幂等记录,避免两个并发请求同时创建订单
$idempotency = Db::name('mock_idempotency')
->where('user_id', $userId)
->where('request_token', $requestToken)
->where('business_type', 'CREATE_ORDER')
->lock(true)
->find();
if ($idempotency && $idempotency['business_no']) {
$order = Db::name('mock_order')
->where('order_no', $idempotency['business_no'])
->find();
Db::commit();
return $order;
}
if (!$idempotency) {
Db::name('mock_idempotency')->insert([
'user_id' => $userId,
'request_token' => $requestToken,
'business_type' => 'CREATE_ORDER',
'created_at' => date('Y-m-d H:i:s'),
]);
}
$orderItems = [];
$totalAmount = 0;
foreach ($items as $item) {
$skuId = (int) ($item['sku_id'] ?? 0);
$quantity = (int) ($item['quantity'] ?? 0);
if ($skuId <= 0 || $quantity <= 0 || $quantity > 99) {
throw new RuntimeException('商品数量不正确');
}
// 锁定 SKU 行,保证检查库存与扣减库存之间不会被并发修改
$sku = Db::name('mock_product_sku')
->alias('s')
->join('mock_product p', 'p.id = s.product_id')
->where('s.id', $skuId)
->where('s.status', 1)
->where('p.status', 1)
->field('s.*,p.name AS product_name')
->lock(true)
->find();
if (!$sku) {
throw new RuntimeException('商品不存在或已下架');
}
if ((int) $sku['stock'] < $quantity) {
throw new RuntimeException($sku['product_name'] . '库存不足');
}
// 条件更新是第二层保护:库存不足时 affected 不会等于 1
$affected = Db::name('mock_product_sku')
->where('id', $skuId)
->where('stock', '>=', $quantity)
->update([
'stock' => Db::raw('stock-' . $quantity),
'locked_stock' => Db::raw('locked_stock+' . $quantity),
'version' => Db::raw('version+1'),
]);
if ($affected !== 1) {
throw new RuntimeException('库存预占失败,请重试');
}
// 金额全部使用整数分计算,禁止使用浮点数元
$subtotal = (int) $sku['price'] * $quantity;
$totalAmount += $subtotal;
$orderItems[] = [
'product_id' => $sku['product_id'],
'sku_id' => $skuId,
'product_name' => $sku['product_name'],
'sku_name' => $sku['sku_name'],
'unit_price' => $sku['price'],
'quantity' => $quantity,
'subtotal' => $subtotal,
];
}
$orderNo = generateOrderNo('MO');
// 保存订单主表;15 分钟后仍未支付则进入超时关闭流程
$orderId = Db::name('mock_order')->insertGetId([
'order_no' => $orderNo,
'user_id' => $userId,
'status' => 'PENDING_PAY',
'total_amount' => $totalAmount,
'paid_amount' => 0,
'refunded_amount' => 0,
'expire_at' => date('Y-m-d H:i:s', time() + 15 * 60),
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
]);
foreach ($orderItems as &$orderItem) {
$orderItem['order_id'] = $orderId;
}
unset($orderItem);
Db::name('mock_order_item')->insertAll($orderItems);
Db::name('mock_idempotency')
->where('user_id', $userId)
->where('request_token', $requestToken)
->where('business_type', 'CREATE_ORDER')
->update(['business_no' => $orderNo]);
Db::commit();
return Db::name('mock_order')->where('id', $orderId)->find();
} catch (\Throwable $e) {
Db::rollback();
throw $e;
}
}
}
十三、订单控制器
// application/api/controller/Order.php
namespace app\api\controller;
use app\api\service\MockPayService;
use app\api\service\OrderService;
use think\Db;
class Order extends Base
{
public function create()
{
$userId = $this->currentUserId();
$items = input('post.items/a', []);
$requestToken = input('post.request_token/s');
if (!$requestToken || strlen($requestToken) > 64) {
$this->failJson('request_token 不正确');
}
try {
$order = (new OrderService())->create(
$userId,
$items,
$requestToken
);
return $this->successJson($order, '订单创建成功');
} catch (\Throwable $e) {
return $this->failJson($e->getMessage());
}
}
public function read($orderNo)
{
$userId = $this->currentUserId();
$order = Db::name('mock_order')
->where('order_no', $orderNo)
->where('user_id', $userId)
->find();
if (!$order) {
$this->failJson('订单不存在', 40401, 404);
}
$order['items'] = Db::name('mock_order_item')
->where('order_id', $order['id'])
->select();
$order['payment'] = Db::name('mock_payment')
->where('order_id', $order['id'])
->order('id', 'desc')
->find();
$order['refunds'] = Db::name('mock_refund')
->where('order_id', $order['id'])
->order('id', 'desc')
->select();
return $this->successJson($order);
}
public function pay($orderNo)
{
$userId = $this->currentUserId();
try {
$result = (new MockPayService())->createPayment($userId, $orderNo);
return $this->successJson($result, '模拟支付单创建成功');
} catch (\Throwable $e) {
return $this->failJson($e->getMessage());
}
}
}
十四、创建模拟支付单
// application/api/service/MockPayService.php
namespace app\api\service;
use RuntimeException;
use think\Db;
class MockPayService
{
public function createPayment($userId, $orderNo)
{
// 创建支付单前必须校验订单归属、状态和有效期
Db::startTrans();
try {
$order = Db::name('mock_order')
->where('order_no', $orderNo)
->where('user_id', $userId)
->lock(true)
->find();
if (!$order) {
throw new RuntimeException('订单不存在');
}
if ($order['status'] === 'PAID') {
throw new RuntimeException('订单已支付');
}
if ($order['status'] !== 'PENDING_PAY') {
throw new RuntimeException('当前状态不能支付');
}
if (strtotime($order['expire_at']) <= time()) {
throw new RuntimeException('订单已过期');
}
// 复用尚未支付的支付单,防止重复点击生成大量支付流水
$payment = Db::name('mock_payment')
->where('order_id', $order['id'])
->where('status', 'NOTPAY')
->order('id', 'desc')
->find();
if (!$payment) {
$payNo = generateOrderNo('MP');
$prepayId = 'mock_prepay_' . bin2hex(random_bytes(12));
$paymentId = Db::name('mock_payment')->insertGetId([
'order_id' => $order['id'],
'pay_no' => $payNo,
'mock_prepay_id' => $prepayId,
'amount' => $order['total_amount'],
'status' => 'NOTPAY',
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
]);
$payment = Db::name('mock_payment')->where('id', $paymentId)->find();
}
Db::commit();
return [
'pay_no' => $payment['pay_no'],
'mock_prepay_id' => $payment['mock_prepay_id'],
'amount' => $payment['amount'],
'amount_yuan' => number_format($payment['amount'] / 100, 2, '.', ''),
'expire_at' => $order['expire_at'],
];
} catch (\Throwable $e) {
Db::rollback();
throw $e;
}
}
}
十五、模拟支付成功
public function completePayment($payNo)
{
// 该方法模拟真实微信支付回调,必须支持重复调用且结果一致
Db::startTrans();
try {
$payment = Db::name('mock_payment')
->where('pay_no', $payNo)
->lock(true)
->find();
if (!$payment) {
throw new RuntimeException('支付单不存在');
}
// 重复回调直接返回原结果
// 幂等判断:已经成功的支付单直接返回,不再次扣库存或增加销量
if ($payment['status'] === 'SUCCESS') {
Db::commit();
return $payment;
}
$order = Db::name('mock_order')
->where('id', $payment['order_id'])
->lock(true)
->find();
if (!$order || $order['status'] !== 'PENDING_PAY') {
throw new RuntimeException('订单状态不能支付');
}
// 即使是模拟支付,也必须核对支付金额与订单金额
if ((int) $payment['amount'] !== (int) $order['total_amount']) {
throw new RuntimeException('支付金额不一致');
}
$transactionId = 'mock_tx_' . date('YmdHis') . bin2hex(random_bytes(5));
$now = date('Y-m-d H:i:s');
Db::name('mock_payment')
->where('id', $payment['id'])
->where('status', 'NOTPAY')
->update([
'status' => 'SUCCESS',
'mock_transaction_id' => $transactionId,
'paid_at' => $now,
'updated_at' => $now,
]);
Db::name('mock_order')
->where('id', $order['id'])
->where('status', 'PENDING_PAY')
->update([
'status' => 'PAID',
'paid_amount' => $payment['amount'],
'paid_at' => $now,
'updated_at' => $now,
]);
// 支付成功后把预占库存转为销量,实际可用库存已在下单时扣减
$items = Db::name('mock_order_item')
->where('order_id', $order['id'])
->select();
foreach ($items as $item) {
Db::name('mock_product_sku')
->where('id', $item['sku_id'])
->where('locked_stock', '>=', $item['quantity'])
->update([
'locked_stock' => Db::raw('locked_stock-' . (int) $item['quantity']),
'sales' => Db::raw('sales+' . (int) $item['quantity']),
]);
}
Db::commit();
return Db::name('mock_payment')->where('id', $payment['id'])->find();
} catch (\Throwable $e) {
Db::rollback();
throw $e;
}
}
十六、模拟支付控制器
// application/api/controller/MockPayment.php
namespace app\api\controller;
use app\api\service\MockPayService;
class MockPayment extends Base
{
public function completePay($payNo)
{
// 只允许开发/测试环境访问
// 双重保护:非调试环境拒绝执行模拟支付完成接口
if (!config('app_debug')) {
$this->failJson('模拟支付接口已关闭', 40301, 403);
}
try {
$payment = (new MockPayService())->completePayment($payNo);
return $this->successJson($payment, '模拟支付成功');
} catch (\Throwable $e) {
return $this->failJson($e->getMessage());
}
}
}
生产环境必须彻底关闭模拟完成接口,不能只依赖前端隐藏按钮。推荐通过独立测试配置、环境变量、内网限制和编译部署流程多重隔离。
十七、小程序请求封装
// utils/request.js
// 只能指向开发或测试环境,生产环境不得暴露模拟支付接口
const API_BASE = 'https://dev-api.example.com'
function request(url, method = 'GET', data = {}) {
return new Promise((resolve, reject) => {
wx.request({
url: API_BASE + url,
method,
data,
header: {
'Content-Type': 'application/json',
'X-Mock-User-Id': wx.getStorageSync('mock_user_id') || ''
},
success(res) {
if (res.statusCode === 200 && res.data.code === 0) {
resolve(res.data.data)
} else {
reject(new Error(res.data.message || '请求失败'))
}
},
fail: reject
})
})
}
module.exports = request
十八、小程序模拟登录
const request = require('../../utils/request')
Page({
async onLoad() {
try {
const login = await request('/api/mock/login', 'POST', {
code: 'mock_code_' + Date.now()
})
wx.setStorageSync('mock_user_id', login.user_id)
wx.setStorageSync('mock_access_token', login.access_token)
this.loadProducts()
} catch (e) {
wx.showToast({ title: e.message, icon: 'none' })
}
}
})
十九、小程序创建订单
async submitOrder() {
// 前端防抖只能改善体验,真正防重仍依赖服务端 request_token
if (this.data.submitting) return
this.setData({ submitting: true })
try {
const requestToken = `${Date.now()}_${Math.random().toString(36).slice(2)}`
const order = await request('/api/mock/orders', 'POST', {
request_token: requestToken,
items: this.data.cartItems.map(item => ({
sku_id: item.sku_id,
quantity: item.quantity
}))
})
wx.navigateTo({
url: `/pages/mock-pay/index?order_no=${order.order_no}`
})
} catch (e) {
wx.showToast({ title: e.message, icon: 'none' })
} finally {
this.setData({ submitting: false })
}
}
二十、小程序模拟收银台
Page({
data: {
orderNo: '',
payment: null,
paying: false
},
onLoad(options) {
this.setData({ orderNo: options.order_no })
this.createPayment()
},
async createPayment() {
const payment = await request(
`/api/mock/orders/${this.data.orderNo}/pay`,
'POST'
)
this.setData({ payment })
},
async confirmPay() {
// 避免用户连续点击;服务端 completePayment 仍需保证幂等
if (this.data.paying) return
this.setData({ paying: true })
try {
const payment = await request(
`/api/mock/payments/${this.data.payment.pay_no}/complete`,
'POST'
)
wx.showToast({ title: '模拟支付成功', icon: 'success' })
setTimeout(() => {
wx.redirectTo({
url: `/pages/order/detail?order_no=${this.data.orderNo}`
})
}, 600)
} catch (e) {
wx.showToast({ title: e.message, icon: 'none' })
} finally {
this.setData({ paying: false })
}
},
cancelPay() {
wx.showToast({ title: '已取消模拟支付', icon: 'none' })
}
})
二十一、模拟收银台页面
<!-- pages/mock-pay/index.wxml -->
<view class="pay-card" wx:if="{{payment}}">
<view class="pay-title">模拟微信支付</view>
<view class="pay-tip">仅供开发测试,不会产生真实扣款</view>
<view class="pay-amount">¥{{payment.amount_yuan}}</view>
<view class="pay-no">支付单号:{{payment.pay_no}}</view>
<button
class="pay-button"
type="primary"
loading="{{paying}}"
disabled="{{paying}}"
bindtap="confirmPay"
>确认模拟支付</button>
<button class="cancel-button" bindtap="cancelPay">取消</button>
</view>
/* pages/mock-pay/index.wxss */
.pay-card {
margin: 40rpx;
padding: 48rpx 36rpx;
border-radius: 24rpx;
background: #fff;
box-shadow: 0 12rpx 40rpx rgba(0, 0, 0, 0.08);
text-align: center;
}
.pay-title { font-size: 38rpx; font-weight: 600; }
.pay-tip { margin-top: 12rpx; color: #fa8c16; font-size: 24rpx; }
.pay-amount { margin: 50rpx 0 36rpx; font-size: 72rpx; font-weight: 700; }
.pay-no { margin-bottom: 40rpx; color: #8c8c8c; font-size: 24rpx; }
.pay-button { background: #07c160; }
.cancel-button { margin-top: 20rpx; }
二十二、取消未支付订单并释放库存
public function cancelOrder($userId, $orderNo)
{
// 取消订单、关闭支付单和释放预占库存必须处于同一事务
Db::startTrans();
try {
$order = Db::name('mock_order')
->where('order_no', $orderNo)
->where('user_id', $userId)
->lock(true)
->find();
if (!$order) {
throw new RuntimeException('订单不存在');
}
if ($order['status'] === 'CANCELLED') {
Db::commit();
return $order;
}
if ($order['status'] !== 'PENDING_PAY') {
throw new RuntimeException('当前订单不能取消');
}
// 支付成功后把预占库存转为销量,实际可用库存已在下单时扣减
$items = Db::name('mock_order_item')
->where('order_id', $order['id'])
->select();
foreach ($items as $item) {
Db::name('mock_product_sku')
->where('id', $item['sku_id'])
->where('locked_stock', '>=', $item['quantity'])
->update([
'stock' => Db::raw('stock+' . (int) $item['quantity']),
'locked_stock' => Db::raw('locked_stock-' . (int) $item['quantity']),
]);
}
Db::name('mock_payment')
->where('order_id', $order['id'])
->where('status', 'NOTPAY')
->update(['status' => 'CLOSED']);
Db::name('mock_order')
->where('id', $order['id'])
->where('status', 'PENDING_PAY')
->update([
'status' => 'CANCELLED',
'closed_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
]);
Db::commit();
return Db::name('mock_order')->where('id', $order['id'])->find();
} catch (\Throwable $e) {
Db::rollback();
throw $e;
}
}
二十三、创建模拟退款
public function createRefund($userId, $orderNo, $refundAmount, $reason)
{
// 退款金额由服务端按实付金额减去累计已退金额进行校验
Db::startTrans();
try {
$order = Db::name('mock_order')
->where('order_no', $orderNo)
->where('user_id', $userId)
->lock(true)
->find();
if (!$order || !in_array($order['status'], ['PAID', 'PART_REFUNDED'], true)) {
throw new RuntimeException('订单当前不能退款');
}
// 当前最大可退金额 = 实付金额 - 已成功退款金额
$available = (int) $order['paid_amount'] - (int) $order['refunded_amount'];
$refundAmount = (int) $refundAmount;
if ($refundAmount <= 0 || $refundAmount > $available) {
throw new RuntimeException('退款金额不正确');
}
$refundNo = generateOrderNo('MR');
$refundId = Db::name('mock_refund')->insertGetId([
'order_id' => $order['id'],
'refund_no' => $refundNo,
'refund_amount' => $refundAmount,
'status' => 'PROCESSING',
'reason' => mb_substr($reason, 0, 255),
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
]);
Db::name('mock_order')
->where('id', $order['id'])
->update(['status' => 'REFUNDING']);
Db::commit();
return Db::name('mock_refund')->where('id', $refundId)->find();
} catch (\Throwable $e) {
Db::rollback();
throw $e;
}
}
二十四、模拟退款完成
public function completeRefund($refundNo)
{
// 模拟退款回调:重复执行时不能重复累计 refunded_amount
Db::startTrans();
try {
$refund = Db::name('mock_refund')
->where('refund_no', $refundNo)
->lock(true)
->find();
if (!$refund) {
throw new RuntimeException('退款单不存在');
}
if ($refund['status'] === 'SUCCESS') {
Db::commit();
return $refund;
}
$order = Db::name('mock_order')
->where('id', $refund['order_id'])
->lock(true)
->find();
$newRefundedAmount = (int) $order['refunded_amount']
+ (int) $refund['refund_amount'];
if ($newRefundedAmount > (int) $order['paid_amount']) {
throw new RuntimeException('累计退款金额超过实付金额');
}
$now = date('Y-m-d H:i:s');
Db::name('mock_refund')
->where('id', $refund['id'])
->where('status', 'PROCESSING')
->update([
'status' => 'SUCCESS',
'mock_refund_id' => 'mock_refund_' . bin2hex(random_bytes(8)),
'success_at' => $now,
'updated_at' => $now,
]);
// 累计退款等于实付金额时为全额退款,否则为部分退款
$orderStatus = $newRefundedAmount === (int) $order['paid_amount']
? 'REFUNDED'
: 'PART_REFUNDED';
Db::name('mock_order')
->where('id', $order['id'])
->update([
'status' => $orderStatus,
'refunded_amount' => $newRefundedAmount,
'updated_at' => $now,
]);
Db::commit();
return Db::name('mock_refund')->where('id', $refund['id'])->find();
} catch (\Throwable $e) {
Db::rollback();
throw $e;
}
}
二十五、小程序申请模拟退款
async applyRefund() {
// 页面输入元,调用后端接口前转换为整数分
const amountFen = Math.round(Number(this.data.refundAmountYuan) * 100)
if (!Number.isInteger(amountFen) || amountFen <= 0) {
wx.showToast({ title: '请输入正确退款金额', icon: 'none' })
return
}
try {
const refund = await request(
`/api/mock/orders/${this.data.orderNo}/refunds`,
'POST',
{
refund_amount: amountFen,
reason: this.data.refundReason || '用户申请退款'
}
)
await request(
`/api/mock/refunds/${refund.refund_no}/complete`,
'POST'
)
wx.showToast({ title: '模拟退款成功', icon: 'success' })
this.loadOrder()
} catch (e) {
wx.showToast({ title: e.message, icon: 'none' })
}
}
前端换算金额只用于交互,服务端仍必须根据订单实付与已退金额重新校验。
二十六、订单状态说明
| 状态 | 说明 | 允许操作 |
|---|---|---|
PENDING_PAY | 待支付,库存已预占 | 支付、取消、超时关闭 |
PAID | 支付成功 | 履约、申请退款 |
CANCELLED | 用户取消 | 重新下单 |
CLOSED | 超时关闭 | 重新下单 |
REFUNDING | 退款处理中 | 查询退款结果 |
PART_REFUNDED | 部分退款成功 | 继续退款可退余额 |
REFUNDED | 全额退款成功 | 查看记录 |
二十七、定时关闭超时订单
// application/command/CloseExpiredOrders.php
namespace app\command;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
class CloseExpiredOrders extends Command
{
protected function configure()
{
$this->setName('mock:close-expired-orders')
->setDescription('关闭过期模拟订单并释放库存');
}
protected function execute(Input $input, Output $output)
{
// 每批最多处理 100 条,避免单次任务运行过久
$orders = Db::name('mock_order')
->where('status', 'PENDING_PAY')
->where('expire_at', '<', date('Y-m-d H:i:s'))
->limit(100)
->select();
foreach ($orders as $order) {
try {
// 调用与手动取消相同的领域服务,确保幂等
app('OrderService')->closeExpired($order['order_no']);
$output->writeln('closed: ' . $order['order_no']);
} catch (\Throwable $e) {
$output->writeln('failed: ' . $order['order_no']);
}
}
}
}
计划任务可以每分钟执行一次:
* * * * * cd /www/project && php think mock:close-expired-orders >> runtime/log/close_order.log 2>&1
二十八、使用 curl 测试完整流程
1. 模拟登录
curl -X POST http://127.0.0.1/api/mock/login \
-H "Content-Type: application/json" \
-d '{"code":"mock_code_demo"}'
2. 创建订单
curl -X POST http://127.0.0.1/api/mock/orders \
-H "Content-Type: application/json" \
-H "X-Mock-User-Id: 1" \
-d '{
"request_token":"create_order_0001",
"items":[
{"sku_id":1,"quantity":1},
{"sku_id":3,"quantity":2}
]
}'
3. 创建模拟支付单
curl -X POST \
http://127.0.0.1/api/mock/orders/MO20261116160000123456/pay \
-H "X-Mock-User-Id: 1"
4. 完成模拟支付
curl -X POST \
http://127.0.0.1/api/mock/payments/MP20261116160100654321/complete
5. 申请模拟退款
curl -X POST \
http://127.0.0.1/api/mock/orders/MO20261116160000123456/refunds \
-H "Content-Type: application/json" \
-H "X-Mock-User-Id: 1" \
-d '{"refund_amount":990,"reason":"测试退款"}'
二十九、必须测试的异常场景
- 客户端把商品价格改为 1 分,服务端仍按数据库价格计算。
- 相同 request_token 重复创建订单,只返回同一订单。
- 两个请求同时购买最后一件库存,只有一个成功。
- 支付完成接口重复调用,不重复扣库存或增加销量。
- 支付金额与订单金额不一致时拒绝入账。
- 订单超时后释放预占库存。
- 已支付订单不能取消,未支付订单不能退款。
- 部分退款累计金额不能超过实付金额。
- 退款完成接口重复调用,不重复累计已退金额。
- 用户不能查询、支付或退款其他用户的订单。
三十、模拟系统切换真实微信支付
后续接入真实微信支付时,可以保留订单、库存和退款状态机,仅替换支付网关:
| 模拟实现 | 真实微信支付实现 |
|---|---|
| 生成 mock_prepay_id | 调用 API v3 JSAPI/小程序下单获取 prepay_id |
| 模拟收银台按钮 | 调用 wx.requestPayment |
| completePay 接口 | 微信支付通知验签、解密和幂等处理 |
| 模拟查询 payment 表 | 调用微信支付查单接口 |
| completeRefund 接口 | 退款通知验签、解密与主动查退款 |
建议定义统一的支付网关接口:
// 业务层只依赖接口,开发和生产环境分别注入不同支付网关
interface PaymentGatewayInterface
{
public function createPayment(array $order, array $payer);
public function queryPayment($outTradeNo);
public function closePayment($outTradeNo);
public function createRefund(array $refund);
public function queryRefund($outRefundNo);
}
开发环境注入 MockPaymentGateway,生产环境注入 WechatPayGateway,业务层不需要关心底层支付渠道。
三十一、安全与上线提醒
- 模拟支付完成接口只能在本地或测试环境启用。
- 生产构建中应移除模拟路由,而不是只隐藏前端按钮。
- 真实金额始终由服务端计算,并使用整数分保存。
- 订单状态变更必须经过领域服务,不能直接信任客户端状态。
- 创建订单、支付完成和退款完成都要实现幂等。
- 库存更新需要事务、条件更新或行锁。
- 所有订单接口检查登录用户和订单归属关系。
- 日志记录订单号和流水号,但不能记录真实密钥或敏感身份信息。
三十二、总结
这套 ThinkPHP 5.1 模拟商城流程虽然不产生真实资金交易,但完整保留了生产支付系统最重要的结构:服务端计价、订单状态机、库存预占、支付记录、幂等回调、部分退款和异常补偿。先用模拟网关把业务链路跑通,再替换为微信支付 API v3,可以显著降低联调难度,也能避免把支付逻辑全部堆在小程序页面中。