duidui_mini_program/pages/camp_detail/modules/order-service.js
2026-03-27 10:41:46 +08:00

126 lines
3.4 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 订单服务模块
* 负责订单创建和支付相关的逻辑
*/
import { campApi } from '../../../config/camp_api.js';
import * as dataFetcher from './data-fetcher.js';
/**
* 创建订单并支付
* @param {Object} context - 页面上下文
* @param {String} sectionId - 小节ID
* @param {Number} priceFen - 价格(分)
* @param {Object} section - 小节信息
*/
export function createOrderAndPay(context, sectionId, priceFen, section) {
var campId = context.data.campId;
var userId = wx.getStorageSync('wxuserid') || '';
var openid = wx.getStorageSync('wxopenid') || '';
if (!userId || !openid) {
wx.showToast({
title: '用户信息缺失,请重新登录',
icon: 'none'
});
return Promise.resolve(false);
}
// 创建订单(包含 openid后端会自动生成预支付信息
var orderData = {
user_id: String(userId),
camp_id: String(campId),
section_id: String(sectionId),
payment_method: 'WECHAT',
openid: openid
};
return campApi.createOrder(orderData)
.then(function (orderRes) {
if (!orderRes || orderRes.success !== true || !orderRes.order_id) {
throw new Error(orderRes && orderRes.message || '创建订单失败');
}
var orderId = orderRes.order_id;
// 如果订单金额为0直接成功免费订单
if (orderRes.actual_amount === 0 || orderRes.order_status === 'PAID') {
wx.showToast({
title: '订单创建成功',
icon: 'success'
});
dataFetcher.fetchCampData(context, campId);
return true;
}
// 如果返回了预支付信息,直接调起微信支付
if (orderRes.prepay_id && orderRes.pay_sign) {
var payParams = {
timeStamp: orderRes.time_stamp || orderRes.timeStamp,
nonceStr: orderRes.nonce_str || orderRes.nonceStr,
package: orderRes.package || 'prepay_id=' + orderRes.prepay_id,
signType: orderRes.sign_type || orderRes.signType || 'RSA',
paySign: orderRes.pay_sign || orderRes.paySign
};
return new Promise(function (resolve, reject) {
wx.requestPayment({
timeStamp: payParams.timeStamp,
nonceStr: payParams.nonceStr,
package: payParams.package,
signType: payParams.signType,
paySign: payParams.paySign,
success: function (res) {
wx.showToast({
title: '支付成功',
icon: 'success'
});
dataFetcher.fetchCampData(context, campId);
resolve(true);
},
fail: function (err) {
if (err.errMsg === 'requestPayment:fail cancel') {
// 用户取消支付,调用取消订单接口
campApi.cancelOrder({ order_id: orderId })
.then(function (cancelRes) {
wx.showToast({
title: '已取消支付',
icon: 'none'
});
})
.catch(function (cancelErr) {
wx.showToast({
title: '已取消支付',
icon: 'none'
});
});
} else {
wx.showToast({
title: '支付失败',
icon: 'none'
});
}
reject(err);
}
});
});
} else {
// 如果没有预支付信息,说明订单创建成功但不需要支付
wx.showToast({
title: '订单创建成功',
icon: 'success'
});
dataFetcher.fetchCampData(context, campId);
return true;
}
})
.catch(function (err) {
wx.showToast({
title: err && err.message || '支付失败',
icon: 'none'
});
return false;
});
}