Skip to content

微信 PC 使用微信登陆

网站接入准备工作

  1. 微信开放平台注册开发者账号,点击查看操作指引;

  2. 微信开放平台-管理中心-创建网站应用并通过审核;

  3. 通过审核后可以获得相应的 AppID 和 AppSecret;

  4. 应用申请微信登录且通过审核后,可开始接入流程。

接入流程

1. 页面

html
<a class="tab-item fl" :href="wechatHref" target="_parent">微信登录</a>

<!--变量-->
<!--wechatHref: wechat.getWechatLoginUrl(),方法如下-->
<!--变量结束-->

2.js

js
const getWechatLoginUrl = () => {
  if (process.browser) {
    const domain = window.location.protocol + "//" + window.location.host;
    // 获得回调地址
    const wechatUrl =
      "https://open.weixin.qq.com/connect/qrconnect?appid=你自己的ID&redirect_uri=" +
      encodeURIComponent("https://www.xxxxxx.com/wechat-callback") +
      "&response_type=code&scope=snsapi_login&state=" +
      btoa("login" + "|||" + btoa(domain));
    return wechatUrl;
  }
};

const getWechatBindUrl = () => {
  if (process.browser) {
    const domain = window.location.protocol + "//" + window.location.host;
    // 获得回调地址
    const wechatUrl =
      "https://open.weixin.qq.com/connect/qrconnect?appid=你自己的ID&redirect_uri=" +
      encodeURIComponent("https://www.xxxxxx.com/wechat-callback") +
      "&response_type=code&scope=snsapi_login&state=" +
      btoa("bind" + "|||" + btoa(domain));
    return wechatUrl;
  }
};

export default {
  getWechatLoginUrl,
  getWechatBindUrl,
};

weixin-callback 页面

html
<template>
  <div
    v-loading="true"
    element-loading-text="正在验证微信数据"
    class="wechat-callback-box"
  ></div>
</template>

<script>
  import { bindWechatApi } from "@/api/me";
  import { goBackUrlback } from "@/utils/tools";
  import { getWechatInfoApi } from "@/api/login";
  import auth from "@/utils/auth";
  const Cookies = process.browser ? require("js-cookie") : undefined;

  export default {
    name: "WechatCallback",
    components: {},
    data() {
      return {};
    },
    mounted() {
      // 拦截微信code
      if (process.browser) {
        const query = this.getPar();
        if (query.code && query.state) {
          this.dealWith(query.code, query.state);
        } else {
          window.location.href = "/";
        }
      }
    },
    methods: {
      getPar() {
        if (process.browser) {
          var url = window.document.location.href.toString();
          var u = url.split("?");
          if (typeof u[1] == "string") {
            u = u[1].split("&");
            var get = {};
            for (var i in u) {
              var j = u[i].split("=");
              get[j[0]] = decodeURIComponent(j[1]);
            }
            return get;
          } else {
            return {};
          }
        }
      },
      dealWith(code, state) {
        if (process.browser) {
          state = atob(state);
          const stateArr = state.split("|||");
          if (!stateArr || stateArr.length != 2) {
            window.location.href = "/";
          }
          const type = stateArr[0];
          const domain = atob(stateArr[1]);
          if (
            domain !==
            window.location.protocol + "//" + window.location.host
          ) {
            // 域名不一致
            window.location.href =
              domain +
              "/wechat-callback?code=" +
              code +
              "&state=" +
              btoa(state);
          } else {
            if (type === "login") {
              this.login(code);
            } else if (type === "bind") {
              this.bind(code);
            } else {
              window.location.href = "/";
            }
          }
        }
      },
      login(code) {
        if (process.browser) {
          getWechatInfoApi({
            code: code,
            appid: "你自己的ID",
          })
            .then((res) => {
              if (res.code !== this.$config.codeOk) {
                this.$IMessage.warning("登录失败");
                this.$router.push("/user/login.html");
                return false;
              }
              const backurl = window.localStorage.getItem("backurl");
              if (res.data.is_account == this.$config.login.has_account) {
                // 微信有账号,直接登录
                const loginInfo = res.data.login_info;
                // 存储登录信息
                auth.saveLoginInfo(loginInfo);
                // Cookies.set('access_token', res.data.access_token)
                // Cookies.set('identify', res.data.identify)
                // Cookies.set('username', res.data.username)
                // 判断是否有手机号
                if (loginInfo.is_mobile === this.$config.login.unbind_mobile) {
                  let bindQuery = {};
                  if (backurl) {
                    bindQuery.backurl = backurl;
                  }
                  this.$router.push({
                    path: "/user/bind.html",
                    query: bindQuery,
                  });
                } else {
                  // 回到来源页
                  console.log("跳转到GOBACK页面");
                  goBackUrlback(window.localStorage.getItem("backurl"));
                }
              } else {
                // 微信没有账号,去绑定手机号
                this.$store.dispatch("user/changeAttr", {
                  wechatInfo: res.data.wechat_info,
                });
                let wxBindQuery = {};
                if (backurl) {
                  wxBindQuery.backurl = backurl;
                }
                this.$router.push({
                  path: "/user/wxbind.html",
                  query: wxBindQuery,
                });
              }
            })
            .catch(() => {
              this.$IMessage.warning("登录失败");
              this.$router.push("/user/login.html");
            });
        }
      },
      bind(code) {
        bindWechatApi({
          wechat_code: code,
          appid: "你自己的ID",
        })
          .then((res) => {
            if (res.code === this.$config.codeOk) {
              this.$IMessage.success(res.msg);
            } else {
              this.$IMessage.warning(res.msg);
            }
            this.$router.push("/me");
          })
          .catch(() => {
            this.$IMessage.warning("绑定失败");
            this.$router.push("/me");
          });
      },
    },
  };
</script>

<style lang="scss" scoped>
  .wechat-callback-box {
    height: 50%;
  }
</style>