egg.js 封装微信小程序openid和session_key的获取

使用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;


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值