weixin.js 6.6 KB

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