WeChat public account authorized to obtain code infinite loop jump page

1. Obtain authorization from WeChat public account

Pitfalls: After only authorizing, the WeChat official account keeps calling back the WeChat interface, resulting in a lot of codes. It is necessary to determine whether there is a code value.

Complete code:

<template>
  
  <RouterView />

</template>

<script setup>
import { onBeforeMount } from 'vue';
import $api from '@/api/index.js';

const APPID='wx000000000111000';

const getCode =() => { // 静默授权
    //获取从后台拿到的openid存下来,判断是否存在
    const wxuser = window.localStorage.getItem('wxuser')

    if (wxuser == null || wxuser === '') {
       getOpen()
    }
}
async function getOpen() {
  const local = window.location.href

  let url = 
  'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + APPID + '&redirect_uri=' + encodeURIComponent(local) + '&response_type=code&scope=snsapi_userinfo&state=1&connect_redirect=1#wechat_redirect'

  if (window.location.href.indexOf('code=') != -1) { // 避免一直重复重定向无限获取code
    let code = await getUrlName('code') // 从url中获取code的值
    if (code == sessionStorage.getItem('code')) { // 微信获取code会重定向,所以从别的页面返回本页后,返回的其实是重定向之后的url,此时url一定带有上次的code,code只能用一次,这时候要重新获取
      let urls = await deUrlParam(window.location.href, ['code']) // 从url中删除code
      window.location.href = urls
    }
    sessionStorage.setItem('code', code)
  } else {
    window.location.href = url
  }
}
//从url中获取指定参数的值
const getUrlName=(paramName)=> {
  const url = window.location.href;
  const regex = new RegExp(`${paramName}=([^&]*)`);
  const match = regex.exec(url);
  if (match) {
    return match[1];
  } else {
    return null;
  }
}
//删除URL中指定search参数,会将参数值一起删除,返回没有该参数的完整url
const deUrlParam=(url, params)=> {
  /**
   * 删除URL中指定search参数,会将参数值一起删除
   * @param {string} url 地址字符串
   * @param {array} aParam 要删除的参数key数组,如['name','age']
   * @return {string} 返回新URL字符串
   */
  for (var index = 0; index < params.length; index++) {
    var item = params[index];
    var fromIndex = url.indexOf(item + "="); //必须加=号,避免参数值中包含item字符串
    if (fromIndex !== -1) {
      // 通过url特殊符号,计算出=号后面的的字符数,用于生成replace正则
      var startIndex = url.indexOf("=", fromIndex);
      var endIndex = url.indexOf("&", fromIndex);
      var hashIndex = url.indexOf("#", fromIndex);

      var reg = "";
      if (endIndex !== -1) {
        // 后面还有search参数的情况
        var num = endIndex - startIndex;
        reg = new RegExp(item + "=.{" + num + "}");
        url = url.replace(reg, "");
      } else if (hashIndex !== -1) {
        // 有hash参数的情况
        var num = hashIndex - startIndex - 1;
        reg = new RegExp("&?" + item + "=.{" + num + "}");
        url = url.replace(reg, "");
      } else {
        // search参数在最后或只有一个参数的情况
        reg = new RegExp("&?" + item + "=.+");
        url = url.replace(reg, "");
      }
    }
  }
  var noSearchParam = url.indexOf("=");
  if (noSearchParam === -1) {
    url = url.replace(/\?/, ""); // 如果已经没有参数,删除?号
  }
  return url;
}

getCode() 

</script>
<style lang="scss" scoped>

</style>

Reference: h5 logs in to WeChat to get the code and openId h5 gets the code and keeps looping back to log in to WeChat to get the code WeChat login redirects to get the code repeatedly_vue WeChat public account jumps h5 always carries the code jump solution_Love Drinking Ice Coke's Blog-CSDN Blog

Guess you like

Origin blog.csdn.net/qq_36821274/article/details/132357919