weixin.js 8.9 KB

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