weixin.js 9.7 KB

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