This commit is contained in:
2025-11-30 21:32:01 +08:00
parent b7f1095e4a
commit d4ff2862bd
11 changed files with 413 additions and 34 deletions

View File

@@ -1,9 +1,11 @@
import { WxServices } from "./modules/wx-services.ts";
import { app, redis } from "@/app.ts";
app
.route({
path: 'wx',
key: 'checkLogin',
description: '微信网页登录后获取登录结果(遗弃)',
})
.define(async (ctx) => {
const state = ctx.query.state;
@@ -28,6 +30,7 @@ app
.route({
path: 'wx',
key: 'mplogin',
description: '微信网页登录后提交code去登录遗弃',
})
.define(async (ctx) => {
const state = ctx.query.state;
@@ -50,7 +53,7 @@ app
.route({
path: 'wx',
key: 'mp-get-openid',
isDebug: true,
description: '微信公众平台获取openid',
})
.define(async (ctx) => {
const code = ctx.query.code;
@@ -68,7 +71,7 @@ app
.route({
path: 'wx',
key: 'open-login',
isDebug: true,
description: '微信开放平台登录',
})
.define(async (ctx) => {
const code = ctx.query.code;
@@ -89,3 +92,71 @@ app
}
})
.addTo(app);
app.route({
path: 'wx',
key: 'get-qrcode-ticket',
description: '获取微信二维码ticket',
})
.define(async (ctx) => {
const wx = new WxServices();
const res = await wx.getQrCodeTicket();
if (!res) {
ctx.throw(500, 'Get qrcode ticket failed');
return;
}
const key = `wx:mp:login:qrcode:${res.ticket}`;
await redis.set(key, '-', 'EX', 360); // 6分钟过期
ctx.body = res;
})
.addTo(app);
app.route({
path: 'wx',
key: 'check-qrcode-login',
description: '检查微信二维码登录状态',
})
.define(async (ctx) => {
const ticket = ctx.query.ticket;
if (!ticket) {
ctx.throw(400, 'ticket is required');
return;
}
const token = await redis.get(`wx:mp:login:qrcode:${ticket}`);
if (!token) {
ctx.throw(400, 'Invalid ticket');
return;
}
if (token === '-') {
ctx.throw(400, 'Not scanned yet');
return;
}
try {
// remove the token after getting it
await redis.del(`wx:mp:login:qrcode:${ticket}`);
ctx.body = JSON.parse(token);
} catch (error) {
ctx.throw(500, 'Invalid token get');
}
})
.addTo(app);
app.route({
path: 'wx',
key: 'login-by-ticket',
description: '通过ticket登录微信扫码登录回调',
})
.define(async (ctx) => {
const { openid, ticket } = ctx.query || {};
if (!openid || !ticket) {
console.error('openid and ticket are required');
ctx.throw(400, 'openid and ticket are required');
return;
}
const wx = new WxServices();
const result = await wx.loginByTicket({ openid, ticket });
ctx.body = result;
})
.addTo(app);