qrcode.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. 'use strict';
  2. const _ = require('lodash');
  3. const Controller = require('egg').Controller;
  4. /**
  5. * 微信扫码登录
  6. */
  7. class QrcodeController extends Controller {
  8. constructor(ctx) {
  9. super(ctx);
  10. this.service = this.ctx.service.weixin;
  11. }
  12. // POST 生成二维码
  13. async create() {
  14. const res = await this.service.createQrcode();
  15. this.ctx.ok({ data: res });
  16. }
  17. // POST 生成群二维码
  18. async createQrcode() {
  19. const res = await this.service.createQrcodeGroup(this.ctx.query);
  20. this.ctx.ok({ data: res });
  21. }
  22. // POST 检查二维码
  23. async check() {
  24. const { qrcode } = this.ctx.params;
  25. const res = await this.service.checkQrcode(qrcode);
  26. this.ctx.ok(res);
  27. }
  28. // POST 微信扫码登录
  29. async login() {
  30. const { token } = this.ctx.requestparam;
  31. const { qrcode } = this.ctx.params;
  32. await this.service.scanQrcode({ qrcode, token });
  33. this.ctx.ok();
  34. }
  35. // GET 微信扫码确认页面
  36. async scan() {
  37. // TODO: 获得微信认证token
  38. const token = this.ctx.query.token || this.ctx.cookies.get('wxtoken');
  39. if (!token) {
  40. this.ctx.logger.debug('【originalUrl】', this.ctx.originalUrl);
  41. // TODO: 跳转到授权地址
  42. const { baseUrl } = this.app.config;
  43. const { authUrl = this.ctx.path } = this.app.config;
  44. const backUrl = encodeURI(`${baseUrl}${this.ctx.originalUrl}`);
  45. const to_uri = `${authUrl}?response_type=token&redirect_uri=${backUrl}#wechat`;
  46. this.ctx.redirect(to_uri);
  47. return;
  48. }
  49. await this.ctx.render('login.njk', { message: '扫码登录确认', token });
  50. }
  51. // POST 换取微信认证token
  52. async token() {
  53. const { qrcode } = this.ctx.params;
  54. const res = await this.service.qrcodeLogin(qrcode);
  55. this.ctx.ok(res);
  56. }
  57. }
  58. module.exports = QrcodeController;