微信公众号

微信公众号获取openid---前端应该怎么做

2020-11-30  本文已影响0人  hello_web_Front

思路:当你点进来的时候先判断地址栏上有没有code,如果有code那么直接截取发给后端,如果没有的话就跳转到这个地址(这里需要填写自己的appId),需要传入一个回调地址,这样微信就知道怎么再跳转回来,这里的回调地址就是你当前刚点进来的这个地址,你这里只要写window.location.href即可,这样跳转回来的时候你会发现url上多出了一个code,前端只需要拿到当前的code,然后传给后台,后台获取到openid,返回给我们即可,然后我们存起来就可以啦

   "https://open.weixin.qq.com/connect/oauth2/authorize?appid=appid" +
         "&redirect_uri=" +
         encodeURIComponent(window.location.href) +
         "&response_type=code" +
         "&scope=snsapi_base" +
         "&state=1#wechat_redirect";
<template>
  <div id="app">
    <keep-alive>
      <router-view class="router"></router-view>
    </keep-alive>
  </div>
</template>
<script>
import wxConfig from "./wx/wxConfig";
import axios from "axios";
import { get_openid, getOpenId } from "./api/app";
import { mapMutations } from "vuex";

export default {
  data() {
    return { transitionName: "slide-right" };
  },
  name: "App",
  async mounted() {
    // http://192.168.2.51/?code=071bJnFa1ymwUz0IhgJa1xsx1B4bJnFz&state=1#/
    await wxConfig(); // 初始化jssdk
    await this.getOpenId();
  },
  methods: {
    ...mapMutations(["setopenId"]),
    GetRequest() {
      var url = location.search;
      var theRequest = new Object();
      if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
          theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
        }
      }
      return theRequest;
    },
    async getCode() {
      let search = window.location.search;
      let code = search
        .split("&")[0]
        .split("?")[1]
        .split("=")[1];
      const res = await getOpenId({ code });
      if (res.status == 200) {
        let openid = res.result;
        this.setopenId(openid);
        localStorage.setItem("openid", openid);
      } else {
      }
    },
    async getOpenId() {
      let code = this.GetRequest()["code"];
      if (code == "" || code == null) {
        window.location.href =
          "https://open.weixin.qq.com/connect/oauth2/authorize?appid=*******************" +
          "&redirect_uri=" +
          encodeURIComponent(window.location.href) +
          "&response_type=code" +
          "&scope=snsapi_base" +
          "&state=1#wechat_redirect";
      } else {
        this.getCode();
      }
    },
  },
};
</script>


上一篇下一篇

猜你喜欢

热点阅读