weixin.js 8.6 KB

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