egg-获取小程序openid
config.js
const config = {
YOUR_SECRET_STRING: '',
XIAO:{
APP_ID:'',
APP_SECRET:''
},
}
module.exports = config
controller层
async getopenid(){
const { ctx } = this;
const {code}=ctx.request.body
let APP_ID=config.XIAO.APP_ID
let APP_SECRET= config.XIAO.APP_SECRET
const url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + APP_ID + '&secret=' + APP_SECRET + '&js_code=' + code + '&grant_type=authorization_code';
const detail=await ctx.service.xiao.getopenid({url})
ctx.body=detail
}
service层
async getopenid({url}){
const { ctx } = this;
const res = await ctx.curl(url, {
dataType: 'json',
});
if (res.data.openid) {
return {
openid: res.data.openid,
code: 1,
sessionKey: res.data.session_key,
};
}
return { // 忽略网络请求失败
msg: res.data.errmsg,
code: 0,
};
}