udpate
This commit is contained in:
91
src/routes/user/wx-login.ts
Normal file
91
src/routes/user/wx-login.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
import { WxServices } from "./modules/wx-services.ts";
|
||||
import { app, redis } from "@/app.ts";
|
||||
app
|
||||
.route({
|
||||
path: 'wx',
|
||||
key: 'checkLogin',
|
||||
})
|
||||
.define(async (ctx) => {
|
||||
const state = ctx.query.state;
|
||||
if (!state) {
|
||||
ctx.throw(400, 'state is required');
|
||||
return;
|
||||
}
|
||||
const token = await redis.get(`wx:mp:login:${state}`);
|
||||
if (!token) {
|
||||
ctx.throw(400, 'Invalid state');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
ctx.body = JSON.parse(token);
|
||||
} catch (error) {
|
||||
ctx.throw(500, 'Invalid token get');
|
||||
}
|
||||
})
|
||||
.addTo(app);
|
||||
|
||||
app
|
||||
.route({
|
||||
path: 'wx',
|
||||
key: 'mplogin',
|
||||
})
|
||||
.define(async (ctx) => {
|
||||
const state = ctx.query.state;
|
||||
const code = ctx.query.code;
|
||||
try {
|
||||
const wx = new WxServices();
|
||||
const token = await wx.login(code, 'mp');
|
||||
await redis.set(`wx:mp:login:${state}`, JSON.stringify(token), 'EX', 10000); // 30秒过期
|
||||
ctx.body = {
|
||||
token,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
ctx.throw(500, 'Invalid code');
|
||||
}
|
||||
})
|
||||
.addTo(app);
|
||||
|
||||
app
|
||||
.route({
|
||||
path: 'wx',
|
||||
key: 'mp-get-openid',
|
||||
isDebug: true,
|
||||
})
|
||||
.define(async (ctx) => {
|
||||
const code = ctx.query.code;
|
||||
if (!code) {
|
||||
ctx.throw(400, 'code is required');
|
||||
return;
|
||||
}
|
||||
const wx = new WxServices();
|
||||
const mpInfo = await wx.getOpenid(code, 'mp');
|
||||
ctx.body = mpInfo;
|
||||
})
|
||||
.addTo(app);
|
||||
|
||||
app
|
||||
.route({
|
||||
path: 'wx',
|
||||
key: 'open-login',
|
||||
isDebug: true,
|
||||
})
|
||||
.define(async (ctx) => {
|
||||
const code = ctx.query.code;
|
||||
const wx = new WxServices();
|
||||
if (!code) {
|
||||
ctx.throw(400, 'code is required');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const token = await wx.login(code);
|
||||
ctx.body = token;
|
||||
if (!token.accessToken) {
|
||||
ctx.throw(500, 'Invalid code');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
ctx.throw(500, 'Invalid code');
|
||||
}
|
||||
})
|
||||
.addTo(app);
|
||||
Reference in New Issue
Block a user