Appearance
微信 Auth 相关内容
核心:获取 code ,传给后段,后端获取 openid
https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html
/checkup/prepare/1243123423_56756756
openid
获取 code
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirectscope
- snsapi_base:不弹出授权页面,只有 openid
- snsapi_userinfo:弹出授权页面,信息更多
代码示例
ts
interface IWxMpAuthConfig {
[key: string]: string | boolean | undefined;
appid: string;
redirect_uri: string;
response_type: "code";
/**
* snsapi_base 不弹出授权页面,只能获取用户openid
* snsapi_userinfo 弹出授权页面,获取更多信息。
*/
scope: "snsapi_base" | "snsapi_userinfo";
state?: string;
forcePopup?: boolean;
}封装
ts
const getWxAuthURL = (config: IWxMpAuthConfig) => {
const start = "https://open.weixin.qq.com/connect/oauth2/authorize";
const end = "#wechat_redirect";
const { appid, redirect_uri, response_type, scope, state, forcePopup } =
config;
// 注意,微信拼接是有顺序要求的
// 所以这里对顺序进行一次排序
const conf: IWxMpAuthConfig = {
appid,
redirect_uri,
response_type,
scope,
state,
forcePopup,
};
const params = [];
for (const key in conf) {
// if (!Object.prototype.hasOwnProperty.call(conf, key)) continue
if (!key) continue;
const value = conf[key];
if (value) params.push(`${key}=${value}`);
}
return `${start}?${params.join("&")}${end}`;
};使用
ts
const { origin, pathname, hash } = window.location
const redirect_uri = encodeURIComponent(`${origin}${pathname}${hash}`)
const url = getWxAuthURL({
appid: 'wxa9462c49dd468b45',
redirect_uri,
scope: 'snsapi_userinfo',
response_type: 'code',
state
})
window.location.href = url