评论

nuxt3项目实现微信h5登录,静默授权,获取openid

nuxt3项目,微信h5静默授权,实现登录,获取openid,如果文章对你有帮助,请收藏,点赞,关注 三连击,后续不迷路😁

在nuxt3项目中,进行微信用户登录,静默授权,还是比较简单的,不废话,直接上代码:

import { getOpenId } from '@/api/login';

// 生产授权url
const getScopeUrl = () => {
  const appid = '自己的appid';
  const redirect_uri = encodeURIComponent(location.href || '生产域名');
  return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`;
};

// 初始化进行授权
const initScope = () => {
  // 如果本地已经有opened了,直接返回,在后续页面直接获取使用
  let openid = localStorage.getItem('openid');
  if (openid) {
    return;
  }

  // 判断是否在微信内置浏览器
  let isWeixinBrowser = /MicroMessenger/i.test(navigator.userAgent);
  if (!isWeixinBrowser) {
    return;
  }

  // 解析当前url,判断是否有code参数
  let urls = new URL(location.href);
  let code = urls.searchParams.get('code');
  // 如果code存在,请求接口换取openid,在后续页面直接获取使用
  if (code) {
    getOpenId({ code }).then((res) => {
      localStorage.setItem('openid', res.data);
    });
  }
  // 如果不逊在,进行静默授权
  else {
    location.href = getScopeUrl();
  }
};

onMounted(() => {
  // 初始化静默授权逻辑
  initScope();
});


如果文章对你有帮助,请收藏,点赞,关注 三连击,后续不迷路😁

最后一次编辑于  06-20  
点赞 0
收藏
评论
登录 后发表内容