weixin.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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 } = 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 });
  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 = `${wxapi.baseUrl}/api/auth?appid=${wxapi.appid}&response_type=code&redirect_uri=${backUrl}&connect_redirect=1#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. console.log('url-->' + to_uri);
  51. this.ctx.redirect(to_uri);
  52. }
  53. // GET 认证回调
  54. async authBack({ code, state }) {
  55. // const { code, state, type, redirecturi } = this.ctx.query;
  56. console.log(this.ctx.query);
  57. this.ctx.logger.debug(`[auth-back] code - ${code}, state - ${state}`);
  58. assert(code, 'code不能为空');
  59. assert(state, 'state不能为空');
  60. console.log('code-->' + code);
  61. const { weixin } = this.ctx.service;
  62. const openid = await weixin.fetch(code);
  63. console.log('openid--->' + openid);
  64. if (openid) {
  65. const key = `visit:auth:state:${state}`;
  66. const val = await this.app.redis.get(key);
  67. const { redirect_uri, type, uid, qrcode } = JSON.parse(val);
  68. console.log('redirect_uri-->' + redirect_uri);
  69. const user = await this.ctx.service.user.findByOpenid(openid);
  70. if (type === '0') {
  71. // 通过openid取得用户信息
  72. if (user) {
  73. const token = await this.ctx.service.login.createJwt(user);
  74. if (user.type === '4') {
  75. const student = await this.ctx.service.student.fetch(user.uid);
  76. const newdata = { planid: student.planid, ...JSON.parse(JSON.stringify(user)) };
  77. const token_ = await this.ctx.service.login.createJwt(newdata);
  78. const to_uri = urljoin(redirect_uri, `?token=${token_}`);
  79. // TODO: 重定性页面
  80. console.log('to_uri000-->' + to_uri);
  81. this.ctx.redirect(to_uri);
  82. } else if (user.type === '1') {
  83. const touri = `${this.app.config.baseUrl}/mobiledirtea`;
  84. const to_uri = urljoin(touri, `?token=${token}`);
  85. // TODO: 重定性页面
  86. console.log('to_uri000-->' + to_uri);
  87. this.ctx.redirect(to_uri);
  88. } else if (user.type === '3') {
  89. const touri = `${this.app.config.baseUrl}/mobiledirtea`;
  90. const to_uri = urljoin(touri, `?token=${token}`);
  91. // TODO: 重定性页面
  92. console.log('to_uri000-->' + to_uri);
  93. this.ctx.redirect(to_uri);
  94. }
  95. } else {
  96. console.log('rrr0000--->' + redirect_uri);
  97. const resunionid = await weixin.fetchUnionID(openid);
  98. const touri = `${this.app.config.baseUrl}/student/bind`;
  99. const to_uri = urljoin(touri, `?openid=${openid}&unionid=${resunionid.unionid}`);
  100. // TODO: 重定性页面
  101. this.ctx.redirect(to_uri);
  102. }
  103. } else if (type === '1') {
  104. const to_uri = urljoin(redirect_uri, `?openid=${openid}&uid=${uid}&type=${type}&qrcode=${qrcode}`);
  105. // TODO: 重定性页面
  106. console.log('1111---?' + to_uri);
  107. this.ctx.redirect(to_uri);
  108. } else if (type === '2') {
  109. const to_uri = urljoin(redirect_uri, `?openid=${openid}&type=${type}&qrcode=${qrcode}`);
  110. // TODO: 重定性页面
  111. console.log('22222---?' + to_uri);
  112. this.ctx.redirect(to_uri);
  113. }
  114. }
  115. }
  116. // GET 用户授权内部测试接口
  117. async authTest() {
  118. const { redirect_uri, type, uid, qrcode, openid } = this.ctx.query;
  119. // const openid = stringRandom();
  120. this.ctx.logger.debug(`[auth-test] reditect_uri - ${redirect_uri}, openid - ${openid}`);
  121. assert(redirect_uri, '回调地址不能为空');
  122. assert(openid, 'openid不能为空');
  123. if (type === '0') {
  124. // 通过openid取得用户信息
  125. const user = await this.ctx.service.user.findByOpenid(openid);
  126. if (user) {
  127. const token = await this.ctx.service.login.createJwt(user);
  128. if (user.type === '4') {
  129. const to_uri = urljoin(redirect_uri, `?token=${token}`);
  130. // TODO: 重定性页面
  131. console.log('to_uri000-->' + to_uri);
  132. this.ctx.redirect(to_uri);
  133. } else if (user.type === '1') {
  134. const touri = `${this.app.config.baseUrl}/mobiledirtea`;
  135. const to_uri = urljoin(redirect_uri, `?token=${token}`);
  136. // TODO: 重定性页面
  137. console.log('to_uri000-->' + to_uri);
  138. this.ctx.redirect(to_uri);
  139. } else if (user.type === '3') {
  140. const touri = `${this.app.config.baseUrl}/mobiledirtea`;
  141. const to_uri = urljoin(redirect_uri, `?token=${token}`);
  142. // TODO: 重定性页面
  143. console.log('to_uri000-->' + to_uri);
  144. this.ctx.redirect(to_uri);
  145. }
  146. } else {
  147. console.log('rrr--->' + redirect_uri);
  148. const to_uri = urljoin(redirect_uri, `?openid=${openid}`);
  149. // TODO: 重定性页面
  150. this.ctx.redirect(to_uri);
  151. }
  152. } else if (type === '1') {
  153. const to_uri = urljoin(redirect_uri, `?openid=${openid}&uid=${uid}&type=${type}&qrcode=${qrcode}`);
  154. // TODO: 重定性页面
  155. this.ctx.redirect(to_uri);
  156. } else if (type === '2') {
  157. const to_uri = urljoin(redirect_uri, `?openid=${openid}&type=${type}&qrcode=${qrcode}`);
  158. // TODO: 重定性页面
  159. this.ctx.redirect(to_uri);
  160. }
  161. }
  162. }
  163. module.exports = WeixinController;