微信小程序开发中遇到的坑

博主也是一个新入坑的萌新,从上个月20多号开始开发微信小程序,总体感觉入手快,门槛低。

开发中使用的办法比较老土。

下面一一介绍下我在开发中遇到的问题与解决方法

1.下拉刷新与上拉加载

下拉刷新微信提供了api,直接去调用就好

代码:

 // 下拉刷新
  onPullDownRefresh: function() {
    wx.showNavigationBarLoading() //在标题栏中显示加载
    this.get_type_ent();  // 上拉需要执行的方法
    this.getData();       // 上拉需要执行的方法
    setTimeout(function() {
      wx.hideNavigationBarLoading() //完成停止加载
      wx.stopPullDownRefresh() //停止下拉刷新
    }, 1500);
  },

需要注意  开起下拉刷新需要在app.json 的window中配置 "enablePullDownRefresh": true 属性 如图:

如需单独一个页面开起下拉刷新则在需要的页面配置 "enablePullDownRefresh": true  不需要写window

上拉加载更多

这里我参照微信社区给出个的云开发列子自己修改了下

代码:

<!-- 推荐 wxml-->   
  <view class="recom">
    <view class="recom_tit">为你推荐</view>
    <!-- 商品 -->
    <view class="recom_box">
      <!-- 盒子 -->
      <!-- <scroll-view scroll-y="false" bindscrolltolower="searchScrollLower"> -->
        <view class="shop_box" wx:for="{{dataList}}" wx:key="{{index}}">
          <navigator url="/pages/com_detail/com_detail?id={{item.id}}" open-type="navigate">   // 点击进入商品详情 可忽略
            <view class="info_box">
              <!-- 商品图 -->
              <view class="info_img">
                //tools.split  图片切割 可忽略    
                <image class="img_r" src='{{tools.split(item.pics)}}'></image>  
              </view>
              <!-- 介绍 -->
              <view class="info_s">
                {{item.name}}
              </view>
              <!-- 价格 -->
              <view class="price_">
                ¥
                <text>{{item.price/100*item.discount}}</text>
              </view>
            </view>
          </navigator>
        </view>
        <view class="loading" hidden="{{!loadMore}}">正在载入更多...</view>
        <view class="loading" hidden="{{!loadAll}}">已加载全部</view>
      <!-- </scroll-view> -->
    </view>
  </view>
/* 推荐商品  wxss*/

.recom {
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.recom_tit {
  width: 100%;
  height: 70rpx;
  line-height: 70rpx;
  text-align: center;
  font-weight: 600;
  background: #fff;
  color: rgb(66, 144, 196);
  overflow: hidden;
}

/* 整个盒子 */

.recom_box {
  width: 100%;
  height: 100%;
  overflow: hidden;
  position: relative;
}

/* 外层盒子 */

.shop_box {
  width: 50%;
  height: 516rpx;
  float: left;
}

/* 内层盒子 */

.info_box {
  width: 94%;
  height: 500rpx;
  margin: 0 auto;
  background: #fff;
  border-radius: 4rpx;
}

/* 图片 */

.info_img {
  width: 100%;
  height: 362rpx;
}

.img_r {
  width: 100%;
  height: 100%;
}

/* 介绍 */

.info_s {
  width: 98%;
  height: 70rpx;
  font-size: 26rpx;
  color: #232326;
  overflow: hidden;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  padding: 1%;
}

/* 价格 */

.price_ {
  width: 100%;
  height: 52rpx;
  color: #f23030;
  font-size: 26rpx;
}

.price_ text {
  font-size: 32rpx;
}

.loading {
  width: 100%;
  height: 60rpx;
  position: absolute;
  bottom: -20rpx;
  padding: 10rpx;
  text-align: center;
  color: #999;
  font-size: 26rpx;
}

.result-item:first-child {
  border-top: 1px solid #e5e5e5;
}

.hr {
  width: 100%;
  height: 2rpx;
  background: #f5f5f5;
}
const app = getApp()
let page = 0 // 当前第几页,0代表第一页 
let limit = 10 //每页显示多少数据 
Page({
  /**
   * 页面的初始数据
   */
  data: {
    dataList: [], //放置返回数据的数组  
    loadMore: false, //"上拉加载"的变量,默认false,隐藏  
    loadAll: false, //“没有数据”的变量,默认false,隐藏  
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getData();
  },
  //页面上拉触底事件的处理函数
  onReachBottom: function() {
    console.log("上拉触底事件")
    let that = this
    if (!that.data.loadMore) {
      that.setData({
        loadMore: true, //加载中  
        loadAll: false //是否加载完所有数据
      });

      //加载更多,这里做下延时加载
      setTimeout(function() {
        that.getData()
      }, 1500)
    }
  },
  //访问网络,请求数据  
  getData() {
    let that = this;
    //第一次加载数据
    if (page == 1) {
      this.setData({
        loadMore: true, //把"上拉加载"的变量设为true,显示  
        loadAll: false //把“没有数据”设为false,隐藏  
      })
    }
    //云数据的请求
    wx.request({
      url: '',  //请求后端地址
      data: {
        page: 0,
        limit: limit,
        status: 1
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        if (res.data.data && res.data.data.length > 0) {
          limit += 10;   // 因为使用page增加有一点bug  我就直接改为每次添加10个数据
          //把新请求到的数据添加到dataList里  
          // let list = that.data.dataList.concat(res.data.data)
          that.setData({
            dataList: res.data.data, //获取数据数组    
            loadMore: false //把"上拉加载"的变量设为false,显示  
          });
          if (res.data.data.length < limit) {
            that.setData({
              loadMore: false, //隐藏加载中。。
              loadAll: true //所有数据都加载完了
            });
            setTimeout(function() {
              that.setData({
                loadAll: false
              })
            }, 1500)
          }
        } else {
          that.setData({
            loadAll: true, //把“没有数据”设为true,显示  
            loadMore: false //把"上拉加载"的变量设为false,隐藏  
          });
        }
      },
      fail(res) {
        console.log("请求失败", res)
        that.setData({
          loadAll: false,
          loadMore: false
        });
      }
    })
  },


})

后端数据格式因你的需求而定

2.配置全局属性

这里我只说一个 配置全局的wxid  很简单 在你的app.js中获取到wxid后保存到全局即可

App({    
  onLaunch: function() {
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        // console.log(res.code);
        wx.request({
          url: '地址?code=' + res.code,  //这里就是使用获取的code去得到你需要的信息
          method: 'POST',
          success: res => {
            // 设置为全局变量   我这里使用的名字是openId
            this.globalData.openId = res.data.data
          }
        })
      }
    })
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo
              // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })
  },
  globalData: {
    userInfo: null,
    openId: ''
  }
})

// 在其他页面使用
Page({
  data: {
    openId: '', // wxid
  },
onLoad(options) {
    let that = this;
    // 分享人wxid
    that.setData({
      openId: app.globalData.openId
    })
}
})

3.商品加入购物车或直接购买商品

首先我们得先获取到用户点击商品的完整信息  我这里是通过上一个用点击跳转方法传递一个商品id到本页面去获取该商品的值的方式 wx.navigateTo({url: '/pages/con_order/con_order?id=' + shopId,}) ,在本页面获取到该商品信息后显示到页面。

购物车数据我是直接把数据保存到缓存里面,进而在购物车页去获取即可,具体思路进入页面时先获取一次缓存,把获取到的数据保存到数组(list)里面,然后再点击加入购物车时判断list中是否包含该商品,如包含提示已包含或数量加1,我这里做的是提示已经包含,如不包含则把该商品加入到list中,最后把list保存到缓存中。(先获取缓存 —> 保存缓存数据—> 当前数据加入保存数据中 —> 把数据加入缓存)   

代码如下:

/const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: '', // 商品id
    name: '', // 商品名称
    price: '', // 商品价格
    num: 0, // 购物车商品件数
    shop_car: {}, // 当前选中商品信息
    shop_list: [], // 购物车缓存集合
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let that = this;
    that.setData({
      id: options.id
    })
    that.get_shop_info();  // 获取当前商品信息
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    // 取出缓存
    this.get_stor();
  },


  // 通过id获取商品信息
  get_shop_info: function() {
    let that = this;
    wx.request({
      url: '',  // 数据接口
      data: {
        page: 0,
        limit: 1,
        id: that.data.id,
        // id: 1,
        status: 1
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        that.setData({
          shop_car: res.data.data[0]
        })
      }
    })
  },


  // 设置缓存
  set_stor: function() {
    wx.setStorage({
      key: "shop_car_stor",  // 缓存数据键名
      data: this.data.shop_list  // 设置的缓存数据
    })
  },

  //  取出缓存
  get_stor: function() {
    let that = this;
    wx.getStorage({
      key: 'shop_car_stor',  // 缓存数据键名
      success(res) {
        that.setData({
          shop_list: res.data,  // 保存从缓存中取出的数据
          num: res.data.length  // 可忽略 商品个数
        })
      }
    })
  },

  // 添加到购物车

  add_shopcar: function() {
    let that = this;
    let list_ = that.data.shop_list;   // 缓存中取出的数据
    for (let i = 0; i < list_.length; i++) {   // 判断数组中是否包含当前商品
      if (list_[i].id == that.data.shop_car.id) {   
        wx.showToast({
          title: list_[i].name+'已经存在',
          icon: 'none',
          duration: 1500
        })
        return;
      }
    }
    // 不存在时 把当前上商品添加到数组中   把当前物品追加到购物车
    that.data.shop_list = that.data.shop_list.concat(that.data.shop_car); 
    that.setData({
      num: that.data.shop_list.length
    })
    // 加入缓存
    that.set_stor();
    wx.showToast({
      title: '加入购物车成功',
      icon: 'success',
      duration: 1500
    })
  },

})

具体思路就是这样  你在购物车页面使用或者缓存就行 。

直接购买更简单  直接把把id传到确认页即可  然后通过id获取即可

go_pay: function() {
    let shopId = this.data.id;
    setTimeout(function() {
      wx.navigateTo({
        url: '/pages/con_order/con_order?id=' + shopId,
      })
    }, 500)
  },

4.购物车中商品加减删除与计算总价格

首先,我们需要把缓存中的数据取出,然后进行相应操作。

思路  获取到缓存中数据后,在操作时,先用一个新的数组把原数据保存下来,操作新的数组,最后把新数组赋值给原数组。注意:操作多个数据时  需要求后端返回一个为布尔型的键值对。注:里面单选与多选是在阿里矢量图库找的两张图片,单选与全选还存在问题。

代码:

<wxs src="../../wxs/split.wxs" module="tools" />  // 切割数组

<view class="container">
  <!-- 商品信息 -->
  <view class="shop_box">
    <view class="{{shop_car.length<1?'hid':'shop_name'}}">阿克索健康商城</view>
    <!-- 一个商品 -->
    <view class="shop_info" wx:for="{{shop_car}}" wx:key="{{index}}">
      <view class="one_selet" data-index="{{index}}" catchtap="one_selet">
        <image src="{{item.boo?selet_url:no_selet_url}}"></image>
      </view>
      <view class="shop_img">
        // 因为我数据中有多张图片 只需要一张
        <image src="{{tools.split(item.pics)}}"></image> 
        //<image src="{{item.pics}}"></image>
      </view>
      <view class="info_">
        <view class="con_name">
          {{item.name}}
        </view>
        <view class="con_need">
          <view class="left_pri">
            ¥{{item.price/100*item.discount}}
          </view>
          <view class="right_num">
            <text class="red_" catchtap="{{itme.num=='1'?'':'red_num'}}" id="{{index}}">一</text>
            <input class="num_" type="number" value="{{item.num}}" disabled="disabled"></input>
            <text class="add_" catchtap="add_num" id="{{index}}">十</text>
          </view>
        </view>
      </view>
      <!-- 删除 -->
      <view class="del" data-id="{{item.id}}" catchtap="del_one_" id="{{index}}" data-id="{{item.id}}">
        <image src="../../images/shop/shanchu.png"></image>
      </view>
    </view>
    <view class="shop__" wx:if="{{shop_car.length<1}}">
      购物车空空如也,快去选购吧
    </view>
  </view>
  <!-- 底部结算 -->
  <view class="floot">
    <!-- 全选 -->
    <view class="all_select" catchtap="selet_all">
      <view class="img_">
        <image src="{{all_selet?selet_url:no_selet_url}}"></image>
      </view>
      <view class="tit_">
        全选
      </view>
    </view>
    <!-- 合计 -->
    <view class="all_money">
      合计:
      <text>¥{{all_price/100}}</text>
    </view>
    <!-- 去结算 -->
    <view class="go_pay" catchtap="go_pay">去结算</view>
  </view>
</view>
/* 商品信息 */

page {
  background: #eee;
}

.shop_box {
  width: 96%;
  height: 100%;
  margin: 0 auto;
  color: #333;
  overflow: hidden;
  overflow-y: scroll;
  margin-bottom: 90rpx;
}

.shop_name {
  width: 100%;
  height: 50rpx;
  line-height: 50rpx;
  font-weight: 600;
}

.shop_info {
  width: 100%;
  height: 150rpx;
  background: #fff;
  overflow: hidden;
  position: relative;
  border-radius: 6rpx;
  padding-bottom: 10rpx;
  margin-bottom: 20rpx;
}

.shop_info .one_selet {
  width: 10%;
  height: 100%;
  float: left;
  text-align: center;
  line-height: 175rpx;
}

.one_selet image {
  width: 50rpx;
  height: 50rpx;
}

.shop_info .shop_img {
  width: 20%;
  height: 100%;
  float: left;
  text-align: center;
}

.shop_img image {
  width: 90%;
  height: 95%;
}

.shop_info .info_ {
  width: 70%;
  height: 100%;
  float: left;
}

.con_name {
  width: 83%;
  padding: 1% 10% 2% 2%;
  font-size: 28rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
}

.con_need {
  width: 96%;
  height: 40%;
  padding: 2% 2% 1% 2%;
  overflow: hidden;
}

.left_pri {
  width: 65%;
  height: 100%;
  float: left;
  line-height: 60rpx;
  color: red;
}

.right_num {
  width: 35%;
  height: 100%;
  float: left;
  line-height: 60rpx;
}

.red_ {
  width: 29%;
  height: 100%;
  float: left;
  background: #f5f5f5;
  text-align: center;
  border-radius: 2rpx;
}

.num_ {
  width: 40%;
  height: 100%;
  float: left;
  text-align: center;
  margin: 0 1%;
  background: #f5f5f5;
  border-radius: 2rpx;
}

.add_ {
  width: 29%;
  height: 100%;
  float: left;
  text-align: center;
  background: #f5f5f5;
  border-radius: 2rpx;
}

.del {
  width: 40rpx;
  height: 40rpx;
  text-align: center;
  line-height: 50rpx;
  position: absolute;
  right: 10rpx;
  top: 10rpx;
}

.del image {
  width: 95%;
  height: 95%;
}

/* 底部购物车 */

.floot {
  width: 100%;
  height: 100rpx;
  position: fixed;
  bottom: 0;
  background: #f5f5f5;
  overflow: hidden;
  color: #333;
  z-index: 2
}

.all_select {
  width: 20%;
  height: 100%;
  float: left;
  text-align: center;
  overflow: hidden;
  line-height: 100rpx;
}

.all_select  .img_ {
  width: 42%;
  height: 100%;
  float: left;
}

.all_select  .tit_ {
  width: 58%;
  height: 100%;
  text-align: left;
  float: left;
}

.all_select  view image {
  width: 50rpx;
  height: 50rpx;
  padding-top: 24rpx;
}

.all_money {
  width: 53%;
  height: 100%;
  float: left;
  text-align: left;
  padding-left: 2%;
  line-height: 100rpx;
}

.all_money text {
  color: red;
}

.go_pay {
  width: 25%;
  height: 100%;
  float: right;
  background: darkcyan;
  text-align: center;
  line-height: 100rpx;
  color: #fff;
}

.shop__ {
  width: 100%;
  text-align: center;
  line-height: 100rpx;
  color: #333;
}

.hid {
  display: none;
}
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    selet_url: '../../images/shop/xz.png', // 选中时的图片
    no_selet_url: '../../images/shop/wxz.png', //未选中时的图片
    all_selet: false, // 是否全选
    one_selet: false, // 一个商品是否选中
    num: 1, // 当前选中商品数量
    shop_car: [], // 购物车商品数据
    all_price: 0, //总价

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let that = this;

    // 计算价格
    that.get_all_pri();

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    // 取出缓存
    this.get_stor();
  },

  // 设置缓存  为了支付页面使用
  set_stor: function() {
    wx.setStorage({
      key: "shop_car_stor",
      data: this.data.shop_car
    })
  },

  //  取出缓存
  get_stor: function() {
    let that = this;
    wx.getStorage({
      key: 'shop_car_stor',
      success(res) {
        that.setData({
          shop_car: res.data
        })
      }
    })
  },

  // 减少数量

  red_num: function(e) {
    let that = this;
    const index = parseInt(e.currentTarget.id); //获取当前的商品的索引值
    let shop_car = that.data.shop_car[index];
    let quantity = shop_car.num; //获取购买数量
    if (quantity == 1) {
      wx.showToast({
        title: '商品数量最小为1',
        icon: 'none',
        duration: 1000
      })

    } else {
      let shop_car = that.data.shop_car; //购物车所有的商品数据
      let quantity = shop_car[index].num; //获取购买数量
      quantity = quantity - 1; //将购买数量 +1
      shop_car[index].num = quantity; //更改当前商品的数量
      that.setData({
        shop_car: shop_car //更新商品数据
      });
    }

    // 计算价格
    that.get_all_pri();
    // 设置缓存
    that.set_stor()
  },

  // 增加数量
  add_num: function(e) {
    let that = this;
    const index = parseInt(e.currentTarget.id); //获取当前的商品的索引值
    let shop_car = that.data.shop_car; //购物车所有的商品数据
    let quantity = shop_car[index].num; //获取购买数量
    quantity = quantity + 1; //将购买数量 +1
    shop_car[index].num = quantity; //更改当前商品的数量
    that.setData({
      shop_car: shop_car //更新商品数据
    });

    // 计算价格
    that.get_all_pri();
    // 设置缓存
    that.set_stor()
  },

  // 全选

  selet_all: function() {
    let that = this;
    let checked = that.data.all_selet; //是否为全选状态
    checked = !checked; //改变状态
    let shop_car = that.data.shop_car; // 获取购物车商品信息
    for (let i = 0; i < shop_car.length; i++) {
      shop_car[i].boo = checked; // 改变所有商品状态
      if (!shop_car[i].boo) {
        all_selet: false
      }
    }

    that.setData({
      all_selet: checked, //更新全选状态
      shop_car: shop_car //更新所有商品的状态
    })
    // 重新计算价格
    that.get_all_pri();
    // 设置缓存
    that.set_stor()
  },

  // 单选

  one_selet: function(e) {
    let that = this;
    var index = e.currentTarget.dataset.index //获取索引值
    let shop_car = that.data.shop_car; //  获取购物车列表
    const checks = shop_car[index].boo; // 获取购物车当前选中状态
    shop_car[index].boo = !checks; //  改变当前选中状态

    that.setData({
      shop_car: shop_car // 重新设置商品选中状态
    })

    // 重新计算价格
    that.get_all_pri();
    // 设置缓存
    that.set_stor()
  },

  // 删除单个商品

  del_one_: function(e) {
    let that = this;
    const index = parseInt(e.currentTarget.id); //获取索引值
    let shop_car = that.data.shop_car[index]; //  获取购物车列表
    wx.showModal({
      title: '提示',
      content: '确定将' + shop_car.name + '移除购物车吗?',
      success: function(res) {
        if (res.confirm) {
          var tempData = that.data.shop_car; //所有商品数据
          tempData.splice(index, 1); //从当前索引值开始删除1项数据
          that.setData({
            shop_car: tempData //更新数据
          })
          wx.showToast({
            title: '删除成功',
            icon: 'success',
            duration: 1000
          })
        } else {
          console.log('用户点击取消')
        }
        // 重新计算价格
        that.get_all_pri();
        // 设置缓存
        that.set_stor()
      },
    })
  },

  // 计算总价格

  get_all_pri: function() {
    let that = this;
    let shop_car = that.data.shop_car; // 获取购物车列表
    let total = 0; // 保存价格
    for (let i = 0; i < shop_car.length; i++) { // 循环列表得到每个数据
      if (shop_car[i].boo) { // 判断选中才会计算价格
        total += shop_car[i].num * shop_car[i].price * shop_car[i].discount; // 所有价格加起来
      }
    }
    that.setData({
      shop_car: shop_car,
      all_price: total.toFixed(2),
    })
  },

  // 去结算
  go_pay: function() {
    let that = this;
    // 设置缓存;
    that.set_stor();
    if (that.data.all_price > 0) {
      wx.navigateTo({
        url: '/pages/con_order/con_order?all_price='+that.data.all_price,
      })
    } else {
      wx.showToast({
        title: '您还没有选择需要购买的商品',
        icon: 'none',
        duration: 1500
      })
    }
  }
})

5.微信支付 前端

微信支付大多功能都是后端在做,而我们只需要去调用他的接口即可,我给大家说下微信支付的前端代码应该怎么写。

const app = getApp()

// pages/con_order/con-order.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: '', // 商品id
    shop_car: [], // 商品信息
    shop_false: [], // 商品中未购买的商品
    all_price: '', // 总价
    openid: '', // 用户wxid
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let that = this;
    // 获取值
    that.setData({
      id: options.id, // 单独购买一件商品id
      all_price: options.all_price, // 总价
      openid: app.globalData.openId, // wxid
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    let that = this;
    // 获取商品订单信息
    that.get_order_info()
  },

  // 设置缓存
  set_stor: function() {
    wx.setStorage({
      key: "shop_car_stor",
      data: this.data.shop_false
    })
  },

  //  取出缓存
  get_stor: function() {
    let that = this;
    wx.getStorage({
      key: 'shop_car_stor',
      success(res) {
        let shop_car = []; // 当前选中购买的商品
        let shop_false = []; // 当前未选中的商品
        let j = 0;
        let k = 0;
        for (let i in res.data) {   // 把需要购买的商品与不需要购买的商品分开保存
          if (res.data[i].boo == true) {
            shop_car[j++] = res.data[i];
          } else if (res.data[i].boo == false) {
            shop_false[k++] = res.data[i];
          }
        }
        that.setData({
          shop_car: shop_car,  // 需要购买商品
          shop_false: shop_false  // 不需要购买商品
        })

        console.log('选中:', that.data.shop_car);
        console.log('未选中:', that.data.shop_false);
      }
    })
  },


  // 获取订单商品信息
  get_order_info: function() {
    let that = this;
    // 判断用户是通过购物车进入还是单个商品进入
    if (that.data.id) {
      wx.request({
        url: '',  // 通过id获取当前需要购买商品的信息
        method: 'GET',
        data: {
          page: 0,
          limit: 1,
          status: 1,
          id: that.data.id,
        },
        success: function(res) {
          that.setData({
            shop_car: res.data.data,
            all_price: res.data.data[0].price * res.data.data[0].num * res.data.data[0].discount
          })
        }
      })
    } else {
      that.get_stor();
    }
  },

  // 支付
  pay_: function() {
    let that = this;
    let shop_ = that.data.shop_car;
    let shop_list = [];
    let openid = that.data.openid;
    // console.log(that.data.openid);
    let list = "[";
    for (let i = 0; i < shop_.length; i++) {
      list += "{'id':" + shop_[i].id + "," + "'num':" + shop_[i].num + "}";
      if (i < shop_.length - 1) {
        list += ","
      }
    }
    list += "]"
    // 提交订单 获取订单信息  支付
    wx.request({
      url: 'https://aksojk.com/item/getOrder?addrId=' + that.data.addr_id + '&items=' + list + '&openid=' + openid,
      method: 'POST',
      success(res) {
        let id = res.data.data.id;
        let discountPrice = res.data.data.discountPrice;
        let wxId = res.data.data.wxId;

        console.log(discountPrice);
        //统一下单
        wx.request({
          url: 'https://aksojk.com/item/pay?id=' + id + '&discountPrice=' + discountPrice + '&wxId=' + wxId,
          method: 'POST',
          success(res) {
            // console.log(res.data.data)
            let orderId = res.data.data.orderId;
            let obj = res.data.data;
            if (res.statusCode === 200) {
              wx.requestPayment({
                'timeStamp': obj.timeStamp,
                'nonceStr': obj.nonceStr,
                'package': obj.package,
                'signType': 'MD5',
                'paySign': obj.paySign,
                'success': function(res) {
                  // 支付成功
                  wx.request({
                    url: 'https://aksojk.com/item/pay/call/back?orderId=' + orderId,
                    method: 'POST',
                    success(res) {
                      // 去除已经购买成功商品
                      setTimeout(function() {
                        that.set_stor()
                      }, 1000);
                      // 支付成功提示
                      wx.showToast({
                        title: '支付成功',
                        duration: 1000
                      })
                      // 支付成功后跳转到订单页
                      wx.switchTab({
                        url: '/pages/order/order'
                      })
                    },
                    fail(res) {
                      wx.showToast({
                        title: '支付失败',
                        duration: 1500
                      })
                    }
                  })
                },
                'fail': function(res) {
                  console.log('fail');
                  console.log(res);
                  wx.showToast({
                    title: '取消支付',
                    icon: 'none'
                  })
                },
                'complete': function(res) {
                  console.log('complete');
                  console.log(res);
                }
              })

            } else {
              wx.showToast({
                title: '下单失败',
                icon: 'none'
              })
            }
          }
        })
      },
      fail(res) {
        console.log(res);
      }
    })
  },
})

微信支付  前端非常简单 主要都是后端在实现。

如有什么问题与我联系

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值