vue中 公众号开发授权

微信环境错误页面。

<template>
   <div class="weui_msg"><div class="weui_icon_area"><i class="weui_icon_info weui_icon_msg"></i></div><div class="weui_text_area"><h4 class="weui_msg_title">请在微信客户端打开链接</h4></div></div>
</template>

<script setup >
import { } from 'vue'

</script>
<style  scoped>
@import '../assets/css/weui.css'

</style>

路由判断

router.beforeEach((to, from, next)=>{
  if(to.path == "/error") {next()}else{
    if(isWeixin()){
      // 微信环境
      
      next()
    }else{
       next("/error")
    }
  }
    
})
/**
 * 是否是微信环境
 * @returns 
 */
 function isWeixin () {
    var ua = window.navigator.userAgent.toLowerCase()
    if (ua.match(/MicroMessenger/i) == 'micromessenger') {
      return true
    } else {
      return false
    }
  }

授权

async function getAuthorize()  {
  //先判断有没有授权(判断地址栏code,有就-用户同意了授权,没有-没授权或者拒绝授权)
  var code = getUrlParam("code"); //此处使用的是history路由模式,hash这么拿不到。getUrlParam()方法在下面
  console.log('code',code)
  if (code) {
    console.log("获取到了 code", code);
    let param = {
      code: code,
    };
    try{
      Api.getUserInfo(param).then((res) => {
      userInfo.value = res?.data?.data || null
    });
    }catch(e){
      showDialog({title:'提示',message:'用户信息获取失败,请稍后再试'})
    }
    getCompanyList()
   
  } else {
    var appid = "wx0008f9b5e1198d**";
    var redirect_uri = "https://*******/wechat_web/index.html";
    var newRedirect = encodeURIComponent(redirect_uri); // 此处需要将你的回调页面进行转码,此方法直接使用
    // window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri="+newRedirect +"&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
    window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + newRedirect + "&response_type=code&scope=snsapi_userinfo#wechat_redirect";
  }
  // }
}
//获取url中的参数
function getUrlParam(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
  var r = window.location.search.substr(1).match(reg); //匹配目标参数
  if (r != null) {
    return unescape(r[2]);
  }
  return null; //返回参数值
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容