1+ import { Request , Response } from "express" ;
2+ import utils from '../utils' ;
3+ import { saveUser } from './index' ;
4+
5+ const appId = utils . config ?. login . wechatAppId || '' ;
6+
7+ export async function login ( req : Request , res : Response ) {
8+ const domain = new URL ( req . headers . referer || `${ req . protocol } ://${ req . headers . host } ` ) . host ;
9+ if ( ! appId ) return res . end ( '微信OAuth 未配置,请联系管理员' ) ;
10+ if ( req . query [ 'code' ] ) {
11+ const tokenData = await verify ( req ) ;
12+ if ( tokenData . access_token ) {
13+ const userInfo = await getUserInfo ( tokenData . access_token , tokenData . openid ) ;
14+ req . session . player = await saveUser ( {
15+ name : 'wechat-' + userInfo . openid ,
16+ nickname : userInfo . nickname ,
17+ id : userInfo . openid ,
18+ from : 'wechat' ,
19+ avatar : userInfo . headimgurl ,
20+ ip : req . header ( 'x-forwarded-for' ) || req . header ( 'x-real-ip' ) || req . socket . remoteAddress || req . ip || ''
21+ } ) ;
22+ return res . redirect ( "/" ) ;
23+ } else {
24+ req . session . error = "登录验证失败,请重试" ;
25+ return res . redirect ( "/login" ) ;
26+ }
27+ }
28+ res . redirect ( `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${ appId } &redirect_uri=https%3A%2F%2F${ domain } %2Fapi%2Flogin%2Fwechat&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect` ) ;
29+ }
30+
31+ async function verify ( req : Request ) {
32+ const verifyReq = {
33+ appid : utils . config ?. login . wechatAppId ,
34+ secret : utils . config ?. login . wechatAppSecret ,
35+ code : req . query [ 'code' ] ,
36+ grant_type : 'authorization_code'
37+ } ;
38+ const params = new URLSearchParams ( verifyReq as any ) ;
39+ const response = await fetch ( `https://api.weixin.qq.com/sns/oauth2/access_token?${ params } ` , {
40+ method : 'GET'
41+ } ) ;
42+ const data = await response . json ( ) ;
43+ return data ;
44+ }
45+
46+ async function getUserInfo ( access_token : string , openid : string ) {
47+ const response = await fetch ( `https://api.weixin.qq.com/sns/userinfo?access_token=${ access_token } &openid=${ openid } ` , {
48+ method : 'GET'
49+ } ) ;
50+ const data = await response . json ( ) ;
51+ return data ;
52+ }
0 commit comments