鉴权完成,并修复小程序接口拦截器问题
This commit is contained in:
11
server/app/controller/product.js
Normal file
11
server/app/controller/product.js
Normal file
@@ -0,0 +1,11 @@
|
||||
const Controller = require("egg").Controller
|
||||
|
||||
class Product extends Controller {
|
||||
async list() {
|
||||
const {ctx: {query}} = this
|
||||
this.ctx.body = {code: 0, data: []}
|
||||
this.ctx.status = 200
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Product
|
||||
41
server/app/controller/wxmp.js
Normal file
41
server/app/controller/wxmp.js
Normal file
@@ -0,0 +1,41 @@
|
||||
const Controller = require("egg").Controller
|
||||
|
||||
const wxmpConfig = {
|
||||
appid: "wx68ef6cfaa104652a",
|
||||
secret: "4dccf2429685eb8787b984d61ae69119"
|
||||
}
|
||||
const table = "sys_user"
|
||||
/**
|
||||
* 微信小程序code转unionid
|
||||
* @param ctx
|
||||
* @returns {Promise<*>}
|
||||
*/
|
||||
const code2Openid = async ctx => {
|
||||
const result = await ctx.curl("https://api.weixin.qq.com/sns/jscode2session", {
|
||||
data: {
|
||||
...wxmpConfig,
|
||||
js_code: ctx.query.code, // 登录时获取的 code
|
||||
grant_type: 'authorization_code' // 授权类型,此处只需填写 authorization_code
|
||||
},
|
||||
dataType: "json"
|
||||
})
|
||||
return result.data?.openid
|
||||
}
|
||||
|
||||
class WeixinMP extends Controller {
|
||||
async token() {
|
||||
const {ctx: {query}, app} = this
|
||||
if (!!query.code) {
|
||||
const wechatOpenId = await code2Openid(this.ctx)
|
||||
if (!wechatOpenId) return this.ctx.body = {code: 1, msg: "鉴权失败,无法获取openid"}
|
||||
const user = await app.mysql.get(table, {wechatOpenId})
|
||||
const {name, avatar} = query
|
||||
const result = await this.service.db.addOrUpdate(table, {name, avatar, wechatOpenId, id: user?.id})
|
||||
const token = app.jwt.sign({id: result.data?.id}, app.config.jwt.secret)
|
||||
this.ctx.body = {code: 0, data: "bearer " + token}
|
||||
} else this.ctx.body = {code: 1, msg: "缺少必要参数(code)"}
|
||||
this.ctx.status = 200
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WeixinMP
|
||||
Reference in New Issue
Block a user