weixin.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. 'use strict';
  2. const assert = require('assert');
  3. const uuid = require('uuid');
  4. const random = require('string-random');
  5. const crypto = require('crypto');
  6. const urljoin = require('url-join');
  7. const _ = require('lodash');
  8. const moment = require('moment');
  9. const { BusinessError, ErrorCode } = require('naf-core').Error;
  10. const jwt = require('jsonwebtoken');
  11. const { AxiosService } = require('naf-framework-mongoose/lib/service');
  12. class WeixinAuthService extends AxiosService {
  13. constructor(ctx) {
  14. super(ctx, {}, _.get(ctx.app.config, 'wxapi'));
  15. this.prefix = 'visit-auth:';
  16. this.jsapiKey = 'visit-access_token';
  17. this.wxInfo = ctx.app.config.wxapi;
  18. this.authBackUrl = `${ctx.app.config.baseUrl}/api/visit/authBack`;
  19. }
  20. /**
  21. * 网页授权
  22. * @param {Object} query 参数
  23. */
  24. async auth(query) {
  25. const { redirect_uri, ...others } = query;
  26. const { appid } = this.wxInfo;
  27. if (!appid) {
  28. throw new BusinessError(ErrorCode.SERVICE_FAULT, '缺少公众号设置');
  29. }
  30. // 用于redis
  31. const state = uuid.v4();
  32. const key = `${this.prefix}${state}`;
  33. const val = JSON.stringify({ ...others, redirect_uri });
  34. await this.app.redis.set(key, val, 'EX', 600);
  35. const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${this.authBackUrl}&response_type=code&scope=snsapi_base&state=${state}#wechat_redirect`;
  36. this.ctx.redirect(url);
  37. }
  38. /**
  39. * 网页授权回调,获取openid
  40. * @param {Object} query 参数
  41. */
  42. async authBack(query) {
  43. const { code, state } = query;
  44. if (!code) throw new BusinessError(ErrorCode.SERVICE_FAULT, '授权未成功');
  45. const { appid, appSecret } = this.wxInfo;
  46. const url = 'https://api.weixin.qq.com/sns/oauth2/access_token';
  47. const params = {
  48. appid,
  49. secret: appSecret,
  50. code,
  51. grant_type: 'authorization_code',
  52. };
  53. const req = await this.httpGet(url, params);
  54. if (req.errcode && req.errcode !== 0) throw new BusinessError(ErrorCode.SERVICE_FAULT, 'openid获取失败');
  55. const openid = _.get(req, 'openid');
  56. if (!openid) {
  57. this.ctx.logger.error(JSON.stringify(req.data));
  58. throw new BusinessError(ErrorCode.SERVICE_FAULT, '未获取到openid');
  59. }
  60. // 验证获取openid结束,接下来应该返回前端
  61. const key = `${this.prefix}${state}`;
  62. let fqueries = await this.app.redis.get(key);
  63. if (fqueries)fqueries = JSON.parse(fqueries);
  64. let { redirect_uri, groupid, doctorid } = fqueries;
  65. let queryStr = `?openid=${openid}`;
  66. if (groupid) queryStr = `${queryStr}&groupid=${groupid}`;
  67. if (doctorid) queryStr = `${queryStr}&doctorid=${doctorid}`;
  68. redirect_uri = urljoin(redirect_uri, queryStr);
  69. this.ctx.redirect(redirect_uri);
  70. }
  71. /**
  72. * JsApi验证
  73. * @param {Object} query 参数
  74. */
  75. async jsapiAuth(query) {
  76. let { url } = query;
  77. url = decodeURIComponent(url);
  78. let jsapi_ticket = await this.app.redis.get(this.jsapiKey);
  79. const { appid, appSecret } = this.wxInfo;
  80. if (!jsapi_ticket) {
  81. // 1,重新获取access_token
  82. const atUrl = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${appSecret}`;
  83. const req = await this.ctx.curl(atUrl, { method: 'GET', dataType: 'json' });
  84. if (req.status !== 200) throw new BusinessError(ErrorCode.SERVICE_FAULT, 'access_token获取失败');
  85. const access_token = _.get(req, 'data.access_token');
  86. // 2,获取jsapi_token
  87. const jtUrl = `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${access_token}&type=jsapi`;
  88. const jtReq = await this.ctx.curl(jtUrl, { method: 'GET', dataType: 'json' });
  89. if (jtReq.status !== 200) throw new BusinessError(ErrorCode.SERVICE_FAULT, 'jsapi_ticket获取失败');
  90. jsapi_ticket = _.get(jtReq, 'data.ticket');
  91. // 实际过期时间是7200s(2h),系统默认设置6000s
  92. const expiresIn = _.get(jtReq, 'data.expires_in', 6000);
  93. // 缓存jsapi_ticket,重复使用
  94. await this.app.redis.set(this.jsapiKey, jsapi_ticket, 'EX', expiresIn);
  95. }
  96. const noncestr = random(16).toLowerCase();
  97. const timestamp = moment().unix();
  98. const signStr = `jsapi_ticket=${jsapi_ticket}&noncestr=${noncestr}&timestamp=${timestamp}&url=${url}`;
  99. const sign = crypto.createHash('sha1').update(signStr).digest('hex');
  100. return { jsapi_ticket, noncestr, timestamp, sign, appid, url };
  101. }
  102. async createJwt({ openid, nickname, subscribe }) {
  103. const { secret, expiresIn = '1d', issuer = 'weixin' } = this.config.jwt;
  104. const subject = openid;
  105. const userinfo = { nickname, subscribe };
  106. const token = await jwt.sign(userinfo, secret, { expiresIn, issuer, subject });
  107. return token;
  108. }
  109. /**
  110. * 创建二维码
  111. * 随机生成二维码,并保存在Redis中,状态初始为pending
  112. * 状态描述:
  113. * pending - 等待扫码
  114. * consumed - 使用二维码登录完成
  115. * scand:token - Jwt登录凭证
  116. */
  117. async createQrcode() {
  118. const qrcode = uuid();
  119. const key = `visit:qrcode:group:${qrcode}`;
  120. await this.app.redis.set(key, 'pending', 'EX', 600);
  121. return qrcode;
  122. }
  123. /**
  124. * 创建二维码
  125. * 生成群二维码
  126. * 状态描述:
  127. * pending - 等待扫码
  128. * consumed - 使用二维码登录完成
  129. * scand:token - Jwt登录凭证
  130. */
  131. async createQrcodeGroup({ groupid }) {
  132. const { authUrl = this.ctx.path } = this.app.config;
  133. let backUrl;
  134. if (authUrl.startsWith('http')) {
  135. backUrl = encodeURI(`${authUrl}?state=${groupid}`);
  136. } else {
  137. backUrl = encodeURI(`${this.ctx.protocol}://${this.ctx.host}${authUrl}?state=${groupid}`);
  138. }
  139. console.log(backUrl);
  140. return backUrl;
  141. }
  142. /**
  143. * 扫码登录确认
  144. */
  145. async scanQrcode({ qrcode, token }) {
  146. assert(qrcode, 'qrcode不能为空');
  147. assert(token, 'token不能为空');
  148. const key = `smart:qrcode:login:${qrcode}`;
  149. const status = await this.app.redis.get(key);
  150. if (!status) {
  151. throw new BusinessError(ErrorCode.SERVICE_FAULT, '二维码已过期');
  152. }
  153. if (status !== 'pending') {
  154. throw new BusinessError(ErrorCode.SERVICE_FAULT, '二维码状态无效');
  155. }
  156. // 验证Token
  157. const { secret } = this.config.jwt;
  158. const decoded = jwt.verify(token, secret, { issuer: 'weixin' });
  159. this.ctx.logger.debug(`[weixin] qrcode login - ${decoded}`);
  160. // TODO: 修改二维码状态,登录凭证保存到redis
  161. await this.app.redis.set(key, `scaned:${token}`, 'EX', 600);
  162. // TODO: 发布扫码成功消息
  163. const { mq } = this.ctx;
  164. const ex = 'qrcode.login';
  165. if (mq) {
  166. await mq.topic(ex, qrcode, 'scaned', { durable: true });
  167. } else {
  168. this.ctx.logger.error('!!!!!!没有配置MQ插件!!!!!!');
  169. }
  170. }
  171. // 使用二维码换取登录凭证
  172. async qrcodeLogin(qrcode) {
  173. assert(qrcode, 'qrcode不能为空');
  174. const key = `smart:qrcode:login:${qrcode}`;
  175. const val = await this.app.redis.get(key);
  176. if (!val) {
  177. throw new BusinessError(ErrorCode.SERVICE_FAULT, '二维码已过期');
  178. }
  179. const [ status, token ] = val.split(':', 2);
  180. if (status !== 'scaned' || !token) {
  181. throw new BusinessError(ErrorCode.SERVICE_FAULT, '二维码状态无效');
  182. }
  183. // TODO: 修改二维码状态
  184. await this.app.redis.set(key, 'consumed', 'EX', 600);
  185. return { token };
  186. }
  187. // 检查二维码状态
  188. async checkQrcode(qrcode) {
  189. assert(qrcode, 'qrcode不能为空');
  190. const key = `smart:qrcode:login:${qrcode}`;
  191. const val = await this.app.redis.get(key);
  192. if (!val) {
  193. throw new BusinessError(ErrorCode.SERVICE_FAULT, '二维码已过期');
  194. }
  195. const [ status ] = val.split(':', 2);
  196. return { status };
  197. }
  198. }
  199. module.exports = WeixinAuthService;