weixin.js 7.5 KB

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