React H5 项目 微信授权登录 /静默登录

2020-06-28  本文已影响0人  不不作为

一:如何判断微信内或者微信外打开项目?

navigator.userAgent.toLowerCase().indexOf('micromessenger') !== -1 || typeof navigator.wxuserAgent != "undefined"

微信内返回true 外返回false

二:微信授权登录APP, 如果有账户,直接跳商城首页,如果没有账户,跳转到注册页面:

1): 给按钮添加点击事件:

 <div className={styles.bottom}>
                           <span>第三方账户登录 <img  src={right} alt=""/></span>
                            <img onClick={()=>{this.weChatLogin()}} src={wx} />
                        </div>

事件书写:

weChatLogin = async () => {
    const url = encodeURI(`${myAPI}/`)
    window.location = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=appId&redirect_uri=${url}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
  }

此时,点击按钮会自动跳转微信授权登录页面
2):在生命周期函数中,截取code传给后台,后台判断此用户是否已注册本APP

   componentDidMount() {
        //const windowHeight = window.innerHeight
      if (window.location.href != "http://www.xcy.ac.cn/" && navigator.userAgent.toLowerCase().indexOf('micromessenger') !== -1 || typeof navigator.wxuserAgent != "undefined") {
        if (navigator.userAgent.toLowerCase().indexOf('micromessenger') !== -1
          || typeof navigator.wxuserAgent != "undefined"
        ) {
          var o1 = window.location.href.split("=")
          var o2 = o1[1] ? o1[1].split("&") : ""
          store.set('code',o2[0])
          console.log(store.get('code'))
          const code = store.get('code')
          if(code){
            users.wechatLogin({code:code}).then(res=>{  //把截取的code 传给后台,后台查询此微信有没有注册本app,如果有返回账号密码,自动登录,如果没有跳转注册页面
              if(res.code===3){
                console.log(res.data.tel)
                console.log(res.data.pwd)
                const phone  = res.data.tel;
                const pwd = res.data.pwd;
                users.login({phone,pwd}).then(res=>{
                  if(res.code===1){ //有:直接跳转商城首页
                    login(phone, pwd)   //调用之后把账号和密码存储再本
                    Toast.success(res.msg, 1, () => {
                      dispatch(routerRedux.push('/home'))
                    });  //成功或者失败之后的提示语
                    return;
                  }
                })
              }else if(res.code===4){ //没有:跳转注册页面
               store.set('user_info',res.data)
               history.push('/WxZhuCe')
                //把信息返给我 然后我要去跳微信注册页面,重新注册账号密码;
              }else if(res.code===2){
                Toast.offline(res.msg,1)
                return;
              }
            })
          }
        }
      }
    }

跳转注册页之后 给后台传值,然后注册成功后携带后台传的的账号密码生成token 进而登录成功

上一篇下一篇

猜你喜欢

热点阅读