jiangwei小站
258 字
1 分钟
微信公众号网页授权登录公用
2024-04-26

只需在微信公众号后台安全域名配置域名
然后在登录页跳转此代码的页面就能把 code 带回去
/authorize?url=${location.href}&appid=xxx

<template>
  <div class="authorize">
    <div class="content wx">
      <div class="title">微信授权登录</div>
      <img src="@/assets/images/common/wx.png" alt="wx" />
    </div>
  </div>
</template>
<script setup lang="ts">
import { GetUrlParams } from "@/utils/Util";

if (GetUrlParams().code) {
  const redirectUri = sessionStorage.getItem("redirectUri") as string;
  const url = addOrUpdateQueryParam(redirectUri, "code", GetUrlParams().code);
  location.href = url;
} else {
  const url = GetUrlParams().url;
  sessionStorage.setItem("redirectUri", url);

  const REDIRECT_URI = location.href;
  window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${
    GetUrlParams().appid
  }&redirect_uri=${encodeURIComponent(
    REDIRECT_URI
  )}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;
}

function addOrUpdateQueryParam(url: string, key: string, value: string) {
  // 使用 URL 对象解析 URL
  const urlObject = new URL(url);

  // 获取查询参数
  const queryParams = urlObject.searchParams;

  // 检查参数是否已存在
  if (queryParams.has(key)) {
    // 如果参数已存在,更新它的值
    queryParams.set(key, value);
  } else {
    // 如果参数不存在,添加新参数
    queryParams.append(key, value);
  }

  // 重新设置 URL 对象的查询参数
  urlObject.search = queryParams.toString();

  return urlObject.toString();
}
</script>
<style lang="scss">
.authorize {
  padding-top: 88px;
  background: url("@/assets/images/mine/bg-login.jpg") no-repeat;
  background-size: 100% auto;
  min-height: 100vh;
  .content {
    padding: 36px;
    padding-top: 216px;
    .title {
      font-size: 40px;
      font-weight: bold;
      margin-bottom: 42px;
    }
  }
  .wx {
    text-align: center;
    font-size: 36px !important;
    img {
      margin: auto;
      width: 64px;
      height: 64px;
    }
  }
}
</style>