// import { models, db, _ } from '../../utils/cloudbase.js' import { getDB, getModels, getCommand, getTempFileURLs, getClient } from '../../utils/cloudbase.js' Page({ data: { products: [], totalAmount: 0, dingweiimg: '', youjiantouimg: '', selectedAddress: '', transactionId: '', outTradeNo: '', }, async onLoad() { const selectedItems = wx.getStorageSync('checkoutItems') || []; // 标准化 quantity 字段 const products = selectedItems.map(item => ({ ...item, quantity: item.num || item.num_index })); this.setData({ products }, () => { this.calculateTotal(); }); const fileIDs = [ 'cloud://honghgaier-5guiffgcf17a2eea.686f-honghgaier-5guiffgcf17a2eea-1373037829/images/icon/dingwei.png', 'cloud://honghgaier-5guiffgcf17a2eea.686f-honghgaier-5guiffgcf17a2eea-1373037829/images/icon/youjiantou.png', ]; const fileList = await getTempFileURLs(fileIDs) this.setData({ dingweiimg: fileList[0].tempFileURL, youjiantouimg: fileList[1].tempFileURL, }) // // 并发下载多个 fileID // Promise.all( // fileIDs.map(fileID => wx.cloud.downloadFile({ fileID })) // ).then(results => { // // 每个 result 对应一个下载结果 // const tempFilePaths = results.map(r => r.tempFilePath); // console.log('全部下载成功:', tempFilePaths); // this.setData({ // dingweiimg: tempFilePaths[0], // youjiantouimg: tempFilePaths[1], // }); // }).catch(err => { // console.error('有文件下载失败:', err); // }); }, decreaseQuantity(e) { const index = e.currentTarget.dataset.index; let products = this.data.products; if (products[index].quantity > 1) { products[index].quantity--; this.setData({ products }); this.calculateTotal(); } }, increaseQuantity(e) { const index = e.currentTarget.dataset.index; let products = this.data.products; products[index].quantity++; this.setData({ products }); this.calculateTotal(); }, onChange(e) { const { id } = e.currentTarget.dataset; const { detail } = e; const products = this.data.products.map(item => { if (item._id === id) { return { ...item, quantity: detail }; } return item; }); this.setData({ products }, () => { this.calculateTotal(); }); }, calculateTotal() { let totalAmount = 0; this.data.products.forEach(item => { totalAmount += item.specList[item.specs_index].price * item.quantity; }); this.setData({ totalAmount }); }, // async handlePay() { // // 1. 检查是否选择了收货地址 // if (!this.data.selectedAddress || !this.data.selectedAddress._id) { // wx.showToast({ // title: '请选择收货地址', // icon: 'none', // }); // return; // } // console.log(this.data.selectedAddress, 'this.data.selectedAddress'); // const outTradeNo = Math.round(Math.random() * 10 ** 13) + Date.now(); // const userInfo = wx.getStorageSync('userInfo') || {}; // // 2. 判断 products 是否已有 orders_id,如果没有再创建订单 // const needCreateOrders = this.data.products.filter(item => !item.orders_id); // let ordersResult = []; // if (needCreateOrders.length > 0) { // const orderPromises = needCreateOrders.map(item => { // return models.orders.create({ // data: { // adresses_id: this.data.selectedAddress._id, // merchandise_id: item._id, //商品id // school_id: userInfo.school_id, // groupbuy_id: item.specList[item.specs_index]._id || "", //规格id // specs_index: item.specs_index, //规格下标 // real_money: item.specList[item.specs_index].price * item.quantity, //付款金额 // way: 0, //订单方式 // user_id: userInfo._id, // num_index: item.quantity, //商品数量 // order_id: String(outTradeNo), //订单号 // status: 0, // 待支付 // }, // envType: "prod", // }); // }); // try { // ordersResult = await Promise.all(orderPromises); // console.log("新订单创建结果: ", ordersResult.map(r => r.data)); // } catch (err) { // console.error("订单创建失败: ", err); // wx.showToast({ title: '订单创建失败', icon: 'none' }); // return; // } // } else { // console.log("订单已存在,无需重复创建"); // } // // 3. 调用云函数下单 // wx.cloud.callFunction({ // name: 'wxpayFunctions', // data: { // type: 'wxpay_order', // description: "购买商品", // out_trade_no: outTradeNo, // amount: { // total: this.data.totalAmount * 100, // 微信支付单位为分 // currency: 'CNY' // }, // }, // success: (res) => { // console.log('下单结果: ', res); // const paymentData = res.result?.data; // this.setData({ // outTradeNo, // transactionId: paymentData.transaction_id // }); // wx.requestPayment({ // timeStamp: paymentData?.timeStamp, // nonceStr: paymentData?.nonceStr, // package: paymentData?.packageVal, // paySign: paymentData?.paySign, // signType: 'RSA', // success: async (payRes) => { // console.log('支付成功: ', payRes); // // 4. 支付成功后更新订单状态为待收货 (status=1) // try { // const updatePromises = this.data.products.map(item => { // // 如果已有 orders_id 就用它,否则用 order_id // const idToUpdate = item.orders_id || null; // if (!idToUpdate) { // // 没有 orders_id,之前创建的订单会通过 order_id + merchandise_id 更新 // return models.orders.update({ // data: { status: 1 }, // filter: { // where: { // $and: [ // { order_id: { $eq: String(outTradeNo) } }, // { merchandise_id: { $eq: item._id } } // ] // } // }, // envType: "prod" // }); // } else { // // 已有订单直接用 _id 更新 // return models.orders.update({ // data: { status: 1 }, // filter: { // where: { _id: { $eq: idToUpdate } } // }, // envType: "prod" // }); // } // }); // const results = await Promise.all(updatePromises); // console.log("支付成功,订单更新结果:", results); // wx.showToast({ // title: '支付成功', // icon: 'success', // duration: 1500, // success() { // wx.navigateBack(); // // wx.reLaunch({ // // url: '/subpackages/order/order?type=' + encodeURIComponent(1) // // }); // } // }); // } catch (err) { // console.error("支付成功,更新订单状态失败:", err); // } // }, // fail: (payErr) => { // console.error('支付失败: ', payErr); // wx.showToast({ title: '支付失败', icon: 'none' }); // // 支付失败订单仍保持status=0(待支付) // } // }); // }, // fail: (err) => { // console.error('下单失败: ', err); // wx.showToast({ title: '下单失败', icon: 'none' }); // } // }); // }, async handlePay() { wx.showLoading({ title: '提交订单中...', mask: true }); // 🚀 防止多次点击 let client = await getClient(); // 跨小程序 SDK const models = await getModels() // 1. 检查是否选择收货地址 const { selectedAddress, products, totalAmount } = this.data; if (!selectedAddress?._id) { wx.hideLoading(); // ❗️记得关闭 wx.showToast({ title: '请选择收货地址', icon: 'none' }); return; } const outTradeNo = Math.round(Math.random() * 10 ** 13) + Date.now(); const userInfo = wx.getStorageSync('userInfo') || {}; // 2. 创建订单(如果没有 orders_id) const needCreateOrders = products.filter(item => !item.orders_id); let ordersResult = []; if (needCreateOrders.length) { try { const orderPromises = needCreateOrders.map(item => models.orders.create({ data: { adresses_id: selectedAddress._id, merchandise_id: item._id, school_id: userInfo.school_id, groupbuy_id: item.specList[item.specs_index]?._id || "", specs_index: item.specs_index, real_money: item.specList[item.specs_index].price * item.quantity, way: 0, user_id: userInfo._id, num_index: item.quantity, order_id: String(outTradeNo), status: 0 }, envType: "prod", })); ordersResult = await Promise.all(orderPromises); console.log("新订单创建结果:", ordersResult.map(r => r.data)); } catch (err) { console.error("订单创建失败:", err); wx.showToast({ title: '订单创建失败', icon: 'none' }); return; } } else { console.log("订单已存在,无需重复创建"); } // 2. 获取小程序B openid const openid = await new Promise((resolve, reject) => { wx.login({ success: async res => { if (!res.code) return reject('获取 code 失败'); try { const r = await client.callFunction({ name: 'getopenid', data: { code: res.code } }); if (r.result?.openid) resolve(r.result.openid); else reject(r.result || '获取 openid 失败'); } catch (err) { reject(err); } }, fail: err => reject(err) }); }); console.log('拿到小程序B openid:', openid); // 3. 调用云函数下单\ try { const res = await client.callFunction({ name: 'wxpayFunctions', data: { type: 'wxpay_order', description: "购买商品", out_trade_no: outTradeNo, amount: { total: totalAmount * 100, currency: 'CNY' }, openid: openid } }); console.log(res, 'resresresresresres'); const paymentData = res.result?.data; if (!paymentData) throw new Error('下单返回数据异常'); this.setData({ outTradeNo, transactionId: paymentData.transaction_id }); wx.hideLoading(); // ✅ 支付前关闭 loading // 4. 调用微信支付 wx.requestPayment({ timeStamp: paymentData.timeStamp, nonceStr: paymentData.nonceStr, package: paymentData.packageVal, paySign: paymentData.paySign, signType: 'RSA', success: async () => { console.log('支付成功'); // 支付成功后批量更新订单状态为待收货 try { // 1. 更新已有订单_id 的订单(单条) const updateByIdPromises = products .filter(item => item.orders_id) .map(item => models.orders.update({ data: { status: 1 }, filter: { where: { _id: { $eq: item.orders_id } } }, envType: "prod" })); // 2. 更新创建订单时生成的所有订单(可能多条)使用 order_id const updateByOrderIdPromise = models.orders.updateMany({ data: { status: 1 }, filter: { where: { order_id: { $eq: String(outTradeNo) } } }, envType: "prod" }); await Promise.all([...updateByIdPromises, updateByOrderIdPromise]); wx.showToast({ title: '支付成功', icon: 'success', duration: 1500, success() { wx.navigateBack(); } }); } catch (err) { console.error("支付成功,更新订单状态失败:", err); } }, fail: (payErr) => { console.error('支付失败:', payErr); wx.showToast({ title: '支付失败', icon: 'none' }); } }); } catch (err) { console.error('下单失败:', err); wx.showToast({ title: '下单失败', icon: 'none' }); } }, setGridView() { wx.navigateTo({ url: '/subpackages/addresslist/addresslist' }); } });