import axios from 'axios'; import { Util } from './sms.util'; type WeChatSettings = { wechatAppId: string; wechatSecret: string; wechatRedirectUrl: string; wechatLoginSuccessRedirectUrl: string; wechatAPIRedirectUrl: string; wechatAPIUserinfoUrl: string; wechatAPITokenUrl: string; wechatQrCodeUrl: string; }; export class WeChatLoginUtil { private settings: WeChatSettings; private static instance: WeChatLoginUtil; constructor(settings: WeChatSettings) { this.settings = settings; } static getInstance() { if (!WeChatLoginUtil.instance) { WeChatLoginUtil.instance = new WeChatLoginUtil({ wechatAppId: `${process.env.WECHAT_APPID}`, wechatSecret: `${process.env.WECHAT_APPSECRET}`, wechatRedirectUrl: `${process.env.WECHAT_REDIRECT_URL}`, wechatLoginSuccessRedirectUrl: `${process.env.WECHAT_LOGIN_SECCESS_REDIRECT_URL}`, wechatAPIRedirectUrl: `${process.env.WECHAT_API_REDIRECT_URL}`, wechatAPIUserinfoUrl: `${process.env.WECHAT_API_USERINFO_URL}`, wechatAPITokenUrl: `${process.env.WECHAT_API_TOKEN_URL}`, wechatQrCodeUrl: `${process.env.WECHAT_QRCODE_URL}` }); } return WeChatLoginUtil.instance; } async getWeChatSDKConfig(): Promise<{ appid: string; state: string; scope: string; }> { return { appid: this.settings.wechatAppId, state: Util.generateRandomNumber(30), scope: 'snsapi_login' }; } async getWeChatQrCodeUrl(): Promise<{ url: string; state: string; }> { const redirectUrl = encodeURIComponent(this.settings.wechatAPIRedirectUrl); const wechatQRCodeUrl = this.settings.wechatQrCodeUrl; const state = Util.generateRandomNumber(30); const qrCodeUrl = `${wechatQRCodeUrl}appid=${this.settings.wechatAppId}&redirect_uri=${redirectUrl}&response_type=code&scope=snsapi_login&state=${state}#wechat_redirect`; return { url: qrCodeUrl, state }; } async getAccessToken( code: string ): Promise<{ access_token: string; expires_in: number; refresh_token: string; openid: string; scope: string; unionid: string; }> { const wechatTokenUrl = this.settings.wechatAPITokenUrl; const tokenUrl = `${wechatTokenUrl}appid=${this.settings.wechatAppId}&secret=${this.settings.wechatSecret}&code=${code}&grant_type=authorization_code`; const response = await axios.get(tokenUrl); return response.data; } async getUserInfoByOpenId( accessToken: string, openID: string ): Promise<{ openid: string; sex: number; nickname: string; language: string; city: string; province: string; country: string; headimgurl: string; unionid: string; privilege: any; }> { const wechatUserInfoUrl = `${process.env.WECHAT_API_USERINFO_URL}`; const userInfoUrl = `${wechatUserInfoUrl}access_token=${accessToken}&openid=${openID}&lang=zh_CN`; const response = await axios.get(userInfoUrl); return response.data; } }