@next-auth-oauth/wechatmp
Version:
基于Auth.js的微信公众号验证码登录、二维码扫描登录插件
102 lines (101 loc) • 3.1 kB
JavaScript
import { MemoryCaptchaManager } from './lib/CaptchaManager';
import { WechatMpLoginManager, } from './WehcatMpLoginManger';
export * from './lib/CaptchaManager';
/**
* 微信公众号平台(验证码登录)
* [体验账号申请](https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login)
*
* @param options
* @returns
*/
export default function WeChatMp(options) {
const { checks: _checks, captchaManager, checkType, endpoint, qrcodeImageUrl, aesKey, token, appId, appSecret, ...reset } = Object.assign({
captchaManager: new MemoryCaptchaManager(),
appId: process.env.AUTH_WECHATMP_APPID ?? 'TEMP',
appSecret: process.env.AUTH_WECHATMP_APPSECRET ?? 'TEMP',
token: process.env.AUTH_WECHATMP_TOKEN ?? 'TEMP',
endpoint: process.env.AUTH_WECHATMP_ENDPOINT ??
'http://localhost:3000/api/auth/wechatmp',
checkType: process.env.AUTH_WECHATMP_CHECKTYPE ?? 'MESSAGE',
qrcodeImageUrl: process.env.AUTH_WECHATMP_QRCODE_IMAGE_URL,
}, options ?? {});
const endpointUrl = new URL(endpoint);
const wechatMPLoginManager = new WechatMpLoginManager({
captchaManager,
checkType,
endpoint,
qrcodeImageUrl,
appId,
appSecret,
token,
aesKey,
});
// 跳转页面,也就是二维码
const authorization = {
url: endpointUrl.toString(),
params: {
client_id: appId,
response_type: 'code',
action: 'qrcode',
},
};
/**
* 账户信息
* @param tokens
* @returns
*/
const account = (tokens) => {
return {
access_token: tokens.access_token,
expires_at: Date.now(),
refresh_token: '',
refresh_token_expires_at: Date.now(),
};
};
const profile = (profile) => {
const openid = profile.unionid ?? profile.openid;
return {
id: openid,
name: openid,
email: openid + '@wechat.com',
raw: profile,
};
};
const userinfo = {
//由于next-auth会校验url的合理,这里就随意填写
url: 'http://localhost:3000/auth/qrcode2',
async request({ tokens }) {
return {
openid: tokens.access_token,
};
},
};
// 从callback中获得state,code 然后进一步获取
const tokenEndpoint = {
url: endpoint,
params: {
action: 'token',
},
};
return {
GET: (req) => wechatMPLoginManager.handle(req),
POST: (req) => wechatMPLoginManager.handle(req),
account,
clientId: appId,
clientSecret: appSecret,
id: 'wechatmp',
name: '微信公众号登录',
type: 'oauth',
style: {
logo: '/providers/wechatOfficialAccount.svg',
bg: '#fff',
text: '#000',
},
userinfo,
profile,
authorization,
checks: ['none'],
token: tokenEndpoint,
...reset,
};
}