uni-app开发-微信公众号网页授权微信登录

原文档:网页授权 | 微信开放文档 (qq.com)
一、微信公众号平台配置网页授权域名

uni-app开发-微信公众号网页授权微信登录_第1张图片

二、示例代码
<template>
    <button open-type="login" @tap="wxLogin">允许</button>
</template>
<script setup lang="ts">
import { onLoad } from "@dcloudio/uni-app";
import loginApi from "@/api/loginApi";
import { ref } from "vue";
const isWeixin = ref(false); // 是否微信内置浏览器

onLoad(() => {
  isWeixin.value = isWechat();
  if (isWeixin.value) {
    checkWeChatCode();
  }
})
/*微信登录相关  start*/
//方法:用来判断是否是微信内置的浏览器
const isWechat = () => {
  return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
}
//方法:用来提取code
const getUrlCode = (name: string) => {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ''])[1]
    .replace(/\+/g, '%20')) || null
}
//检查浏览器地址栏中微信接口返回的code
const checkWeChatCode = () => {
  let code = getUrlCode('code');
  if (code) {
    bindUser(code)
  }
}
// 微信登录
const wxLogin = () => {
  // url 是当前链接 encodeURIComponent字符串作为 URI 组件进行编码 来做可识别的回调链接
  let uri = encodeURIComponent(window.location.href);
  window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=appid&redirect_uri=${uri}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`;
}
// 绑定用户
const bindUser = (code: string) => {
  
}
</script>

你可能感兴趣的:(Uni-app,uni-app,微信,前端)