xccjk / x-blog

学习笔记
17 stars 2 forks source link

微信H5出现重复授权窗口跳转问题? #23

Closed xccjk closed 1 year ago

xccjk commented 3 years ago

微信H5出现重复授权窗口跳转问题

场景与问题描述

  1. Android机上,主要在低版本Android机上,客户打开微信H5,页面出现多次弹出授权窗口,需要点击多次确认才会消失
  2. 微信授权主要用于获取code码,用于微信支付时使用

原因分析

  1. 原因分析:多次重定向导致出现多次授权
  2. 重定向方法
  // 代码1
  redirectWXAuth = () => {
    const { goToPage } = this.state
    const redirectUrl = encodeURIComponent(
      `${process.env.REDIRECT_HOST}/login?goto_page=${encodeURIComponent(goToPage)}&bindCode=1`
    )
    const wechatAuthUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${process.env.WXAPPID}&redirect_uri=${redirectUrl}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
    window.location.replace(wechatAuthUrl)
  }
  1. 经过查阅资料,发现有两种情况下可能会出现重复授权的问题
  // 代码2
  // 重定向前
  https://h5.abc.com/?v=1592878502327#/home
  // 经过重定向后
  https://h5.abc.com/?v=1592878502327#

  // 处理方式 - 对要重定向地址中的#剪切
  redirectWXAuth = () => {
    const { goToPage } = this.state
    const url = (goToPage + '').replace('#', '')
    const redirectUrl = encodeURIComponent(
      `${process.env.REDIRECT_HOST}/login?goto_page=${encodeURIComponent(url)}&bindCode=1`
    )
    const wechatAuthUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${process.env.WXAPPID}&redirect_uri=${redirectUrl}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
    window.location.replace(wechatAuthUrl)
  }
  // 处理方式2 - 不使用hash模式路由,由后端配置nginx来解决路由跳转
  1. 最终结果,去除重定向地址中的#,同时添加参数connect_redirect
  redirectWXAuth = () => {
    const { goToPage } = this.state
    const url = (goToPage + '').replace('#', '')
    const redirectUrl = encodeURIComponent(
      `${process.env.REDIRECT_HOST}/login?goto_page=${encodeURIComponent(url)}&bindCode=1`
    )
    const wechatAuthUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${process.env.WXAPPID}&redirect_uri=${redirectUrl}&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect`
    window.location.replace(wechatAuthUrl)
  }