weixin.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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.wxInfo = ctx.app.config.wxapi;
  18. this.authBackUrl = `${ctx.app.config.baseUrl}/wxgateway/authBack`;
  19. }
  20. /**
  21. * 网页授权
  22. * @param {String} site 公众号标识,对config中设置
  23. * @param {Object} query 参数
  24. */
  25. async auth({ site }, query) {
  26. const { redirect_uri, ...others } = query;
  27. const { baseUrl } = this.wxInfo;
  28. if (!this.wxInfo[site]) throw new BusinessError(ErrorCode.ACCESS_DENIED, '缺少公众号站点设置');
  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. if (!this.wxInfo[site]) throw new BusinessError(ErrorCode.ACCESS_DENIED, '缺少公众号站点设置');
  78. const { appid } = this.wxInfo[site];
  79. const res = await this.httpGet('/api.weixin.qq.com/cgi-bin/user/info?lang=zh_CN', { appid, openid });
  80. const object = _.pick(res, [ 'nickname', 'headimgurl', 'openid' ]); // 昵称,头像,openid
  81. return { name: object.nickname, icon: object.headimgurl, openid };
  82. }
  83. /**
  84. * JsApi验证
  85. * @param {String} site 公众号标识,对config中设置
  86. * @param {Object} query 参数
  87. */
  88. async jsapiAuth({ site }, query) {
  89. let { url } = query;
  90. url = decodeURIComponent(url);
  91. let jsapi_ticket = await this.app.redis.get(`${site}:${this.jsapiKey}`);
  92. if (!this.wxInfo[site]) throw new BusinessError(ErrorCode.ACCESS_DENIED, '缺少公众号站点设置');
  93. const { appid, appSecret } = this.wxInfo[site];
  94. if (!jsapi_ticket) {
  95. // 1,获取access_token
  96. const atUrl = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${appSecret}`;
  97. const req = await this.ctx.curl(atUrl, { method: 'GET', dataType: 'json' });
  98. if (req.status !== 200) throw new BusinessError(ErrorCode.SERVICE_FAULT, 'access_token获取失败');
  99. const access_token = _.get(req, 'data.access_token');
  100. // 2,获取jsapi_token
  101. const jtUrl = `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${access_token}&type=jsapi`;
  102. const jtReq = await this.ctx.curl(jtUrl, { method: 'GET', dataType: 'json' });
  103. if (jtReq.status !== 200) throw new BusinessError(ErrorCode.SERVICE_FAULT, 'jsapi_ticket获取失败');
  104. jsapi_ticket = _.get(jtReq, 'data.ticket');
  105. // 实际过期时间是7200s(2h),系统默认设置6000s
  106. const expiresIn = _.get(jtReq, 'data.expires_in', 6000);
  107. // 缓存jsapi_ticket,重复使用
  108. await this.app.redis.set(`${site}:${this.jsapiKey}`, jsapi_ticket, 'EX', expiresIn);
  109. }
  110. const noncestr = random(16).toLowerCase();
  111. const timestamp = moment().unix();
  112. const signStr = `jsapi_ticket=${jsapi_ticket}&noncestr=${noncestr}&timestamp=${timestamp}&url=${url}`;
  113. const sign = crypto.createHash('sha1').update(signStr).digest('hex');
  114. return { jsapi_ticket, noncestr, timestamp, sign, appid, url };
  115. }
  116. async createJwt({ openid, nickname, subscribe }) {
  117. const { secret, expiresIn = '1d', issuer = 'weixin' } = this.config.jwt;
  118. const subject = openid;
  119. const userinfo = { nickname, subscribe };
  120. const token = await jwt.sign(userinfo, secret, { expiresIn, issuer, subject });
  121. return token;
  122. }
  123. /**
  124. * 创建二维码
  125. * 随机生成二维码,并保存在Redis中,状态初始为pending
  126. * 状态描述:
  127. * pending - 等待扫码
  128. * consumed - 使用二维码登录完成
  129. * scand:token - Jwt登录凭证
  130. */
  131. async createQrcode() {
  132. const qrcode = uuid();
  133. const key = `visit:qrcode:group:${qrcode}`;
  134. await this.app.redis.set(key, 'pending', 'EX', 600);
  135. return qrcode;
  136. }
  137. /**
  138. * 创建二维码
  139. * 生成群二维码
  140. * 状态描述:
  141. * pending - 等待扫码
  142. * consumed - 使用二维码登录完成
  143. * scand:token - Jwt登录凭证
  144. */
  145. async createQrcodeGroup({ groupid }) {
  146. const { authUrl = this.ctx.path } = this.app.config;
  147. let backUrl;
  148. if (authUrl.startsWith('http')) {
  149. backUrl = encodeURI(`${authUrl}?state=${groupid}`);
  150. } else {
  151. backUrl = encodeURI(`${this.ctx.protocol}://${this.ctx.host}${authUrl}?state=${groupid}`);
  152. }
  153. console.log(backUrl);
  154. return backUrl;
  155. }
  156. /**
  157. * 扫码登录确认
  158. */
  159. async scanQrcode({ qrcode, token }) {
  160. assert(qrcode, 'qrcode不能为空');
  161. assert(token, 'token不能为空');
  162. const key = `smart:qrcode:login:${qrcode}`;
  163. const status = await this.app.redis.get(key);
  164. if (!status) {
  165. throw new BusinessError(ErrorCode.SERVICE_FAULT, '二维码已过期');
  166. }
  167. if (status !== 'pending') {
  168. throw new BusinessError(ErrorCode.SERVICE_FAULT, '二维码状态无效');
  169. }
  170. // 验证Token
  171. const { secret } = this.config.jwt;
  172. const decoded = jwt.verify(token, secret, { issuer: 'weixin' });
  173. this.ctx.logger.debug(`[weixin] qrcode login - ${decoded}`);
  174. // TODO: 修改二维码状态,登录凭证保存到redis
  175. await this.app.redis.set(key, `scaned:${token}`, 'EX', 600);
  176. // TODO: 发布扫码成功消息
  177. const { mq } = this.ctx;
  178. const ex = 'qrcode.login';
  179. if (mq) {
  180. await mq.topic(ex, qrcode, 'scaned', { durable: true });
  181. } else {
  182. this.ctx.logger.error('!!!!!!没有配置MQ插件!!!!!!');
  183. }
  184. }
  185. // 使用二维码换取登录凭证
  186. async qrcodeLogin(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, token ] = val.split(':', 2);
  194. if (status !== 'scaned' || !token) {
  195. throw new BusinessError(ErrorCode.SERVICE_FAULT, '二维码状态无效');
  196. }
  197. // TODO: 修改二维码状态
  198. await this.app.redis.set(key, 'consumed', 'EX', 600);
  199. return { token };
  200. }
  201. // 检查二维码状态
  202. async checkQrcode(qrcode) {
  203. assert(qrcode, 'qrcode不能为空');
  204. const key = `smart:qrcode:login:${qrcode}`;
  205. const val = await this.app.redis.get(key);
  206. if (!val) {
  207. throw new BusinessError(ErrorCode.SERVICE_FAULT, '二维码已过期');
  208. }
  209. const [ status ] = val.split(':', 2);
  210. return { status };
  211. }
  212. }
  213. module.exports = WeixinAuthService;