weixin.js 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. 'use strict';
  2. const assert = require('assert');
  3. const uuid = require('uuid');
  4. const _ = require('lodash');
  5. const { BusinessError, ErrorCode } = require('naf-core').Error;
  6. const jwt = require('jsonwebtoken');
  7. const { AxiosService } = require('naf-framework-mongoose/lib/service');
  8. class WeixinAuthService extends AxiosService {
  9. constructor(ctx) {
  10. super(ctx, {}, _.get(ctx.app.config, 'wxapi'));
  11. }
  12. // 通过认证码获得用户信息
  13. async fetch(code) {
  14. // TODO:参数检查和默认参数处理
  15. assert(code);
  16. const { wxapi } = this.app.config;
  17. const res = await this.httpGet('/api/fetch', { code });
  18. if (res.errcode && res.errcode !== 0) {
  19. this.ctx.logger.error(
  20. `[WeixinAuthService] fetch open by code fail, errcode: ${res.errcode}, errmsg: ${res.errmsg}`
  21. );
  22. throw new BusinessError(ErrorCode.SERVICE_FAULT, '获得微信认证信息失败');
  23. }
  24. this.ctx.logger.info(`auth=>${JSON.stringify(res)}`);
  25. // const reqUrl = 'https://api.weixin.qq.com/sns/oauth2/access_token';
  26. // const params = {
  27. // appid: wxapi.appid,
  28. // secret: wxapi.appSecret,
  29. // code,
  30. // grant_type: 'authorization_code',
  31. // };
  32. // const res = await this.httpGet(reqUrl, params);
  33. if (res.errcode && res.errcode !== 0) {
  34. this.ctx.logger.error(`[WeixinAuthService] fetch open by code fail, errcode: ${res.errcode}, errmsg: ${res.errmsg}`);
  35. throw new BusinessError(ErrorCode.SERVICE_FAULT, '获得微信认证信息失败');
  36. }
  37. // const { openid } = res;
  38. return res;
  39. }
  40. // 通过openid获得用户信息
  41. async fetchUnionID(openid) {
  42. // TODO:参数检查和默认参数处理
  43. assert(openid);
  44. const appid = 'wxdf3ed83c095be97a';
  45. const grant_type = 'client_credential';
  46. const secret = '748df7c2a75077a79ae0c971b1638244';
  47. // TODO: 获得用户信息
  48. const url = 'http://wx.cc-lotus.info/api.weixin.qq.com/cgi-bin/token?appid=' + appid + '&grant_type=' + grant_type + '&secret=' + secret;
  49. const res = await this.ctx.curl(url, {
  50. method: 'get',
  51. headers: {
  52. 'content-type': 'application/json',
  53. },
  54. dataType: 'json',
  55. });
  56. // console.debug('res: ', res);
  57. if (res.errcode && res.errcode !== 0) {
  58. this.ctx.logger.error(`[WeixinAuthService] fetch userinfo by openid fail, errcode: ${res.errcode}, errmsg: ${res.errmsg}`);
  59. throw new BusinessError(ErrorCode.SERVICE_FAULT, '获得微信用户信息失败');
  60. }
  61. const token = res.access_token;
  62. const urlun = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token=' + token + '&openid=' + openid + '&lang=zh_CN';
  63. const result = await this.ctx.curl(urlun, {
  64. method: 'get',
  65. headers: {
  66. 'content-type': 'application/json',
  67. },
  68. dataType: 'json',
  69. });
  70. // console.debug('res: ', res);
  71. if (result.errcode && result.errcode !== 0) {
  72. this.ctx.logger.error(`[WeixinAuthService] fetch userinfo by openid fail, errcode: ${res.errcode}, errmsg: ${res.errmsg}`);
  73. throw new BusinessError(ErrorCode.SERVICE_FAULT, '获得微信用户信息失败');
  74. }
  75. return result;
  76. }
  77. async createJwt({ openid, nickname, subscribe }) {
  78. const { secret, expiresIn = '1d', issuer = 'weixin' } = this.config.jwt;
  79. const subject = openid;
  80. const userinfo = { nickname, subscribe };
  81. const token = await jwt.sign(userinfo, secret, { expiresIn, issuer, subject });
  82. return token;
  83. }
  84. /**
  85. * 创建二维码
  86. * 随机生成二维码,并保存在Redis中,状态初始为pending
  87. * 状态描述:
  88. * pending - 等待扫码
  89. * consumed - 使用二维码登录完成
  90. * scand:token - Jwt登录凭证
  91. */
  92. async createQrcode() {
  93. const qrcode = uuid();
  94. const key = `visit:qrcode:group:${qrcode}`;
  95. await this.app.redis.set(key, 'pending', 'EX', 600);
  96. return qrcode;
  97. }
  98. /**
  99. * 创建二维码
  100. * 生成群二维码
  101. * 状态描述:
  102. * pending - 等待扫码
  103. * consumed - 使用二维码登录完成
  104. * scand:token - Jwt登录凭证
  105. */
  106. async createQrcodeGroup({ groupid }) {
  107. const { authUrl = this.ctx.path } = this.app.config;
  108. let backUrl;
  109. if (authUrl.startsWith('http')) {
  110. backUrl = encodeURI(`${authUrl}?state=${groupid}`);
  111. } else {
  112. backUrl = encodeURI(`${this.ctx.protocol}://${this.ctx.host}${authUrl}?state=${groupid}`);
  113. }
  114. return backUrl;
  115. }
  116. /**
  117. * 扫码登录确认
  118. */
  119. async scanQrcode({ qrcode, token }) {
  120. assert(qrcode, 'qrcode不能为空');
  121. assert(token, 'token不能为空');
  122. const key = `smart:qrcode:login:${qrcode}`;
  123. const status = await this.app.redis.get(key);
  124. if (!status) {
  125. throw new BusinessError(ErrorCode.SERVICE_FAULT, '二维码已过期');
  126. }
  127. if (status !== 'pending') {
  128. throw new BusinessError(ErrorCode.SERVICE_FAULT, '二维码状态无效');
  129. }
  130. // 验证Token
  131. const { secret } = this.config.jwt;
  132. const decoded = jwt.verify(token, secret, { issuer: 'weixin' });
  133. this.ctx.logger.debug(`[weixin] qrcode login - ${decoded}`);
  134. // TODO: 修改二维码状态,登录凭证保存到redis
  135. await this.app.redis.set(key, `scaned:${token}`, 'EX', 600);
  136. // TODO: 发布扫码成功消息
  137. const { mq } = this.ctx;
  138. const ex = 'qrcode.login';
  139. if (mq) {
  140. await mq.topic(ex, qrcode, 'scaned', { durable: true });
  141. } else {
  142. this.ctx.logger.error('!!!!!!没有配置MQ插件!!!!!!');
  143. }
  144. }
  145. // 使用二维码换取登录凭证
  146. async qrcodeLogin(qrcode) {
  147. assert(qrcode, 'qrcode不能为空');
  148. const key = `smart:qrcode:login:${qrcode}`;
  149. const val = await this.app.redis.get(key);
  150. if (!val) {
  151. throw new BusinessError(ErrorCode.SERVICE_FAULT, '二维码已过期');
  152. }
  153. const [ status, token ] = val.split(':', 2);
  154. if (status !== 'scaned' || !token) {
  155. throw new BusinessError(ErrorCode.SERVICE_FAULT, '二维码状态无效');
  156. }
  157. // TODO: 修改二维码状态
  158. await this.app.redis.set(key, 'consumed', 'EX', 600);
  159. return { token };
  160. }
  161. // 检查二维码状态
  162. async checkQrcode(qrcode) {
  163. assert(qrcode, 'qrcode不能为空');
  164. const key = `smart:qrcode:login:${qrcode}`;
  165. const val = await this.app.redis.get(key);
  166. if (!val) {
  167. throw new BusinessError(ErrorCode.SERVICE_FAULT, '二维码已过期');
  168. }
  169. const [ status ] = val.split(':', 2);
  170. return { status };
  171. }
  172. // 发送微信模板消息
  173. async sendTemplateMsg(templateid, openid, first, keyword1, keyword2, remark, tourl) {
  174. const { wxapi } = this.ctx.app.config;
  175. const url = wxapi.sendDirMq + wxapi.appid;
  176. let _url = '';
  177. if (tourl) {
  178. // 通过openid取得用户基本信息
  179. const user = await this.ctx.model.User.findOne({ openid });
  180. const newdata = { openid, name: user.name, title: first, detail: keyword1, date: keyword2, remark, status: '0' };
  181. const res = await this.ctx.model.Message.create(newdata);
  182. // 需要回执的时候进行保存处理
  183. _url = this.ctx.app.config.baseUrl + '/api/train/auth?state=1&redirect_uri=' + this.ctx.app.config.baseUrl + '/classinfo/&type=9&objid=' + tourl + '&msgid=' + res.id;
  184. }
  185. const requestData = { // 发送模板消息的数据
  186. touser: openid,
  187. template_id: templateid,
  188. url: _url,
  189. data: {
  190. first: {
  191. value: first,
  192. color: '#173177',
  193. },
  194. keyword1: {
  195. value: keyword1,
  196. color: '#1d1d1d',
  197. },
  198. keyword2: {
  199. value: keyword2,
  200. color: '#1d1d1d',
  201. },
  202. remark: {
  203. value: remark,
  204. color: '#173177',
  205. },
  206. },
  207. };
  208. await this.ctx.curl(url, {
  209. method: 'post',
  210. headers: {
  211. 'content-type': 'application/json',
  212. },
  213. dataType: 'json',
  214. data: JSON.stringify(requestData),
  215. });
  216. }
  217. // 发送微信模板消息自定义消息
  218. async sendTemplateDesign(templateid, openid, first, keyword1, keyword2, remark, tourl) {
  219. const { wxapi } = this.ctx.app.config;
  220. const url = wxapi.sendDirMq + wxapi.appid;
  221. const requestData = { // 发送模板消息的数据
  222. touser: openid,
  223. template_id: templateid,
  224. url: tourl,
  225. data: {
  226. first: {
  227. value: first,
  228. color: '#173177',
  229. },
  230. keyword1: {
  231. value: keyword1,
  232. color: '#1d1d1d',
  233. },
  234. keyword2: {
  235. value: keyword2,
  236. color: '#1d1d1d',
  237. },
  238. remark: {
  239. value: remark,
  240. color: '#173177',
  241. },
  242. },
  243. };
  244. const res = await this.ctx.curl(url, {
  245. method: 'post',
  246. headers: {
  247. 'content-type': 'application/json',
  248. },
  249. dataType: 'json',
  250. data: JSON.stringify(requestData),
  251. });
  252. }
  253. // 小程序登录
  254. async appAuth(js_code) {
  255. const { wxapp } = this.app.config;
  256. if (!wxapp) return;
  257. let url = 'https://api.weixin.qq.com/sns/jscode2session';
  258. let query = `?js_code=${js_code}`;
  259. const keys = Object.keys(wxapp);
  260. for (const key of keys) {
  261. query = `${query}&${key}=${wxapp[key]}`;
  262. }
  263. url = `${url}${query}`;
  264. const res = await this.ctx.curl(url, {
  265. method: 'get',
  266. headers: {
  267. 'content-type': 'application/json',
  268. },
  269. dataType: 'json',
  270. });
  271. const { openid } = res.data;
  272. if (!openid) throw new BusinessError(ErrorCode.BUSINESS, '未获取到openid', '未获取到openid');
  273. return openid;
  274. }
  275. }
  276. module.exports = WeixinAuthService;