weixin.js 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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, baseUrl } = 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_userinfo&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. // 获取微信的用户信息
  61. const res = await this.httpGet('/api.weixin.qq.com/cgi-bin/user/info?lang=zh_CN', { appid, openid });
  62. const object = _.pick(res, [ 'nickname', 'headimgurl', 'openid' ]); // 昵称,头像,openid
  63. // 验证获取openid结束,接下来应该返回前端
  64. const key = `${this.prefix}${state}`;
  65. let fqueries = await this.app.redis.get(key);
  66. if (fqueries)fqueries = JSON.parse(fqueries);
  67. let { redirect_uri, groupid, doctorid } = fqueries;
  68. let queryStr = `?openid=${openid}`;
  69. // TODO 验证redirect_uri,如果有groupid,type=group=>用户入驻,直接处理
  70. console.log(fqueries);
  71. if (groupid) {
  72. if (redirect_uri.includes('type=group')) {
  73. // TODO加用户,进组
  74. const udata = { name: object.nickname, icon: object.headimgurl, openid: object.openid, groupid };
  75. try {
  76. await this.ctx.service.patient.create(udata);
  77. } catch (error) {
  78. this.logger.error(error);
  79. }
  80. } else {
  81. // TODO 点击进入群组聊天,不过没改也没加
  82. queryStr = `${queryStr}&groupid=${groupid}`;
  83. }
  84. }
  85. if (doctorid) queryStr = `${queryStr}&doctorid=${doctorid}`;
  86. redirect_uri = urljoin(redirect_uri, queryStr);
  87. console.log(redirect_uri);
  88. this.ctx.redirect(redirect_uri);
  89. }
  90. /**
  91. * JsApi验证
  92. * @param {Object} query 参数
  93. */
  94. async jsapiAuth(query) {
  95. let { url } = query;
  96. url = decodeURIComponent(url);
  97. let jsapi_ticket = await this.app.redis.get(this.jsapiKey);
  98. const { appid, appSecret } = this.wxInfo;
  99. if (!jsapi_ticket) {
  100. // 1,重新获取access_token
  101. const atUrl = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${appSecret}`;
  102. const req = await this.ctx.curl(atUrl, { method: 'GET', dataType: 'json' });
  103. if (req.status !== 200) throw new BusinessError(ErrorCode.SERVICE_FAULT, 'access_token获取失败');
  104. const access_token = _.get(req, 'data.access_token');
  105. // 2,获取jsapi_token
  106. const jtUrl = `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${access_token}&type=jsapi`;
  107. const jtReq = await this.ctx.curl(jtUrl, { method: 'GET', dataType: 'json' });
  108. if (jtReq.status !== 200) throw new BusinessError(ErrorCode.SERVICE_FAULT, 'jsapi_ticket获取失败');
  109. jsapi_ticket = _.get(jtReq, 'data.ticket');
  110. // 实际过期时间是7200s(2h),系统默认设置6000s
  111. const expiresIn = _.get(jtReq, 'data.expires_in', 6000);
  112. // 缓存jsapi_ticket,重复使用
  113. await this.app.redis.set(this.jsapiKey, jsapi_ticket, 'EX', expiresIn);
  114. }
  115. const noncestr = random(16).toLowerCase();
  116. const timestamp = moment().unix();
  117. const signStr = `jsapi_ticket=${jsapi_ticket}&noncestr=${noncestr}&timestamp=${timestamp}&url=${url}`;
  118. const sign = crypto.createHash('sha1').update(signStr).digest('hex');
  119. return { jsapi_ticket, noncestr, timestamp, sign, appid, url };
  120. }
  121. async createJwt({ openid, nickname, subscribe }) {
  122. const { secret, expiresIn = '1d', issuer = 'weixin' } = this.config.jwt;
  123. const subject = openid;
  124. const userinfo = { nickname, subscribe };
  125. const token = await jwt.sign(userinfo, secret, { expiresIn, issuer, subject });
  126. return token;
  127. }
  128. /**
  129. * 创建二维码
  130. * 随机生成二维码,并保存在Redis中,状态初始为pending
  131. * 状态描述:
  132. * pending - 等待扫码
  133. * consumed - 使用二维码登录完成
  134. * scand:token - Jwt登录凭证
  135. */
  136. async createQrcode() {
  137. const qrcode = uuid();
  138. const key = `visit:qrcode:group:${qrcode}`;
  139. await this.app.redis.set(key, 'pending', 'EX', 600);
  140. return qrcode;
  141. }
  142. /**
  143. * 创建二维码
  144. * 生成群二维码
  145. * 状态描述:
  146. * pending - 等待扫码
  147. * consumed - 使用二维码登录完成
  148. * scand:token - Jwt登录凭证
  149. */
  150. async createQrcodeGroup({ groupid }) {
  151. const { authUrl = this.ctx.path } = this.app.config;
  152. let backUrl;
  153. if (authUrl.startsWith('http')) {
  154. backUrl = encodeURI(`${authUrl}?state=${groupid}`);
  155. } else {
  156. backUrl = encodeURI(`${this.ctx.protocol}://${this.ctx.host}${authUrl}?state=${groupid}`);
  157. }
  158. console.log(backUrl);
  159. return backUrl;
  160. }
  161. /**
  162. * 扫码登录确认
  163. */
  164. async scanQrcode({ qrcode, token }) {
  165. assert(qrcode, 'qrcode不能为空');
  166. assert(token, 'token不能为空');
  167. const key = `smart:qrcode:login:${qrcode}`;
  168. const status = await this.app.redis.get(key);
  169. if (!status) {
  170. throw new BusinessError(ErrorCode.SERVICE_FAULT, '二维码已过期');
  171. }
  172. if (status !== 'pending') {
  173. throw new BusinessError(ErrorCode.SERVICE_FAULT, '二维码状态无效');
  174. }
  175. // 验证Token
  176. const { secret } = this.config.jwt;
  177. const decoded = jwt.verify(token, secret, { issuer: 'weixin' });
  178. this.ctx.logger.debug(`[weixin] qrcode login - ${decoded}`);
  179. // TODO: 修改二维码状态,登录凭证保存到redis
  180. await this.app.redis.set(key, `scaned:${token}`, 'EX', 600);
  181. // TODO: 发布扫码成功消息
  182. const { mq } = this.ctx;
  183. const ex = 'qrcode.login';
  184. if (mq) {
  185. await mq.topic(ex, qrcode, 'scaned', { durable: true });
  186. } else {
  187. this.ctx.logger.error('!!!!!!没有配置MQ插件!!!!!!');
  188. }
  189. }
  190. // 使用二维码换取登录凭证
  191. async qrcodeLogin(qrcode) {
  192. assert(qrcode, 'qrcode不能为空');
  193. const key = `smart:qrcode:login:${qrcode}`;
  194. const val = await this.app.redis.get(key);
  195. if (!val) {
  196. throw new BusinessError(ErrorCode.SERVICE_FAULT, '二维码已过期');
  197. }
  198. const [ status, token ] = val.split(':', 2);
  199. if (status !== 'scaned' || !token) {
  200. throw new BusinessError(ErrorCode.SERVICE_FAULT, '二维码状态无效');
  201. }
  202. // TODO: 修改二维码状态
  203. await this.app.redis.set(key, 'consumed', 'EX', 600);
  204. return { token };
  205. }
  206. // 检查二维码状态
  207. async checkQrcode(qrcode) {
  208. assert(qrcode, 'qrcode不能为空');
  209. const key = `smart:qrcode:login:${qrcode}`;
  210. const val = await this.app.redis.get(key);
  211. if (!val) {
  212. throw new BusinessError(ErrorCode.SERVICE_FAULT, '二维码已过期');
  213. }
  214. const [ status ] = val.split(':', 2);
  215. return { status };
  216. }
  217. }
  218. module.exports = WeixinAuthService;