58 lines
1.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { openidConfig } from './config.js';
export const isWechat = () => {
const ua = navigator.userAgent.toLowerCase();
return /micromessenger/i.test(ua);
};
export const getOpenid = async () => {
const url = new URL(window.location.href);
const state = url.searchParams.get('state');
const code = url.searchParams.get('code');
const orgin = url.origin;
const res = await fetch(`${orgin}/api/router?path=wx&key=mp-get-openid&state=${state}&code=${code}`)
.then((res) => res.json())
.catch((err) => {
console.error(err);
alert('登录失败,请稍后再试');
document.body.append('登录失败,请稍后再试');
// closePage();
});
if (res.code === 200) {
document.body.append(JSON.stringify(res.data, null, 2));
}
};
export const checkHasCode = () => {
const url = new URL(window.location.href);
const code = url.searchParams.get('code');
return code;
};
export const initGetOpenidEvent = () => {
if (!isWechat()) {
document.body.append('请在微信中打开');
return;
}
const hasCode = checkHasCode();
if (hasCode) {
getOpenid();
} else {
// 没有code则跳转获取code
getCodeRedirect();
}
};
const randomString = () => {
return Math.random().toString(36).substring(2, 15);
};
export const getCodeRedirect = () => {
const defaultURL = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect`;
const appid = openidConfig.appid;
const redirect_uri = encodeURIComponent(openidConfig.redirect_uri);
const scope = openidConfig.scope;
const state = randomString();
const link = defaultURL.replace('APPID', appid).replace('REDIRECT_URI', redirect_uri).replace('SCOPE', scope).replace('STATE', state);
window.location.href = link;
};