微信公眾號獲取openid---前端應(yīng)該怎么做

思路:當(dāng)你點(diǎn)進(jìn)來的時(shí)候先判斷地址欄上有沒有code,如果有code那么直接截取發(fā)給后端,如果沒有的話就跳轉(zhuǎn)到這個(gè)地址(這里需要填寫自己的appId),需要傳入一個(gè)回調(diào)地址,這樣微信就知道怎么再跳轉(zhuǎn)回來,這里的回調(diào)地址就是你當(dāng)前剛點(diǎn)進(jìn)來的這個(gè)地址,你這里只要寫window.location.href即可,這樣跳轉(zhuǎn)回來的時(shí)候你會發(fā)現(xiàn)url上多出了一個(gè)code,前端只需要拿到當(dāng)前的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>


?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容