聊一聊小程序内嵌H5-单点登录

116 阅读1分钟

不爱讲废话,直接贴代码(相关说明已在对应代码中加注解)

// 获取链接参数
getUrlParam(name) {
    const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    const r = window.location.search.substr(1).match(reg); //匹配目标参数
    if (r != null) return unescape(r[2]);
    return null; //返回参数值
}
autoH5Login() {
    let mobile = this.getUrlParam('mobile') || Taro.getStorageSync('mobile') || null
    let openId = this.getUrlParam('openId') || Taro.getStorageSync('openId') || null
    if (this.getUrlParam('mobile')) {
      // 更新相关storage
      Taro.setStorageSync('mobile', this.getUrlParam('mobile'))
    }
    if (this.getUrlParam('openId')) {
      // 更新相关storage
      Taro.setStorageSync('openId', this.getUrlParam('openId'))
    }
    let targetPagePath = this.getUrlParam('targetPage') // 获取跳转链接目标页面path
    // 注:signature api防篡改签名验签方法,可以封装到api中,默认添加验签,设置needSign灵活变量
    let params = signature({
      ReqTime: new Date().getTime(),
      Mobile: mobile,
      AppId: appId,
      OpenId : openId
    })
    api.post({
      url: 后端封装微信小程序的开放登录接口
      data: params
    }).then(res => {
      if(res.data.IsSuccess) {
        // 登录成功==>存储用户信息==> 条状目标页面
        ...
        Taro.switchTab({
          url: targetPagePath || '/pages/index/index'
        })
      } else {
        // 错误提示,或者跳转错误页面
        ...
      }
    })
}