weixin.js 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. 'use strict';
  2. const assert = require('assert');
  3. const uuid = require('uuid');
  4. const _ = require('lodash');
  5. const { BusinessError, ErrorCode } = require('naf-core').Error;
  6. const jwt = require('jsonwebtoken');
  7. const { AxiosService } = require('naf-framework-mongoose/lib/service');
  8. class WeixinAuthService extends AxiosService {
  9. constructor(ctx) {
  10. super(ctx, {}, _.get(ctx.app.config, 'wxapi'));
  11. }
  12. // 通过认证码获得用户信息
  13. async fetch(code) {
  14. // TODO:参数检查和默认参数处理
  15. assert(code);
  16. const { wxapi } = this.app.config;
  17. let res = await this.httpGet('/api/fetch', { code });
  18. if (res.errcode && res.errcode !== 0) {
  19. this.ctx.logger.error(`[WeixinAuthService] fetch open by code fail, errcode: ${res.errcode}, errmsg: ${res.errmsg}`);
  20. throw new BusinessError(ErrorCode.SERVICE_FAULT, '获得微信认证信息失败');
  21. }
  22. const { openid } = res;
  23. // TODO: 获得用户信息
  24. res = await this.httpGet('/api.weixin.qq.com/cgi-bin/user/info?lang=zh_CN', { appid: wxapi.appid, openid });
  25. // console.debug('res: ', res);
  26. if (res.errcode && res.errcode !== 0) {
  27. this.ctx.logger.error(`[WeixinAuthService] fetch userinfo by openid fail, errcode: ${res.errcode}, errmsg: ${res.errmsg}`);
  28. throw new BusinessError(ErrorCode.SERVICE_FAULT, '获得微信用户信息失败');
  29. }
  30. return res;
  31. }
  32. async createJwt({ openid, nickname, subscribe }) {
  33. const { secret, expiresIn = '1d', issuer = 'weixin' } = this.config.jwt;
  34. const subject = openid;
  35. const userinfo = { nickname, subscribe };
  36. const token = await jwt.sign(userinfo, secret, { expiresIn, issuer, subject });
  37. return token;
  38. }
  39. /**
  40. * 创建二维码
  41. * 随机生成二维码,并保存在Redis中,状态初始为pending
  42. * 状态描述:
  43. * pending - 等待扫码
  44. * consumed - 使用二维码登录完成
  45. * scand:token - Jwt登录凭证
  46. */
  47. async createQrcode() {
  48. const qrcode = uuid();
  49. const key = `visit:qrcode:group:${qrcode}`;
  50. await this.app.redis.set(key, 'pending', 'EX', 600);
  51. return qrcode;
  52. }
  53. /**
  54. * 创建二维码
  55. * 生成群二维码
  56. * 状态描述:
  57. * pending - 等待扫码
  58. * consumed - 使用二维码登录完成
  59. * scand:token - Jwt登录凭证
  60. */
  61. async createQrcodeGroup({ groupid }) {
  62. const { authUrl = this.ctx.path } = this.app.config;
  63. let backUrl;
  64. if (authUrl.startsWith('http')) {
  65. backUrl = encodeURI(`${authUrl}?state=${groupid}`);
  66. } else {
  67. backUrl = encodeURI(`${this.ctx.protocol}://${this.ctx.host}${authUrl}?state=${groupid}`);
  68. }
  69. console.log(backUrl);
  70. return backUrl;
  71. }
  72. /**
  73. * 扫码登录确认
  74. */
  75. async scanQrcode({ qrcode, token }) {
  76. assert(qrcode, 'qrcode不能为空');
  77. assert(token, 'token不能为空');
  78. const key = `smart:qrcode:login:${qrcode}`;
  79. const status = await this.app.redis.get(key);
  80. if (!status) {
  81. throw new BusinessError(ErrorCode.SERVICE_FAULT, '二维码已过期');
  82. }
  83. if (status !== 'pending') {
  84. throw new BusinessError(ErrorCode.SERVICE_FAULT, '二维码状态无效');
  85. }
  86. // 验证Token
  87. const { secret } = this.config.jwt;
  88. const decoded = jwt.verify(token, secret, { issuer: 'weixin' });
  89. this.ctx.logger.debug(`[weixin] qrcode login - ${decoded}`);
  90. // TODO: 修改二维码状态,登录凭证保存到redis
  91. await this.app.redis.set(key, `scaned:${token}`, 'EX', 600);
  92. // TODO: 发布扫码成功消息
  93. const { mq } = this.ctx;
  94. const ex = 'qrcode.login';
  95. if (mq) {
  96. await mq.topic(ex, qrcode, 'scaned', { durable: true });
  97. } else {
  98. this.ctx.logger.error('!!!!!!没有配置MQ插件!!!!!!');
  99. }
  100. }
  101. // 使用二维码换取登录凭证
  102. async qrcodeLogin(qrcode) {
  103. assert(qrcode, 'qrcode不能为空');
  104. const key = `smart:qrcode:login:${qrcode}`;
  105. const val = await this.app.redis.get(key);
  106. if (!val) {
  107. throw new BusinessError(ErrorCode.SERVICE_FAULT, '二维码已过期');
  108. }
  109. const [ status, token ] = val.split(':', 2);
  110. if (status !== 'scaned' || !token) {
  111. throw new BusinessError(ErrorCode.SERVICE_FAULT, '二维码状态无效');
  112. }
  113. // TODO: 修改二维码状态
  114. await this.app.redis.set(key, 'consumed', 'EX', 600);
  115. return { token };
  116. }
  117. // 检查二维码状态
  118. async checkQrcode(qrcode) {
  119. assert(qrcode, 'qrcode不能为空');
  120. const key = `smart:qrcode:login:${qrcode}`;
  121. const val = await this.app.redis.get(key);
  122. if (!val) {
  123. throw new BusinessError(ErrorCode.SERVICE_FAULT, '二维码已过期');
  124. }
  125. const [ status ] = val.split(':', 2);
  126. return { status };
  127. }
  128. // 发送微信模板消息
  129. async sendTemplateMsg(templateid, openid, first, keyword1, keyword2, remark, tourl) {
  130. const url = this.ctx.app.config.sendDirMq + this.ctx.app.config.appid;
  131. let _url = '';
  132. if (tourl) {
  133. _url = this.ctx.app.config.baseUrl + '/api/train/auth?state=1&redirect_uri=' + this.ctx.app.config.baseUrl + '/classinfo/&type=template&objid=' + tourl;
  134. }
  135. const requestData = { // 发送模板消息的数据
  136. touser: openid,
  137. template_id: templateid,
  138. url: _url,
  139. data: {
  140. first: {
  141. value: first,
  142. color: '#173177',
  143. },
  144. keyword1: {
  145. value: keyword1,
  146. color: '#1d1d1d',
  147. },
  148. keyword2: {
  149. value: keyword2,
  150. color: '#1d1d1d',
  151. },
  152. remark: {
  153. value: remark,
  154. color: '#173177',
  155. },
  156. },
  157. };
  158. console.log('templateid---' + templateid);
  159. console.log('openid---' + openid);
  160. console.log('requestData---' + JSON.stringify(requestData));
  161. await this.ctx.curl(url, {
  162. method: 'post',
  163. headers: {
  164. 'content-type': 'application/json',
  165. },
  166. dataType: 'json',
  167. data: JSON.stringify(requestData),
  168. });
  169. }
  170. }
  171. module.exports = WeixinAuthService;