weixin.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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. /**
  9. * 微信认证,获得openid和用户信息,生成微信Jwt
  10. */
  11. class WeixinController extends Controller {
  12. /**
  13. * 认证流程
  14. * 1. 缓存原始请求地址,生成state和认证回调地址
  15. * 2. 通过wxapi认证,获得认证code
  16. * 3. 通过code获得openid,通过openid,查询绑定用户,创建jwt
  17. * 4. jwt写入redis,返回认证code
  18. * 5. 通过code获取jwt
  19. */
  20. // GET 请求认证
  21. // response_type:
  22. // code - url带上code参数重定向到原始地址
  23. // store - 默认,认证结果写入sessionStore,然后重定向回请求页面(要求请求页面和认证服务在同一域名下)
  24. // token - url带上token参数重定向到原始地址
  25. async auth() {
  26. const { redirect_uri, code, test, type, response_type = 'store', uid, qrcode, msgid, objid } = this.ctx.query;
  27. if (test) {
  28. return await this.authTest();
  29. }
  30. if (code) {
  31. return await this.authBack(this.ctx.query);
  32. }
  33. this.ctx.logger.debug(`[auth] reditect_uri - ${redirect_uri}`);
  34. // assert(redirect_uri, '回调地址不能为空');
  35. // TODO: 保存原始请求地址
  36. // const { config } = this.app;
  37. // console.log('ctx.host: ', this.ctx.host);
  38. // console.log('config.hostHeaders: ', config.hostHeaders);
  39. // TODO: 保存原始请求地址
  40. const state = uuid();
  41. const key = `visit:auth:state:${state}`;
  42. const val = JSON.stringify({ redirect_uri, type, uid, qrcode, msgid, objid });
  43. await this.app.redis.set(key, val, 'EX', 600);
  44. // TODO: 生成回调地址
  45. const { wxapi, authUrl = this.ctx.path } = this.app.config;
  46. const backUrl = encodeURI(`${this.app.config.baseUrl}${this.config.authUrl}?state=${state}`);
  47. const to_uri = encodeURI(`${wxapi.baseUrl}/api/auth?appid=${wxapi.appid}&response_type=code&redirect_uri=${backUrl}#wechat`);
  48. // const backUrl = encodeURI(`${this.app.config.baseUrl}${this.config.authUrl}/`);
  49. // 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`;
  50. this.ctx.redirect(to_uri);
  51. }
  52. // GET 认证回调
  53. async authBack({ code, state }) {
  54. // const { code, state, type, redirecturi } = this.ctx.query;
  55. this.ctx.logger.debug(`[auth-back] code - ${code}, state - ${state}`);
  56. assert(code, 'code不能为空');
  57. assert(state, 'state不能为空');
  58. const { weixin } = this.ctx.service;
  59. const key = `visit:auth:state:${state}`;
  60. const val = await this.app.redis.get(key);
  61. let openid;
  62. try {
  63. ({ openid } = await weixin.fetch(code));
  64. } catch (err) {
  65. await this.ctx.render('error.njk', { title: err.message, message: err.details });
  66. return;
  67. }
  68. if (openid) {
  69. const { redirect_uri, type, uid, qrcode, msgid, objid } = JSON.parse(val);
  70. const user = await this.ctx.service.user.findByOpenid(openid);
  71. if (type === '0') {
  72. // 通过openid取得用户信息
  73. if (user) {
  74. const token = await this.ctx.service.login.createJwt(user);
  75. if (user.type === '4') {
  76. const to_uri = urljoin(redirect_uri, `?token=${token}`);
  77. // TODO: 重定性页面
  78. this.ctx.redirect(to_uri);
  79. } else if (user.type === '1') {
  80. const touri = `${this.app.config.baseUrl}/mobiledirtea`;
  81. const to_uri = urljoin(touri, `?token=${token}`);
  82. // TODO: 重定性页面
  83. this.ctx.redirect(to_uri);
  84. } else if (user.type === '3') {
  85. const touri = `${this.app.config.baseUrl}/mobiledirtea`;
  86. const to_uri = urljoin(touri, `?token=${token}`);
  87. // TODO: 重定性页面
  88. this.ctx.redirect(to_uri);
  89. }
  90. } else {
  91. // const resunionid = await weixin.fetchUnionID(openid);
  92. const touri = `${this.app.config.baseUrl}/student/bind`;
  93. const to_uri = urljoin(touri, `?openid=${openid}`); // &unionid=${resunionid.unionid}
  94. // TODO: 重定性页面
  95. this.ctx.redirect(to_uri);
  96. }
  97. } else if (type === '1') {
  98. const to_uri = urljoin(redirect_uri, `?openid=${openid}&uid=${uid}&type=${type}&qrcode=${qrcode}`);
  99. // TODO: 重定性页面
  100. this.ctx.redirect(to_uri);
  101. } else if (type === '2') {
  102. const to_uri = urljoin(redirect_uri, `?openid=${openid}&type=${type}&qrcode=${qrcode}`);
  103. // TODO: 重定性页面
  104. this.ctx.redirect(to_uri);
  105. } else if (type === '9') {
  106. // const token = await this.ctx.service.login.createJwt(user);
  107. const to_uri = urljoin(redirect_uri, `?openid=${openid}&type=${type}&msgid=${msgid}&objid=${objid}`);
  108. // TODO: 重定性页面
  109. this.ctx.redirect(to_uri);
  110. }
  111. }
  112. }
  113. // GET 用户授权内部测试接口
  114. async authTest() {
  115. const { redirect_uri, type, uid, qrcode, openid, msgid, objid } = this.ctx.query;
  116. // const openid = stringRandom();
  117. this.ctx.logger.debug(`[auth-test] reditect_uri - ${redirect_uri}, openid - ${openid}`);
  118. assert(redirect_uri, '回调地址不能为空');
  119. assert(openid, 'openid不能为空');
  120. const user = await this.ctx.service.user.findByOpenid(openid);
  121. if (type === '0') {
  122. // 通过openid取得用户信息
  123. if (user) {
  124. const token = await this.ctx.service.login.createJwt(user);
  125. if (user.type === '4') {
  126. const to_uri = urljoin(redirect_uri, `?token=${token}`);
  127. // TODO: 重定性页面
  128. this.ctx.redirect(to_uri);
  129. } else if (user.type === '1') {
  130. const touri = `${this.app.config.baseUrl}/mobiledirtea`;
  131. const to_uri = urljoin(touri, `?token=${token}`);
  132. // TODO: 重定性页面
  133. this.ctx.redirect(to_uri);
  134. } else if (user.type === '3') {
  135. const touri = `${this.app.config.baseUrl}/mobiledirtea`;
  136. const to_uri = urljoin(touri, `?token=${token}`);
  137. // TODO: 重定性页面
  138. this.ctx.redirect(to_uri);
  139. }
  140. } else {
  141. console.log('rrr0000--->' + redirect_uri);
  142. const resunionid = await weixin.fetchUnionID(openid);
  143. const touri = `${this.app.config.baseUrl}/student/bind`;
  144. const to_uri = urljoin(touri, `?openid=${openid}&unionid=${resunionid.unionid}`);
  145. // TODO: 重定性页面
  146. this.ctx.redirect(to_uri);
  147. }
  148. } else if (type === '1') {
  149. const to_uri = urljoin(redirect_uri, `?openid=${openid}&uid=${uid}&type=${type}&qrcode=${qrcode}`);
  150. // TODO: 重定性页面
  151. console.log('1111---?' + to_uri);
  152. this.ctx.redirect(to_uri);
  153. } else if (type === '2') {
  154. const to_uri = urljoin(redirect_uri, `?openid=${openid}&type=${type}&qrcode=${qrcode}`);
  155. // TODO: 重定性页面
  156. console.log('22222---?' + to_uri);
  157. this.ctx.redirect(to_uri);
  158. } else if (type === '9') {
  159. // const token = await this.ctx.service.login.createJwt(user);
  160. const to_uri = urljoin(redirect_uri, `?openid=${openid}&type=${type}&msgid=${msgid}&objid=${objid}`);
  161. // TODO: 重定性页面
  162. console.log('99999---?' + to_uri);
  163. this.ctx.redirect(to_uri);
  164. }
  165. }
  166. // GET 签到小程序请求用户
  167. async appAuth() {
  168. console.warn('in appAuth');
  169. const { js_code, login = true } = this.ctx.query;
  170. console.log(js_code);
  171. const appopenid = await this.ctx.service.weixin.appAuth(js_code);
  172. if (!login) this.ctx.ok(appopenid);
  173. console.warn(`openid=>${appopenid}`);
  174. // const state = uuid();
  175. // const key = `appinfo:${state}`;
  176. // await this.app.redis.set(key, appopenid, 'EX', 600);
  177. const res = await this.ctx.service.user.findByAppOpenid(appopenid);
  178. const obj = { user: res, openid: appopenid };
  179. this.ctx.ok(obj);
  180. }
  181. }
  182. module.exports = WeixinController;