小程序商品加入购物车

用于小程序的商品加入购物车操作


使用步骤

第一步:配置接口地址

config.js 文件中找到 config 设置

第二步:检查接口定义

搜索 shop_add_cart 接口是否已经存在定义(有的小程序模板已经定义)

如果没有定义,在 config 底部新增以下代码:

shopAddCartUrl: getApiUrl('shop_add_cart'),

并复制红色部分待用。如果已经存在,则直接复制使用即可。

第三步:接口调用请求

如果定义名称不同,使用第二步复制的内容替换红框部分

/**
* 加入购物车(addCart) && 立即购买(buyNow) && 确认规格选择(specType)
* 接收参数
* 无需接收参数,从页面数据中取值
* 接口传参
* product_id:购买的商品ID
* product_num:购买的商品数量
* spec_value_id:购买的商品规格ID
*/
onConfirmSubmit() {
    let _this = this;
    let detail = _this.data.detail;
    // 提交数据
    let postData = {
        product_id: detail.aid,
        product_num: _this.data.product_num,
        spec_value_id: detail.spec_value_id ? detail.spec_value_id : 0
    };
    // 提交类型
    let submitType = _this.data.buttonType;
    // 加入购物车
    if ('addCart' == submitType) {
        App._requestPost(_this, App.globalData.config.shopAddCartUrl, postData,
            function(res) {
                _this.setData({
                    showBottomPopup: !_this.data.showBottomPopup,
                    cart_total_num: res.data.cart_total_num
                });
                App.showSuccess('已添加至购物车');
            },
            function(res) {
                App.showError(res.msg);
            }
        );
    }
    // 立即购买
    else if ('buyNow' == submitType) {
        App._requestPost(_this, App.globalData.config.shopBuyNowUrl, postData,
            function(res) {
                wx.redirectTo({ url: res.url });
            },
            function(res) {
                App.showError(res.msg);
            }
        );
    }
    // 确认规格选择
    else if ('specType' == submitType) {
        _this.setData({
            showBottomPopup: !_this.data.showBottomPopup
        })
    }
},

接口传值

product_id:购买的商品ID,必传

product_num:购买的商品数量,必传

spec_value_id:购买的商品规格ID,选填,无规格传0


文档最后更新时间:2026-01-13 11:59:49

文档
目录

深色
模式

切换
宽度