微信小程序业务 手摸手教学

目录

一、自动检测版本更新

示例代码

二、微信登录

实现步骤

示例代码 

 页面效果

三、微信订阅消息

实现步骤

示例代码 

页面效果

四、微信支付

官方示例代码

项目相关代码


涵盖微信登录(静默)、微信支付、微信订阅消息等持续更新、

一、自动检测版本更新

  • 示例代码

  • 放置于全局文件 app.js , onLaunch生命周期中
const updateManager = wx.getUpdateManager()

updateManager.onUpdateReady(function () {
  wx.showModal({
    title: '更新提示',
    content: '新版本已经准备好,是否重启应用?',
    success: function (res) {
      if (res.confirm) {
        // 调用 applyUpdate 应用新版本并重启
        updateManager.applyUpdate()
      }
    }
  })
})

二、微信登录

实现步骤

  • 当前的授权状态 => 已授权 => 实现静默登录
  • 未授权 => 先授权 => 再进行登录
  • 低版本需做兼容处理

示例代码 

<!--pages/authorize/page.wxml-->
<view class="authorize">
  <view class="grant">
    <view class="avatar">
      <open-data type="userAvatarUrl" default-avatar="https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132"></open-data>
    </view>
    <view class="name">
      <open-data type="userNickName"></open-data>
    </view>
    <view wx:if="{{canIUse}}" class="opera">
      <button class="btn" wx:if="{{canIUseGetUserProfile}}" bindtap="getUserProfile">微信授权登录</button>
      <button class="btn" wx:else open-type="getUserInfo" bindgetuserinfo="bindGetUserInfo">微信授权登录</button>
      <button class="btn small btn-gray-text btn-cancel" bindtap="onTapCancel">暂不授权</button>
    </view>
    <view wx:else class="placeholder">请升级微信版本</view>
  </view>
</view>
/* pages/authorize/page.wxss */
.authorize {
  position: fixed;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  background-color: #fff;
  z-index: 101;
}

.authorize .grant {
  position: absolute;
  top: 50%;
  left: 0;
  width: 100%;
  margin-top: -450rpx;
}

.authorize .grant .avatar {
  height: 200rpx;
  width: 200rpx;
  margin: 0 auto;
  -webkit-border-radius: 50%;
  -moz-border-radius: 50%;
  border-radius: 50%;
  overflow: hidden;
}

.authorize .grant .name {
  height: 160rpx;
  line-height: 160rpx;
  text-align: center;
  font-size: 16px;
  font-weight: 500;
}

.authorize .grant .opera {
  padding: 0 10%;
  text-align: center;
}

.btn {
  background-color: rgb(0, 45, 128);
  border: none;
  color: #fff;
  min-height: auto !important;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  font-size: 28rpx;
  padding: 0;
  width: 100%;
  font-weight: normal;
  transition: all 0.2s;
  border-radius: 40rpx;
}

.btn.btn-cancel {
  display: inline-block;
  color: #b2b2b2;
  margin-top: 100rpx;
}

.btn:after {
  border: none;
  display: none;
}
.btn.btn-gray-text {
  color: #9a9a9a;
  background-color: transparent;
}

.btn.small{
  height: 60rpx;
  line-height: 60rpx;
  width: auto;
  padding: 0 30rpx;
  text-align: center;
  font-size: 28rpx;
}
const util = require('../../utils/util')
const api= require('../../config/api')
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo'), 
    code:null,
    canIUseGetUserProfile: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    
    this.reloadWxCode()
    
    if(wx.getUserInfo){
      this.setData({
        canIUseGetUserProfile:true
      })
    }
    let that = this;
    // 获取用户当前的授权状态
    wx.getSetting({
      success: function (res) {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权,可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            withCredentials: true,
            lang: 'zh_CN',
            success: function (res) {
              that.onGetUserInfo(res);
            },
          });
        }
      },
    });
  },

  // 统一调用登录接口
  onGetUserInfo(value){
    if(!value)return
    var _this = this;
    let loading = false //定义一个变量来判断是否loading

    if(!loading){
      wx.showLoading({
        title: '登陆中..',
        mask:true
      })
      loading = true
    }
    
 
    // 调用登录接口
    let params = {
      code:_this.data.code, //code
      userInfo:value //用户信息
    }
    // 登录接口
    util.request(api.loginApi,params,'POST').then(res=>{
        //存储用户信息
      if (res.errno == 0) {
        wx.setStorageSync('userInfo', res.account);
        wx.setStorageSync('token', res.token.access_token);

        app.globalData.isLogin = true //修改登录状态
        setTimeout(() => {
          if(loading){
            wx.hideLoading();
            loading = false
        }
          util.toast('登录成功')
        }, 600);
        wx.reLaunch({
          url: '/pages/index/index',
        })
       
      }
    
    
  }).catch(err=>{
    app.globalData.isLogin = false;
    util.showErrorToast('微信登录失败');
  })
  },
  // 获取code
  reloadWxCode(){
    let _that = this;
    wx.login({
      success: (res) => {
        _that.setData({
          code:res.code
        })
      },
    })
  },
  // 取消授权
  onTapCancel(){
    var _this = this;
    wx.showModal({
      title: '确定要暂不授权吗?授权可以提供更便捷,快速的服务',
      success: (res) => {
        if (!res.confirm) {
          return
        }
        // 不授权,跳转到首页,让code失效
        wx.switchTab({
          url:"/pages/index/index",
        })
        _this.reloadWxCode()
      }
    })
  },
  // 新版
  getUserProfile: function() {
    var that = this;
    wx.getUserProfile({
      lang: 'zh_CN',
      desc: '展示微信图像、昵称、性别及地区', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
      success: (res) => {
        let userInfo = res.userInfo
       that.onGetUserInfo(userInfo);
      },fail: (err) => {
        console.log(err);
      }
    })
  },
  
  // 旧版
  bindGetUserInfo: function (e) {
    let userInfo = e.detail.userInfo
    if (!userInfo) { 
      app.globalData.isLogin = true
      return;
    }
    this.onGetUserInfo(userInfo);
  },


})

 页面效果

三、微信订阅消息

一次性订阅消息使用方法详见 wx.requestSubscribeMessage,永久订阅消息(仅小游戏可用)使用方法详见wx.requestSubscribeSystemMessage  

实现步骤

  1. 前后端协作, 调用后端接口, 获取所有的模板消息队列(方便管理)
  2. 封装一个复用函数, 用于统一发送处理订阅消息 wx.requestSubscribeMessage

示例代码 

  • 后端返回模板消息队列

  •  自定义工具函数
// 定义一个订阅消息的函数
const subscribeMessage = (templateSubArr) => {
  // 拦截空参数
  if (Array.isArray(templateSubArr) && templateSubArr.length === 0) return

  //获取用户的当前设置
  wx.getSetting({
    withSubscriptions: true,
    success(res) {
      if (res.errMsg === 'getSetting:ok' && res.subscriptionsSetting.mainSwitch) {
        wx.requestSubscribeMessage({
          tmplIds: templateSubArr,
          success(res) {
            console.log(res);
          },
          complete(err) {
            console.log(err);
          }
        })
      } else {
        // 不允许总是授权
        wx.showModal({
          title: '提示',
          content: '请授权开通服务通知',
          complete: (res) => {
            if (res.confirm) {
              wx.openSetting({
                success(res) {
                  console.log("success", res)
                },
                fail(res) {
                  console.log("fail", res)
                }
              })
            }
          }
        })
      }
    }
  })
};
  • 页面调用
 onoilCard() {
    let templateId1 = 'insert_oil_pay_notice' //加油支付提醒
    let templateId2 = 'member_binding_ic_card_notice' //会员绑定IC卡消息提醒
    let templateId3 = 'ic_card_month_consumer_notice' //交易统计通知
    let templateList = app.globalData.templateList // 消息模板对队列数组
    let templateSubArr = templateList.filter(ele => [templateId1, templateId2, templateId3].includes(ele.wxTemplateType))
      .map(ele => ele.templateId)
        
   // 此处调用订阅消息函数
    util.subscribeMessage(templateSubArr)

    const { account } = this.data
    if (!account) return
    wx.navigateTo({
      url: `/packageA/pages/oil_card/oil_card?accountId=${account.accountId}`,
    })
  },

页面效果

四、微信支付

通过 wx.requestPayment(Object object) 发起微信支付

官方示例代码

wx.requestPayment({
  timeStamp: '',
  nonceStr: '',
  package: '',
  signType: 'MD5',
  paySign: '',
  success (res) { },
  fail (res) { }
})
  • 逻辑: 通过传递用户信息, 调用后端接口 换取支付相关参数
  • 传递参数于 wx.requestPayment(params), 发起支付请求
  • 在success, 以及fail中做逻辑判断 比如(loading 提示, 页面跳转)

项目相关代码

onPay:function(){
    const obj = {
         // 参数
    }
    util.request(api.rechargePaymentApi,obj,'POST').then(res=>{
      if(res.code == 200){
        const wxPayParameters = JSON.parse(res.data.payInfo)
        const id = res.data && res.data.id
        const params = {
          // timeStamp:'',//时间戳
          // nonceStr:'',//随机字符串
          // package:'',//统一下单接口返回的 prepay_id 参数值,提交格式如:prepay_id=**
          // signType: 'MD5',//签名算法
          // paySign:'',//签名
          ...wxPayParameters,
          success: function (res) {
            console.log(res,'调用支付');
            if (res.errMsg !== 'requestPayment:ok') {
              util.toast('支付失败');
              return;
            }
            util.toast('已支付等待确认');
            setTimeout(function () {
              wx.reLaunch({
                url:`/packageA/pages/pay_finish/pay_finish?id=${id}`//支付完成, 页面跳转
              });
            }, 2000);
          },
          fail: function (res) {
            console.log(res,'调用支付失败');
            if (res.errMsg === 'requestPayment:fail cancel') {
              return;
            }
            util.toast('调用支付失败');
          },
        }
       
        wx.requestPayment(params)
     }else{
       util.toast(res.msg)
     }
    })

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值