Skip to content

Commit 7e5778c

Browse files
committed
✨ feat: 添加微信登录功能
1 parent 1e09641 commit 7e5778c

File tree

5 files changed

+62
-1
lines changed

5 files changed

+62
-1
lines changed

game/backend/src/login/index.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,5 +29,8 @@ export function getThirdPartyType() {
2929
if (config?.login?.steamApiKey) {
3030
types.push('steam');
3131
}
32+
if (config?.login?.wechatAppId && config?.login?.wechatAppSecret) {
33+
types.push('wechat');
34+
}
3235
return types;
3336
}

game/backend/src/login/wechat.ts

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
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+
}

game/backend/src/routes/api.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { Controller } from "../controller";
33
import { login as fishpiLogin, register as fishpiRegister, updateUserInfo } from "../login/fishpi";
44
import { login as steamLogin } from "../login/steam";
55
import { login as githubLogin } from "../login/github";
6+
import { login as wechatLogin } from "../login/wechat";
67
import { Record, RecordRepo, User, UserRepo, AppDataSource, PlayerStats, ManageRepo } from "@/entities";
78
import { getPlayerStats, isConfigured } from "@/utils";
89
import { FindOptionsWhere, Like } from "typeorm";
@@ -167,6 +168,7 @@ const createRoutes = (game: GameContext, gameName: string) => {
167168
router.get("/register/fishpi", fishpiRegister);
168169
router.get("/login/steam", steamLogin);
169170
router.get("/login/github", githubLogin);
171+
router.get("/login/wechat", wechatLogin);
170172

171173
router.post("/logout", (req: Request, res: Response) => {
172174
req.session.destroy((err) => {

game/backend/src/routes/config.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ router.post("/", (req, res) => {
1212
const {
1313
webport, goldenKey, host, port, username, password, database, prefix, marketKey,
1414
persistence_driver, persistence_host, persistence_port, persistence_username, persistence_password, persistence_database, persistence_prefix,
15-
githubClientId, githubClientSecret, steamApiKey, steamMirror
15+
githubClientId, githubClientSecret, steamApiKey, steamMirror, wechatAppId, wechatAppSecret
1616
} = req.body;
1717

1818
const config: IConfig = {
@@ -39,6 +39,8 @@ router.post("/", (req, res) => {
3939
githubClientSecret,
4040
steamApiKey,
4141
steamMirror,
42+
wechatAppId,
43+
wechatAppSecret,
4244
}
4345
}
4446

game/backend/types/index.d.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,5 +39,7 @@ interface IConfig {
3939
githubClientSecret?: string;
4040
steamApiKey?: string;
4141
steamMirror?: string;
42+
wechatAppId?: string;
43+
wechatAppSecret?: string;
4244
}
4345
}

0 commit comments

Comments
 (0)