1. 页面 WXML 文件(例如:order.wxml
)
<view class="container"> <button bindtap="submitOrder">提交订单</button> </view>
3. 页面 JS 文件(例如:order.js
)
Page({ data: { // 可以在这里定义一些数据,例如订单详情 }, submitOrder: function() { const that = this; wx.request({ url: 'https://your-backend-server.com/api/submitOrder', // 后端提交订单接口 method: 'POST', data: { // 发送订单相关数据,例如商品ID、数量等 orderId: 'your-order-id', productIds: ['product1', 'product2'], quantities: [2, 1], }, success(res) { if (res.data && res.data.prepayId) { // 如果后端返回了 prepayId,则调用小程序支付接口 that.requestPayment(res.data.prepayId); } else { wx.showToast({ title: '提交订单失败', icon: 'none' }); } }, fail() { wx.showToast({ title: '提交订单请求失败', icon: 'none' }); } }); }, requestPayment: function(prepayId) { wx.requestPayment({ timeStamp: '', // 注意:这个时间戳应该由后端生成并返回 nonceStr: '', // 注意:这个随机字符串应该由后端生成并返回 package: prepay_id=${prepayId}
, signType: 'MD5', // 根据后端签名类型填写,可能是 RSA2 paySign: '', // 注意:这个签名应该由后端生成并返回 success(res) { wx.showToast({ title: '支付成功', icon: 'success' }); // 支付成功后跳转到订单详情页面或其他页面 wx.redirectTo({ url: '/pages/orderDetail/orderDetail?orderId=your-order-id' }); }, fail(err) { wx.showToast({ title: '支付失败', icon: 'none' }); } }); // 这里需要调用后端接口获取 timeStamp, nonceStr, paySign 等参数 wx.request({ url: 'https://your-backend-server.com/api/getPaymentInfo', // 后端获取支付信息接口 method: 'POST', data: { prepayId: prepayId }, success(res) { if (res.data) { const paymentData = res.data; wx.requestPayment({ timeStamp: paymentData.timeStamp, nonceStr: paymentData.nonceStr, package: prepay_id=${prepayId}
, signType: paymentData.signType, paySign: paymentData.paySign, success(res) { wx.showToast({ title: '支付成功', icon: 'success' }); // 支付成功后逻辑 }, fail(err) { wx.showToast({ title: '支付失败', icon: 'none' }); } }); } }, fail() { wx.showToast({ title: '获取支付信息失败', icon: 'none' }); } }); } });