daShangDao_miniProgram/components/MemberBookCheck.js
2026-06-15 16:37:57 +08:00

892 lines
24 KiB
JavaScript
Raw Permalink 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.

/**
* 获取用户业务信息的公共方法
* @param {Number} userId - 用户ID
* @returns {Promise<Object>} - 返回Promise包含请求结果
*/
export const getUserRecbusiness = async (userId) => {
const [err, response] = await uni.request({
// url: 'https://newadmin.buzhiyushu.cn/settledMember/record/queryMemberBooksCount',
url: 'https://go.order.service.buzhiyushu.cn/api/user/getUserRecbusiness',
// method: 'POST',
method: 'GET',
data: {
userId: userId // 确保转换为数字类型
},
header: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
// console.log('查询会员书籍数量结果:', response);
// 检查是否有错误
if (err) {
throw err;
}
return response;
};
/**
* 检查孔网翻新会员状态的公共方法
* @param {Number} userId - 用户ID
* @returns {Promise<Object>} - 返回Promise包含请求结果
*/
export const checkKwfwMemberStatus = async (userId) => {
const res = await uni.request({
url: 'https://go.order.service.buzhiyushu.cn/api/orders/checkStatus',
method: 'POST',
header: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: {
userId: userId,
type: 3
}
});
console.log('查询孔网翻新会员结果:', res);
return res[1] || res; // 兼容数组结构H5/小程序不同返回)
};
/**
* 检查用户是否可以上传书籍
* @param {Object} options - 配置选项
* @param {Boolean} options.showToast - 是否显示未登录提示默认为true
* @param {Boolean} options.showModal - 是否显示上传达到上限的提示默认为true
* @param {String} options.modalTitle - 提示弹窗的标题,默认为"提示"
* @param {String} options.rechargeUrl - 充值页面的URL默认为"/pages/user/recharge"
* @returns {Promise<Boolean>} - 返回Promiseresolve为true表示可以上传false表示不可上传
*/
export const checkMemberBooksCount = async (options = {}) => {
// 默认选项
const defaultOptions = {
showToast: true,
showModal: true,
modalTitle: '提示',
rechargeUrl: '/pages/user/recharge',
amount: 1 // 默认充值金额,单位元
};
// 合并选项
const mergedOptions = {
...defaultOptions,
...options
};
try {
// 获取用户ID
const userId = uni.getStorageSync('userId');
console.log('获取到的userId:', userId);
// 检查用户是否已登录
if (!userId) {
if (mergedOptions.showToast) {
uni.showToast({
title: '用户未登录,请先登录',
icon: 'none',
duration: 2500
});
}
return false;
}
// 调用查询接口
const response = await getUserRecbusiness(userId);
console.log("响应",response)
// 判断接口返回值
if (response.statusCode === 200 && response.data.data.isVip === false) {
// 如果返回false提示用户去充值
if (mergedOptions.showModal) {
return new Promise((resolve) => {
uni.showModal({
title: mergedOptions.modalTitle,
content: '您的上传数量已达上限,请充值后继续使用',
confirmText: '去充值',
cancelText: '取消',
success: (res) => {
if (res.confirm) {
// 跳转到会员选择页面指定只显示xcx上书会员
uni.navigateTo({
url: '/pkgUser/memberSelect?from=memberCheck&type=xcx'
});
// 返回一个Promise在用户返回时重新检查
return new Promise((resolve) => {
// 设置一个全局回调函数,供会员选择页面调用
getApp().memberSelectCallback = (success) => {
if (success) {
// 充值成功,重新检查权限
checkMemberBooksCount(mergedOptions)
.then(canUpload => {
if (canUpload) {
uni.showToast({
title: '现在您可以上传书籍了',
icon: 'success',
duration: 2000
});
resolve(true);
} else {
resolve(false);
}
});
} else {
resolve(false);
}
};
});
} else {
// 用户取消返回false表示不能上传
resolve(false);
}
}
});
});
}
return false;
}
// 如果返回true表示可以上传
return true;
} catch (error) {
console.error('查询会员书籍数量失败:', error);
// 接口调用失败时,默认允许上传,避免阻断用户使用
return true;
}
};
// 保存当前的settledId用于支付通知
let currentSettledId = null;
/**
* 调用微信支付
* @param {Number} amount - 充值金额
* @param {Number} settledId - 会员等级ID
* @param {String} paymentType - 支付类型,'normal' 为普通会员,'kwfw' 为孔网翻新会员
* @param {String} orderId - 订单id
* @returns {Promise<Object>} - 返回支付结果
*/
export const callWxPay = async (amount, settledId, paymentType = 'normal', orderId) => {
try {
// 保存settledId到模块变量供后续调用使用
currentSettledId = settledId;
console.log('当前的settledId1:', currentSettledId);
// 获取用户openid
const openid = uni.getStorageSync('openId');
if (!openid) {
throw new Error('未获取到openid');
}
// 获取用户ID
const userId = uni.getStorageSync('userId');
if (!userId) {
throw new Error('未获取到userId');
}
// 构造支付请求参数
const payData = {
openid: openid,
taskId: userId, // 使用用户ID作为任务ID
total: amount * 1, // 金额转为分
totalStr: amount.toString(),
description: `充值金额:${amount}`,
settledId: settledId
};
console.log('发起支付请求参数:', payData);
// 调用后端支付接口
const [err, res] = await uni.request({
url: 'https://api.buzhiyushu.cn/xcx/jsapiPay',
method: 'POST',
data: payData,
header: {
'Content-Type': 'application/json'
}
});
if (err) {
throw err;
}
console.log('支付接口返回:', res);
if (res.statusCode === 200 && res.data.code === 200) {
// 获取支付参数
const payParams = res.data.data;
console.log('支付参数:', payParams);
console.log('支付参数完整数据:', JSON.stringify(payParams));
// 调起微信支付
return new Promise((resolve) => {
// 在小程序环境中使用wx.requestPayment
wx.requestPayment({
appId: payParams.appId,
timeStamp: payParams.timeStamp,
nonceStr: payParams.nonceStr,
package: payParams.package,
signType: 'RSA',
paySign: payParams.paySign,
success: function(res) {
console.log('支付成功', res);
// 支付成功后,调用订单查询接口确认支付状态
checkPayStatus(payParams.outTradeNo, currentSettledId, paymentType,
orderId).then(orderResult => {
if (orderResult.success) {
resolve({
success: true,
data: res,
orderResult
});
} else {
resolve({
success: false,
error: '支付状态确认失败'
});
}
}).catch(err => {
console.error('订单查询失败', err);
// 即使订单查询失败,也认为支付成功,因为用户已经完成了支付流程
resolve({
success: true,
data: res,
orderQueryFailed: true
});
});
},
fail: function(err) {
console.error('支付失败', err);
resolve({
success: false,
error: err
});
},
complete: function(res) {
console.log('支付完成', res);
}
});
});
} else {
throw new Error(res.data.msg || '支付接口调用失败');
}
} catch (error) {
console.error('微信支付失败:', error);
uni.showToast({
title: '支付失败:' + error.message,
icon: 'none'
});
return {
success: false,
error
};
}
};
/**
* 查询支付订单状态
* @param {String} outTradeNo - 商户订单号
* @param {Number} [settledId] - 会员等级ID可选
* @param {String} paymentType - 支付类型,'normal' 为普通会员,'kwfw' 为孔网翻新会员
* @returns {Promise<Object>} - 返回订单查询结果
*/
export const checkPayStatus = async (outTradeNo, currentSettledId, paymentType = 'normal', orderId) => {
try {
console.log('查询订单号:', outTradeNo); // 添加日志确认订单号
console.log('当前的settledId2:', currentSettledId);
console.log("订单号", orderId);
// 如果未提供settledId参数使用模块变量
const finalSettledId = currentSettledId;
if (finalSettledId) {
console.log('使用会员等级ID:', finalSettledId);
}
const [err, res] = await uni.request({
url: 'https://api.buzhiyushu.cn/xcx/queryOrder',
method: 'POST',
data: {
outTradeNo: outTradeNo
},
header: {
'Content-Type': 'application/json'
}
});
if (err) {
throw err;
}
console.log('订单查询结果:', res);
if (res.statusCode === 200 && res.data.code === 200) {
// 根据支付类型执行不同的处理逻辑
if (paymentType === 'normal') {
// 普通会员支付:调用通知接口保存支付记录
try {
获取用户ID
const userId = uni.getStorageSync('userId');
// 准备通知数据
const notifyData = {
...res.data.data, // 将查询到的订单数据传递给通知接口
userId: userId // 添加用户ID
};
// 如果有会员等级ID添加到通知数据中
if (finalSettledId) {
notifyData.settledId = finalSettledId;
console.log('添加会员等级ID到通知数据:', finalSettledId);
}
console.log("当前的settledId3:", notifyData.settledId);
console.log("通知数据:", notifyData);
const [notifyErr, notifyRes] = await uni.request({
url: 'https://newadmin.buzhiyushu.cn/wechatPay/notification',
method: 'POST',
data: notifyData,
header: {
'Content-Type': 'application/json'
}
});
if (notifyErr) {
console.error('保存支付记录失败:', notifyErr);
} else {
console.log('保存支付记录结果:', notifyRes);
}
} catch (notifyError) {
console.error('调用支付通知接口失败:', notifyError);
}
}
return {
success: true,
data: res.data.data,
isPaid: res.data.data.trade_state === 'SUCCESS'
};
} else {
return {
success: false,
error: res.data.msg || '订单查询失败'
};
}
} catch (error) {
console.error('查询订单状态失败:', error);
return {
success: false,
error
};
}
};
/**
* 获取会员等级列表
* @returns {Promise<Array>} - 返回会员等级列表
*/
export const getMemberLevelList = async () => {
try {
const [err, res] = await uni.request({
url: 'https://newadmin.buzhiyushu.cn/settledCostConfig/list',
// url: 'http://localhost:8089/settledCostConfig/list',
method: 'GET',
header: {
'Content-Type': 'application/json'
}
});
if (err) {
throw err;
}
console.log('获取会员等级列表结果:', res);
if (res.data.code === 200 && res.data.data && res.data.data.length > 0) {
return res.data.data;
} else {
throw new Error('获取会员等级列表失败');
}
} catch (error) {
console.error('获取会员等级列表失败:', error);
throw error;
}
};
/**
* 显示会员等级选择器
* @param {Array} levelList - 会员等级列表
* @returns {Promise<Object>} - 返回用户选择的会员等级
*/
export const showMemberLevelSelector = (levelList) => {
return new Promise((resolve) => {
// 构建选择项
const items = levelList.map(level => ({
text: `${level.name || '会员等级'} (${level.price}元)`,
value: level
}));
// 显示操作菜单让用户选择
uni.showActionSheet({
itemList: items.map(item => item.text),
success: function(res) {
const selectedIndex = res.tapIndex;
if (selectedIndex >= 0 && selectedIndex < items.length) {
resolve(items[selectedIndex].value);
} else {
resolve(null);
}
},
fail: function() {
resolve(null); // 用户取消选择
}
});
});
};
/**
* 检查用户是否为孔网翻新会员
* @param {Object} options - 配置选项
* @param {Boolean} options.showToast - 是否显示未登录提示默认为true
* @param {Boolean} options.showModal - 是否显示非会员提示默认为true
* @param {String} options.modalTitle - 提示弹窗的标题,默认为"提示"
* @returns {Promise<Boolean>} - 返回Promiseresolve为true表示是会员false表示不是会员
*/
export const checkKwfwMember = async (options = {}) => {
const defaultOptions = {
showToast: true,
showModal: true,
modalTitle: '提示'
};
const mergedOptions = { ...defaultOptions, ...options };
try {
const userId = uni.getStorageSync('userId');
console.log('检查孔网翻新会员获取到的userId:', userId);
if (!userId) {
if (mergedOptions.showToast) {
uni.showToast({
title: '用户未登录,请先登录',
icon: 'none',
duration: 2500
});
}
return false;
}
// ✅ 调用公共方法
let response;
try {
response = await checkKwfwMemberStatus(userId);
} catch (err) {
console.error('请求出错:', err);
throw err;
}
// ✅ 确保返回结构存在
if (!response || !response.data) {
throw new Error('接口调用失败');
}
const { code, data, message } = response.data;
console.log('会员检查结果:', code, data);
// ✅ 1. 情况一:接口返回用户不存在
if (code === 40001) {
return await handleNotMemberModal(mergedOptions);
}
// ✅ 2. 情况二:接口正常返回,但 isVip 为 false
if (code === 200 && data && data.isVip === false) {
return await handleNotMemberModal(mergedOptions);
}
// ✅ 3. 情况三:是会员
if (code === 200 && data && data.isVip === true) {
console.log('当前用户是孔网翻新会员 ✅');
return true;
}
// 其他异常情况
console.warn('接口返回未知状态:', code, message);
return false;
} catch (error) {
console.error('查询孔网翻新会员失败:', error);
if (mergedOptions.showToast) {
uni.showToast({
title: '网络错误,请稍后重试',
icon: 'none'
});
}
return false;
}
};
// ✅ 单独提取弹窗逻辑,便于多处调用
const handleNotMemberModal = (mergedOptions) => {
return new Promise((resolve) => {
if (!mergedOptions.showModal) return resolve(false);
uni.showModal({
title: mergedOptions.modalTitle,
content: '您还不是孔网翻新会员,需要开通会员才能使用此功能',
confirmText: '开通会员',
cancelText: '取消',
success: (res) => {
if (res.confirm) {
uni.navigateTo({
url: '/pkgUser/memberSelect?from=kwfw&type=kwfw'
});
getApp().kwfwMemberCallback = (success) => {
if (success) {
checkKwfwMember(mergedOptions).then((isMember) => {
if (isMember) {
uni.showToast({
title: '开通成功,现在您可以使用孔网翻新功能了',
icon: 'success',
duration: 2000
});
resolve(true);
} else {
resolve(false);
}
});
} else {
resolve(false);
}
};
} else {
resolve(false);
}
}
});
});
};
/**
* 孔网翻新会员订单插入接口(预留)
* @param {Object} orderData - 订单数据
* @returns {Promise<Object>} - 返回订单插入结果
*/
/**
* 支付前插入孔网翻新会员订单记录(预留接口)
* @param {Object} orderData 订单数据
* @returns {Object} 插入结果包含orderId
*/
export const createKwfwMemberOrder = async (orderData) => {
try {
console.log('支付前创建孔网翻新会员订单:', orderData);
// 获取并验证用户ID
let userId = orderData.userId || uni.getStorageSync('userId');
if (!userId || userId === 'undefined') {
console.error('用户未登录或userId无效');
return {
success: false,
error: '用户未登录,请先登录'
};
}
// 第一步:创建服务
// 确保所有参数都有有效值
const serviceName = orderData.serviceName || 'xcx翻新会员';
const price = orderData.originalPrice || orderData.price || '1';
const unit = orderData.unit || '月';
const length = orderData.length || '1';
const sort = orderData.sort || '1'
let vipType = '';
if (orderData.memberType == 'kwfw') {
vipType = 'xcxRenovate';
} else {
vipType = 'xcxLetter';
};
const createServiceData = {
service_name: String(serviceName),
price: String(price),
unit: String(unit),
length: String(length),
type: String(vipType),
sort: String(sort)
};
console.log('createServiceData:', createServiceData);
// 验证所有必需参数
if (!createServiceData.service_name || createServiceData.service_name === 'undefined' ||
!createServiceData.price || createServiceData.price === 'undefined' ||
!createServiceData.unit || createServiceData.unit === 'undefined' ||
!createServiceData.length || createServiceData.length === 'undefined') {
console.error('参数验证失败:', createServiceData);
return {
success: false,
error: '参数不完整请检查orderData中的serviceName、originalPrice、unit、length字段'
};
}
const [serviceErr, serviceResponse] = await uni.request({
url: 'https://go.order.service.buzhiyushu.cn/api/createService',
method: 'POST',
data: createServiceData,
header: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
if (serviceErr) {
console.error('创建服务失败:', serviceErr);
return {
success: false,
error: '创建服务失败: ' + serviceErr.errMsg
};
}
console.log('创建服务成功:', serviceResponse);
const serviceId = serviceResponse.data.data
if (!serviceId) {
console.error('服务创建成功但未返回服务ID');
return {
success: false,
error: '服务创建成功但未返回服务ID'
};
}
// 第二步:创建订单
const createOrderData = {
orderType: String(vipType),
userId: String(userId),
goodsId: String(serviceId),
count: String(1),
note: orderData.note || '孔网翻新会员订单'
};
console.log('createOrderData:', createOrderData);
const [orderErr, orderResponse] = await uni.request({
url: 'https://go.order.service.buzhiyushu.cn/api/orders/createOrder',
method: 'POST',
data: createOrderData,
header: {
'Content-Type': 'application/x-www-form-urlencoded'
// 'Content-Type': 'multipart/form-data'
}
});
if (orderErr) {
console.error('创建订单失败:', orderErr);
return {
success: false,
error: '创建订单失败: ' + orderErr.errMsg
};
}
console.log('创建订单成功:', orderResponse.data);
const orderId = orderResponse.data.data
if (!orderId) {
console.error('订单创建成功但未返回订单ID');
return {
success: false,
error: '订单创建成功但未返回订单ID'
};
}
return {
success: true,
orderId: orderId,
serviceId: serviceId,
message: '订单创建成功',
serviceData: serviceResponse.data,
orderData: orderResponse.data
};
} catch (error) {
console.error('创建孔网翻新会员订单失败:', error);
return {
success: false,
error: error.message
};
}
};
/**
* 支付后更新孔网翻新会员订单记录
* @param {String} orderId 订单ID
* @param {Object} payResult 支付结果
* @returns {Object} 更新结果
*/
export const updateKwfwMemberOrder = async (orderId, payResult, userId) => {
try {
console.log('支付后更新孔网翻新会员订单:', {
orderId,
payResult,
userId
});
// orderId 参数已经是实际的订单ID数字不需要再次提取
const actualOrderId = String(orderId)
console.log("actualOrderId", actualOrderId)
// 调用订单更新接口
const [err, response] = await uni.request({
url: 'https://go.order.service.buzhiyushu.cn/api/orders/orderForPay',
method: 'POST',
data: {
orderId: String(actualOrderId),
orderInfo: JSON.stringify(payResult),
userId: String(userId),
},
header: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
if (err) {
console.error('更新订单失败:', err);
return {
success: false,
error: '更新订单失败: ' + err.errMsg
};
}
console.log('订单更新接口返回:', response);
if (response.statusCode === 200) {
return {
success: true,
message: '订单更新成功',
data: response.data
};
} else {
return {
success: false,
error: '订单更新失败: ' + (response.data?.message || '未知错误')
};
}
} catch (error) {
console.error('更新孔网翻新会员订单失败:', error);
return {
success: false,
error: error.message
};
}
};
/**
* 更新用户书籍数量限制
* @param {Object} payResult 支付结果
* @param {String} orderId 订单ID
* @param {String} userId 用户ID
* @param {String} settledId 会员等级ID
* @returns {Promise<Object>} 返回更新结果
*/
export const updateUserBooksCountLimit = async (payResult, orderId, userId, settledId) => {
try {
console.log('更新用户书籍数量限制:', {
payResult,
orderId,
userId,
settledId
});
// 调用后端接口更新用户书籍数量限制
const [err, response] = await uni.request({
url: 'https://newadmin.buzhiyushu.cn/updateUserBooksCountLimit',
method: 'POST',
data: {
payResult: JSON.stringify(payResult),
orderId: orderId,
userId: userId,
settledId: settledId
},
header: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
if (err) {
console.error('更新用户书籍数量限制失败:', err);
return {
success: false,
error: '更新用户书籍数量限制失败: ' + err.errMsg
};
}
console.log('更新用户书籍数量限制接口返回:', response);
if (response.statusCode === 200 && response.data.code === 200) {
return {
success: true,
message: '用户书籍数量限制更新成功',
data: response.data.data
};
} else {
return {
success: false,
error: '更新用户书籍数量限制失败: ' + (response.data?.msg || '未知错误')
};
}
} catch (error) {
console.error('更新用户书籍数量限制失败:', error);
return {
success: false,
error: error.message
};
}
};
/**
* 获取所有服务列表
* @param {String} type - 服务类型
* @returns {Promise<Array>} - 返回服务列表
*/
export const getAllServices = async (type) => {
try {
const [err, response] = await uni.request({
url: 'https://go.order.service.buzhiyushu.cn/api/getAllServices',
method: 'POST',
data: {
type: type
},
header: {
'Content-Type': 'application/json'
}
});
if (err) {
throw err;
}
console.log('获取所有服务列表结果:', response);
// 检查响应状态
if (response.statusCode === 200 && response.data.code === 200) {
return {
success: true,
data: response.data.data,
message: response.data.message
};
} else {
throw new Error(response.data.message || '获取服务列表失败');
}
} catch (error) {
console.error('获取所有服务列表失败:', error);
return {
success: false,
error: error.message || '网络请求失败'
};
}
};
export default {
getUserRecbusiness,
checkKwfwMemberStatus,
checkMemberBooksCount,
callWxPay,
checkPayStatus,
getMemberLevelList,
showMemberLevelSelector,
checkKwfwMember,
createKwfwMemberOrder,
updateKwfwMemberOrder,
updateUserBooksCountLimit,
getAllServices
};