使用auth.code2Session,通过 wx.login 接口获得临时登录凭证 code 后传到开发者服务器调用此接口完成登录流程。
创建公用Service app/service/base.js
'use strict';
const Service = require('egg').Service;
class BaseService extends Service {
}
module.exports = BaseService;
配置appid和secret config/config.default.js
/* eslint valid-jsdoc: "off" */
'use strict';
/**
* @param {Egg.EggAppInfo} appInfo app info
*/
module.exports = appInfo => {
/**
* built-in config
* @type {Egg.EggAppConfig}
**/
const config = exports = {};
// 微信小程序信息配置
config.wxApp = {
one: { // pyp答题窗小程序
appid: '',
secret: '',
},
two: { // 阿龙团拼小程序
appid: '',
secret: '',
},
};
return {
...config,
};
};
创建service app/wx_app_api/login.js
'use strict';
const BaseService = require('../core/base');
class LoginService extends BaseService {
/**
* 获取openid
* @param {*} code 前端wx.login获取的code登录码
* @param {*} num config中配置的小程序的标识
*/
async code2Session(code, num = 'one') {
const { ctx } = this;
const wxApp = this.config.wxApp[num];
const url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + wxApp.appid + '&secret=' + wxApp.secret + '&js_code=' + code + '&grant_type=authorization_code';
const res = await ctx.curl(url, {
dataType: 'json',
});
if (res.data.openid) {
return {
openid: res.data.openid,
sta: true,
sessionKey: res.data.session_key,
};
}
return { // 忽略网络请求失败
msg: res.data.errmsg,
sta: false,
};
}
}
module.exports = LoginService;