首页 前端知识 h5登录微信获取code和openId h5获取code一直循环回退 微信登录获取code 微信登录重定向重复获取code

h5登录微信获取code和openId h5获取code一直循环回退 微信登录获取code 微信登录重定向重复获取code

2024-07-01 23:07:22 前端知识 前端哥 608 507 我要收藏

1、官方文档:

https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html

https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect

scope分为snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo (弹出授权页面,可通过 openid 拿到昵称、性别、所在地。并且, 即使在未关注的情况下,只要用户授权,也能获取其信息 )

如果出现redirect_uri参数错误,那一般就是公众号授权回调页面域名的问题:

在这里插入图片描述

重点:
公众号授权回调页面域名,一定要填写顶级域名
公众号授权回调页面域名,一定要填写顶级域名
公众号授权回调页面域名,一定要填写顶级域名

还有,这儿不要写https://或者http://

在这里插入图片描述

实例(控制台打出了code):
在这里插入图片描述

如果一直重复回调刷新页面,那就用下面的代码就可以解决;

代码演示(静默授权):

async function weixin() {
  let appid = 'wx9a43yt13312e2e00'
  let redirectUrl = encodeURIComponent(window.location.href)

  let url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirectUrl}&response_type=code&scope=snsapi_base&state=STATE&connect_redirect=1#wechat_redirect`
  if (window.location.href.indexOf('code=') != -1) { // 避免一直重复重定向无限获取code
    let code = await getQueryVariable('code') // 从url中获取code的值(此方法文末会贴出)
    if (code == sessionStorage.getItem('code')) { // 微信获取code会重定向,所以从别的页面返回本页后,返回的其实是重定向之后的url,此时url一定带有上次的code,code只能用一次,这时候要重新获取
      let urls = await ridUrlParam(window.location.href, ['code']) // 从url中祛除code,用没有code的url重新生成code (此方法文末会贴出)
      window.location.href = urls
    }
    sessionStorage.setItem('code', code)
  } else {
    window.location.href = url
  }
}

方法1:从url中获取code的值

https://blog.csdn.net/u013361179/article/details/127072879?spm=1001.2014.3001.5501

方法2:从url中祛除code,返回没有code的url

https://blog.csdn.net/u013361179/article/details/127052843?spm=1001.2014.3001.5501

转载请注明出处或者链接地址:https://www.qianduange.cn//article/13769.html
标签
评论
发布的文章

读魏书生的心得体会

2024-07-03 14:07:10

jQuery 选择器

2024-05-12 00:05:34

Vue中public/assets目录区别

2024-07-02 23:07:29

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!