weixin.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. 'use strict';
  2. const assert = require('assert');
  3. const _ = require('lodash');
  4. const uuid = require('uuid');
  5. const urljoin = require('url-join');
  6. const stringRandom = require('string-random');
  7. const Controller = require('egg').Controller;
  8. const { BusinessError, ErrorCode } = require('naf-core').Error;
  9. /**
  10. * 微信认证,获得openid和用户信息,生成微信Jwt
  11. */
  12. class WeixinController extends Controller {
  13. /**
  14. * 认证流程
  15. * 1. 缓存原始请求地址,生成state和认证回调地址
  16. * 2. 通过wxapi认证,获得认证code
  17. * 3. 通过code获得openid,通过openid,查询绑定用户,创建jwt
  18. * 4. jwt写入redis,返回认证code
  19. * 5. 通过code获取jwt
  20. */
  21. // GET 请求认证
  22. // response_type:
  23. // code - url带上code参数重定向到原始地址
  24. // store - 默认,认证结果写入sessionStore,然后重定向回请求页面(要求请求页面和认证服务在同一域名下)
  25. // token - url带上token参数重定向到原始地址
  26. async auth() {
  27. const { redirect_uri, code, test, type, response_type = 'store', uid, qrcode, msgid, objid } = this.ctx.query;
  28. if (test) {
  29. return await this.authTest();
  30. }
  31. if (code) {
  32. return await this.authBack(this.ctx.query);
  33. }
  34. this.ctx.logger.debug(`[auth] reditect_uri - ${redirect_uri}`);
  35. // assert(redirect_uri, '回调地址不能为空');
  36. // TODO: 保存原始请求地址
  37. // const { config } = this.app;
  38. // console.log('ctx.host: ', this.ctx.host);
  39. // console.log('config.hostHeaders: ', config.hostHeaders);
  40. // TODO: 保存原始请求地址
  41. const state = uuid();
  42. const key = `visit:auth:state:${state}`;
  43. const val = JSON.stringify({ redirect_uri, type, uid, qrcode, msgid, objid });
  44. await this.app.redis.set(key, val, 'EX', 600);
  45. // TODO: 生成回调地址
  46. const { wxapi, authUrl = this.ctx.path } = this.app.config;
  47. const backUrl = encodeURI(`${this.app.config.baseUrl}${this.config.authUrl}?state=${state}`);
  48. const to_uri = encodeURI(`${wxapi.baseUrl}/api/auth?appid=${wxapi.appid}&response_type=code&redirect_uri=${backUrl}#wechat`);
  49. // const backUrl = encodeURI(`${this.app.config.baseUrl}${this.config.authUrl}/`);
  50. // const to_uri = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${wxapi.appid}&response_type=code&scope=snsapi_base&redirect_uri=${backUrl}&state=${state}&connect_redirect=1#wechat_redirect`;
  51. this.ctx.redirect(to_uri);
  52. }
  53. // GET 认证回调
  54. async authBack({ code, state }) {
  55. // const { code, state, type, redirecturi } = this.ctx.query;
  56. this.ctx.logger.debug(`[auth-back] code - ${code}, state - ${state}`);
  57. assert(code, 'code不能为空');
  58. assert(state, 'state不能为空');
  59. const { weixin } = this.ctx.service;
  60. const key = `visit:auth:state:${state}`;
  61. const val = await this.app.redis.get(key);
  62. let openid;
  63. try {
  64. ({ openid } = await weixin.fetch(code));
  65. } catch (err) {
  66. await this.ctx.render('error.njk', { title: err.message, message: err.details });
  67. return;
  68. }
  69. if (openid) {
  70. const { redirect_uri, type, uid, qrcode, msgid, objid } = JSON.parse(val);
  71. const user = await this.ctx.service.user.findByOpenid(openid);
  72. if (type === '0') {
  73. console.log('function in type=0');
  74. // 通过openid取得用户信息
  75. if (user) {
  76. console.log('function in if user');
  77. const token = await this.ctx.service.login.createJwt(user);
  78. if (user.type === '4') {
  79. console.log('function in user.type=4');
  80. // 学生
  81. // 检查学生是否已退出,学生表的isComming是不是2,如果是2 就跳到别的地方提示您已退出
  82. let stu;
  83. try {
  84. stu = await this.ctx.service.student.fetch({ id: user.uid });
  85. } catch (error) {
  86. console.log(`错误信息:${error}`);
  87. const to_uri = urljoin(redirect_uri, `?token=${token}`);
  88. // TODO: 重定性页面
  89. this.ctx.redirect(to_uri);
  90. }
  91. if (stu) {
  92. const { isComming } = stu;
  93. if (isComming && isComming === '2') {
  94. const refuse = `${this.app.config.baseUrl}/msgconfirm/isleave`;
  95. this.ctx.redirect(refuse);
  96. } else {
  97. const to_uri = urljoin(redirect_uri, `?token=${token}`);
  98. // TODO: 重定性页面
  99. this.ctx.redirect(to_uri);
  100. }
  101. } else {
  102. const touri = `${this.app.config.baseUrl}/student/bind`;
  103. const to_uri = urljoin(touri, `?openid=${openid}`);
  104. this.ctx.redirect(to_uri);
  105. }
  106. } else if (user.type === '1') {
  107. // 班主任
  108. const touri = `${this.app.config.baseUrl}/mobiledirtea`;
  109. const to_uri = urljoin(touri, `?token=${token}`);
  110. // TODO: 重定性页面
  111. this.ctx.redirect(to_uri);
  112. } else if (user.type === '3') {
  113. // 教师
  114. const touri = `${this.app.config.baseUrl}/mobiledirtea`;
  115. const to_uri = urljoin(touri, `?token=${token}`);
  116. // TODO: 重定性页面
  117. this.ctx.redirect(to_uri);
  118. }
  119. } else {
  120. // const resunionid = await weixin.fetchUnionID(openid);
  121. const touri = `${this.app.config.baseUrl}/student/bind`;
  122. const to_uri = urljoin(touri, `?openid=${openid}`); // &unionid=${resunionid.unionid}
  123. // TODO: 重定性页面
  124. this.ctx.redirect(to_uri);
  125. }
  126. } else if (type === '1') {
  127. const to_uri = urljoin(redirect_uri, `?openid=${openid}&uid=${uid}&type=${type}&qrcode=${qrcode}`);
  128. // TODO: 重定性页面
  129. this.ctx.redirect(to_uri);
  130. } else if (type === '2') {
  131. const to_uri = urljoin(redirect_uri, `?openid=${openid}&type=${type}&qrcode=${qrcode}`);
  132. // TODO: 重定性页面
  133. this.ctx.redirect(to_uri);
  134. } else if (type === '9') {
  135. // const token = await this.ctx.service.login.createJwt(user);
  136. const to_uri = urljoin(redirect_uri, `?openid=${openid}&type=${type}&msgid=${msgid}&objid=${objid}`);
  137. // TODO: 重定性页面
  138. this.ctx.redirect(to_uri);
  139. }
  140. }
  141. }
  142. // GET 用户授权内部测试接口
  143. async authTest() {
  144. const { redirect_uri, type, uid, qrcode, openid, msgid, objid } = this.ctx.query;
  145. // const openid = stringRandom();
  146. this.ctx.logger.debug(`[auth-test] reditect_uri - ${redirect_uri}, openid - ${openid}`);
  147. assert(redirect_uri, '回调地址不能为空');
  148. assert(openid, 'openid不能为空');
  149. const user = await this.ctx.service.user.findByOpenid(openid);
  150. if (type === '0') {
  151. // 通过openid取得用户信息
  152. if (user) {
  153. const token = await this.ctx.service.login.createJwt(user);
  154. if (user.type === '4') {
  155. const to_uri = urljoin(redirect_uri, `?token=${token}`);
  156. // TODO: 重定性页面
  157. this.ctx.redirect(to_uri);
  158. } else if (user.type === '1') {
  159. const touri = `${this.app.config.baseUrl}/mobiledirtea`;
  160. const to_uri = urljoin(touri, `?token=${token}`);
  161. // TODO: 重定性页面
  162. this.ctx.redirect(to_uri);
  163. } else if (user.type === '3') {
  164. const touri = `${this.app.config.baseUrl}/mobiledirtea`;
  165. const to_uri = urljoin(touri, `?token=${token}`);
  166. // TODO: 重定性页面
  167. this.ctx.redirect(to_uri);
  168. }
  169. } else {
  170. console.log('rrr0000--->' + redirect_uri);
  171. const resunionid = await weixin.fetchUnionID(openid);
  172. const touri = `${this.app.config.baseUrl}/student/bind`;
  173. const to_uri = urljoin(touri, `?openid=${openid}&unionid=${resunionid.unionid}`);
  174. // TODO: 重定性页面
  175. this.ctx.redirect(to_uri);
  176. }
  177. } else if (type === '1') {
  178. const to_uri = urljoin(redirect_uri, `?openid=${openid}&uid=${uid}&type=${type}&qrcode=${qrcode}`);
  179. // TODO: 重定性页面
  180. console.log('1111---?' + to_uri);
  181. this.ctx.redirect(to_uri);
  182. } else if (type === '2') {
  183. const to_uri = urljoin(redirect_uri, `?openid=${openid}&type=${type}&qrcode=${qrcode}`);
  184. // TODO: 重定性页面
  185. console.log('22222---?' + to_uri);
  186. this.ctx.redirect(to_uri);
  187. } else if (type === '9') {
  188. // const token = await this.ctx.service.login.createJwt(user);
  189. const to_uri = urljoin(redirect_uri, `?openid=${openid}&type=${type}&msgid=${msgid}&objid=${objid}`);
  190. // TODO: 重定性页面
  191. console.log('99999---?' + to_uri);
  192. this.ctx.redirect(to_uri);
  193. }
  194. }
  195. // GET 签到小程序请求用户
  196. async appAuth() {
  197. try {
  198. const { js_code, login = true } = this.ctx.query;
  199. console.log(js_code);
  200. const appopenid = await this.ctx.service.weixin.appAuth(js_code);
  201. if (!login) this.ctx.ok(appopenid);
  202. console.warn(`openid=>${appopenid}`);
  203. // const state = uuid();
  204. // const key = `appinfo:${state}`;
  205. // await this.app.redis.set(key, appopenid, 'EX', 600);
  206. const res = await this.ctx.service.user.findByAppOpenid(appopenid);
  207. const obj = { user: res, openid: appopenid };
  208. this.ctx.ok(obj);
  209. } catch (error) {
  210. throw new BusinessError(ErrorCode.NETWORK, '获取小程序信息失败,请尝试重新进入');
  211. }
  212. }
  213. }
  214. module.exports = WeixinController;