【愚公系列】2022年10月 微信小程序-电商项目-用户自动登录功能实现

举报
愚公搬代码 发表于 2022/10/31 19:24:17 2022/10/31
【摘要】 前言登录组件的封装代码Component({ options: { multipleSlots: false }, properties: { show: { type: Boolean, value: false } }, observers: { 'show': function (value) { console.log...

前言

登录组件的封装代码



Component({
  options: {
    multipleSlots: false
  },
  properties: {
    show: {
      type: Boolean,
      value: false
    }
  },
  observers: {
    'show': function (value) {
      console.log(value);

      this.setData({
        visible: value
      })
    }
  },
  data: {
    visible: false
  },
  ready() {},
  methods: {
    close(e) {
      this.setData({
        visible: false
      })
    },
    async login(e, retryNum = 0) {
      let {
        userInfo,
        encryptedData,
        iv
      } = e.detail

      // 本地token与微信服务器上的session要分别对待
      let tokenIsValid = false, sessionIsValid = false
      let res0 = await getApp().wxp.checkSession().catch(err=>{
        // 清理登陆状态,会触发该错误
        // checkSession:fail 系统错误,错误码:-13001,session time out…d relogin
        console.log("err",err);
        tokenIsValid = false
      })
      console.log("res0", res0);
      if (res0 && res0.errMsg === "checkSession:ok") sessionIsValid = true
      let token = wx.getStorageSync('token')
      if (token) tokenIsValid = true

      if (!tokenIsValid || !sessionIsValid) {
        let res1 = await getApp().wxp.login()
        let code = res1.code
        console.log("code",code);
        
        let res = await getApp().wxp.request({
          url: `${getApp().wxp.URL_BASE}/user/wexin-login2`,
          method: 'POST',
          header: {
            'content-type': 'application/json',
            'Authorization': `Bearer ${token || ''}`
          },
          data: {
            code,
            userInfo,
            encryptedData,
            iv,
            sessionKeyIsValid:sessionIsValid
          }
        })
        
        if (res.statusCode == 500){
          if (retryNum < 3){
            this.login.apply(this, [e, ++retryNum])
          }else{
            wx.showModal({
              title: '登录失败',
              content: '请退出小程序,清空记录并重试',
            })
          }
          return
        }
        // Error: Illegal Buffer at WXBizDataCrypt.decryptData
        console.log('登录接口请求成功', res.data)
        token = res.data.data.authorizationToken
        wx.setStorageSync('token', token)
        console.log('authorization', token)
      }

      getApp().globalData.token = token
      wx.showToast({
        title: '登陆成功了',
      })
      this.close()
      this.triggerEvent('loginSuccess')
      getApp().globalEvent.emit('loginSuccess')

    },
    login2(e) {
      let {
        userInfo,
        encryptedData,
        iv
      } = e.detail
      // console.log('userInfo', userInfo);

      const requestLoginApi = (code) => {
        //发起网络请求
        wx.request({
          url: 'http://localhost:3000/user/wexin-login2',
          method: 'POST',
          header: {
            'content-type': 'application/json'
          },
          data: {
            code: code,
            userInfo,
            encryptedData,
            iv
          },
          success(res) {
            console.log('请求成功', res.data)
            let token = res.data.data.authorizationToken
            wx.setStorageSync('token', token)
            onUserLogin(token)
            console.log('authorization', token)
          },
          fail(err) {
            console.log('请求异常', err)
          }
        })
      }

      const onUserLogin = (token) => {
        getApp().globalData.token = token
        wx.showToast({
          title: '登陆成功了',
        })
        this.close()
        this.triggerEvent('loginSuccess')
        getApp().globalEvent.emit('loginSuccess')
      }

      const login = () => {
        wx.login({
          success(res0) {
            if (res0.code) {
              requestLoginApi(res0.code)
            } else {
              console.log('登录失败!' + res0.errMsg)
            }
          }
        })
      }

      wx.checkSession({
        success() {
          //session_key 未过期,并且在本生命周期一直有效
          console.log('在登陆中');
          let token = wx.getStorageSync('token')
          if (token) {
            onUserLogin(token)
          } else {
            // session会重复,需要处理
            login()
          }
        },
        fail() {
          // session_key 已经失效,需要重新执行登录流程
          login()
        }
      })

    }
  }
})
{
  "component": true,
  "usingComponents": {
    "van-popup": "@vant/weapp/popup/index"
  }
}

<van-popup show="{{visible}}" position="bottom" 
custom-style="min-height:200px;background-color: #efefef;">
		<view class="picker-view">
			<view class="picker-view__pane">
				<text bindtap="close">取消</text>
			</view>
			<view style="font-size:17px;font-weight:bold;line-height:30px;border-bottom:1px solid #f2f2f2;padding: 0px 0 20px;width: 100%;color:#353535;text-align: center;">微信授权登录</view>
			<image style="width: 40px;height: 40px;padding-top: 20px;" src="/static/image/component-on.png"></image>
			<view style="font-size:17px;font-weight:400;color:#353535;line-height: 40px;">小程序将申请获取以下权限</view>
			<view style="font-size:11px;color:#b2b2b2;border-bottom:1px solid #f2f2f2;width: 100%;padding: 0px 0 40px;text-align: center;">● 获得你的公开信息(昵称、头像、地区及性别)</view>
			<view style="height:80px;padding-top: 20px;">
				<button bindgetuserinfo="login" open-type="getUserInfo" type="primary">登陆</button>
			</view>
		</view>
</van-popup>

.picker-view {
  width: 100%;
  display: flex;
  background-color: #fff;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  bottom: 0rpx;
  left: 0rpx;
}

.picker-item {
  line-height: 70rpx;
  margin-left: 5rpx;
  margin-right: 5rpx;
  text-align: center;
}

.picker-view__pane {
  height: 100rpx;
  width: 100%;
  padding: 20rpx 32rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: border-box;
}

.picker-view__pane text{
  color: #00cc88;
  font-size: 30rpx;
}

.pick-view__group {
  width: 96%;
  height: 450rpx;
}

一、商品详情页面规格选择功能实现

<!--pages/goods/index.wxml-->
<swiper indicator-dots style="height:300px;">
	<block wx:for="{{goodsImages}}" wx:key="*this">
		<swiper-item>
			<van-image lazy-load loading="loading" fit="cover" width="100%" height="300" src="{{item.content}}" />
		</swiper-item>
	</block>
</swiper>
<!-- 标题及价格 -->
<view style="background-color:white;padding: 10px 15px 0;font-family:'微软雅黑'">
	<view style="color:#C0A769;">
		<text style="font-size:11px;"></text>
		<text style="font-size:18px;">{{goodsData.start_price}}</text>
	</view>
	<van-row>
		<van-col span="16">
			<view style="color:black;font-size:16px;">{{goodsData.goods_name}}</view>
		</van-col>
		<van-col span="8" style="text-align:right;">
			<view class="iconfont icon-share share"> 分享</view>
		</van-col>
	</van-row>
	<view style="color:#939697;font-size:11px;">{{goodsData.goods_desc}}</view>
</view>
<!-- 运费说明 -->
<van-cell-group border="{{false}}">
	<van-cell class="buydesc" title="全程护航,请放心购买" is-link />
</van-cell-group>

<van-cell-group title=" ">
	<van-cell value="" is-link>
		<view slot="title">
			<text style="float: left;padding-right: 10px;font-size: 13px;color: gray;">运费</text>
			<view>免运费</view>
		</view>
	</van-cell>
</van-cell-group>
<!-- 商品规格 -->
<van-cell-group title=" ">
	<van-cell value="" is-link>
		<view slot="title">
			<text style="float: left;padding-right: 10px;font-size: 13px;color: gray;">服务</text>
			<view>收货后结算</view>
		</view>
	</van-cell>
	<van-cell value="" is-link bind:click="showSkuPanelPopup">
		<view slot="title">
			<text style="float: left;padding-right: 10px;font-size: 13px;color: gray;">规格</text>
			<view>
				{{selectedGoodsSkuObject.text || "选择"}}
			</view>
		</view>
	</van-cell>
</van-cell-group>
<!-- 商品描述 -->
<view style="padding:10px 10px 100px;">
  <van-image wx:for="{{goodsImages}}" wx:key="content" lazy-load loading="loading" fit="cover" width="100%" height="300" src="{{item.content}}" />
  <text>{{goodsContentInfo.content}}</text>
</view>
<!-- 购物车 -->
<van-goods-action>
  <van-goods-action-icon icon="cart-o" text="购物车" info="0" />
  <van-goods-action-icon icon="shop-o" text="店铺" />
  <van-goods-action-button bindtap="addToCart" text="加入购物车" type="warning" />
  <van-goods-action-button text="立即购买" />
</van-goods-action>
<!-- 商品规格 -->
<van-popup show="{{showSkuPanel}}" closeable position="bottom" round custom-style="min-height:200px;background-color: #efefef;" bind:close="onCloseSkuPanel">
	<view style="width:100%;background-color: #efefef;display:flex;padding:10px 10px 0;">
		<view>
			<image style="width:100px;height:100px;border-radius:5px;" src="{{goodsImages[0].content}}" />
		</view>
		<view style="flex:1;padding-left:10px;color: gray;padding-top: 10px;">
			<view>价格:{{selectedGoodsSku.price/100}}</view>
			<view>库存:{{selectedGoodsSku.stock}}</view>
			<view>规格:
				<text wx:for="{{goodsSkuData.goodsAttrKeys}}" wx:key="attr_key" style="padding-right:5px;">{{selectedAttrValue[item.attr_key].attr_value}}</text>
			</view>
		</view>
	</view>
	<block wx:for="{{goodsSkuData.goodsAttrKeys}}" wx:key="attr_key">
		<van-cell-group title=" ">
			<van-cell>
				<view slot="title">
					<view class="van-cell-text">{{item.attr_key}}</view>
					<block wx:for="{{item.goods_attr_values}}" wx:for-item="item2" wx:key="attr_value">
						<van-tag bindtap="onTapSkuTag" data-attrvalue="{{item2}}" data-attrkey="{{item.attr_key}}" plain="{{item2.id!=selectedAttrValue[item.attr_key].id}}" type="primary">{{item2.attr_value}}</van-tag>
					</block>
				</view>
			</van-cell>
		</van-cell-group>
	</block>
	<van-button bindtap="onConfirmGoodsSku" type="primary" size="large">确定</van-button>
</van-popup>
<!-- 登录组件 -->
<button bindtap="requestHomeApiByReq4" type="primary">测试登陆</button>
<LoginPanel show="{{showLoginPanel}}"></LoginPanel>
/* pages/goods/index.wxss *//* miniprogram/pages/goods/index.wxss */
.price .van-cell__title{
  color: rgba(181,154,81,1);
  font-size: 20pt;
}
.title .van-cell__title{
  font-size: 17pt;
}
.buydesc .van-cell__title{
  font-size: 13px;
}
.share{
  font-size:11px;background-color:#F5F9FA;color:#767A7B;border-radius:30px;padding: 5px 10px;margin-right: -27px;width: 50px;text-align: center;float: right;
}
.van-tag{
  margin-left: 10px;
}
.van-popup{
  background-color: #efefef;
}
// miniprogram/pages/goods/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showLoginPanel:false,
    showSkuPanel: false,
    goodsId:0,
    goodsData:{},
    goodsImages: [],
    goodsContentInfo:{},
    goodsSkuData:{},
    selectedGoodsSku:{},
    selectedAttrValue:{},
    selectedGoodsSkuObject:{}
  },

   /**
   * 登录功能实现
   * @param {*} e 
   */
  requestHomeApiByReq4(e){
    getApp().wxp.request4({
      url: 'http://localhost:3000/user/home',
      onReturnObject(rtn){
        // rtn.abort()
      }
    }).catch(err=>{
      console.log(err);
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    let goodsId = options.goodsId
    this.data.goodsId = goodsId
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.on('goodsData', (res)=> {
      console.log(res)
      let goodsImages = res.data.goods_infos.filter(item=>(item.kind == 0))
      let goodsContentInfo = res.data.goods_infos.filter(item=>(item.kind == 1))[0]

      this.setData({
        goodsData:res.data,
        goodsImages,
        goodsContentInfo
      })
    })
    // 拉取sku规格数据
    let goodsSkuDataRes = await wx.wxp.request({
      url: `http://localhost:3000/goods/goods/${goodsId}/sku`,
    })
    if (goodsSkuDataRes){
      let goodsSkuData = goodsSkuDataRes.data.data 
      this.setData({
        goodsSkuData
      })
    }
  },
  // 显示规格面板
  showSkuPanelPopup() {
    this.setData({ showSkuPanel: true });
  },
  
  // 关闭规格面板
  onCloseSkuPanel(){
    this.setData({ showSkuPanel: false });
  },
  //选择商品规格
  onTapSkuTag(e){
    // 获取及设置选择的规格
    let attrvalue = e.currentTarget.dataset.attrvalue
    let attrKey = e.currentTarget.dataset.attrkey

    console.log('attrvalueid',attrvalue,attrKey);
    let selectedAttrValue = this.data.selectedAttrValue
    selectedAttrValue[attrKey] = attrvalue
    this.setData({
      selectedAttrValue
    })
    // 计算价格及库存
    let totalIdValue = 0
    let goodsAttrKeys = this.data.goodsSkuData.goodsAttrKeys
    for (let j=0;j<goodsAttrKeys.length;j++){
      let attrKey = goodsAttrKeys[j].attr_key
      if (selectedAttrValue[attrKey]){
        totalIdValue+=selectedAttrValue[attrKey].id
      }
    }
    console.log("totalIdValue", totalIdValue);
    
    let goodsSku = this.data.goodsSkuData.goodsSku
    let tempTotalIdValue = 0

    for(let j=0;j<goodsSku.length;j++){
      let goodsAttrPath = goodsSku[j].goods_attr_path 
      if (goodsAttrPath.length != goodsAttrKeys.length){
        break
      }
      tempTotalIdValue = 0
      goodsAttrPath.forEach(item=>tempTotalIdValue += item)
      console.log("tempTotalIdValue",tempTotalIdValue);

      if (tempTotalIdValue == totalIdValue){
        let selectedGoodsSku = goodsSku[j]
        this.setData({
          selectedGoodsSku
        })
        break;
      }
    }
  },

  // 确定选择当前规格
  onConfirmGoodsSku(){
    let goodsSkuData = this.data.goodsSkuData
    let selectedGoodsSkuObject = this.data.selectedGoodsSkuObject
    selectedGoodsSkuObject.sku = Object.assign({}, this.data.selectedGoodsSku)
    selectedGoodsSkuObject.text = ''
    for (let j=0;j<goodsSkuData.goodsAttrKeys.length;j++){
      let item = goodsSkuData.goodsAttrKeys[j]
      if (!this.data.selectedAttrValue[item.attr_key]){
        wx.showModal({
          title: '没有选择全部规格',
          showCancel:false
        })
        return
      }
      selectedGoodsSkuObject.text += this.data.selectedAttrValue[item.attr_key].attr_value + ' '
    }
    this.setData({
      selectedGoodsSkuObject,
      showSkuPanel: false
    })
  },
  // 添加商品到购物车
  async addToCart(e){
    if (!this.data.selectedGoodsSkuObject.sku){
      wx.showModal({
        title: '请选择商品规格',
        showCancel: false
      })
      this.showSkuPanelPopup()
      return
    }
    let goods_id = this.data.goodsId
    let goods_sku_id = this.data.selectedGoodsSkuObject.sku.id 
    let goods_sku_desc = this.data.selectedGoodsSkuObject.text
    let data = {
      goods_id,
      goods_sku_id,
      goods_sku_desc
    }
    let res = await getApp().wxp.request4({
      url:'http://localhost:3000/user/my/carts',
      method:'post',
      data
    })
    if (res.data.msg == 'ok'){
      wx.showToast({
        title: '已添加',
      })
    }
  },
})
{
  "usingComponents": {
    "van-image": "@vant/weapp/image/index",
    "van-row": "@vant/weapp/row/index",
    "van-col": "@vant/weapp/col/index",
    "van-cell": "@vant/weapp/cell/index",
    "van-cell-group": "@vant/weapp/cell-group/index",
    "van-popup": "@vant/weapp/popup/index",
    "van-button": "@vant/weapp/button/index",
    "van-tag": "@vant/weapp/tag/index",
    "van-goods-action": "@vant/weapp/goods-action/index",
    "van-goods-action-icon": "@vant/weapp/goods-action-icon/index",
    "van-goods-action-button": "@vant/weapp/goods-action-button/index",
    "LoginPanel":"../../components/login"
  }
}

二、效果

在这里插入图片描述

【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。