qrcode.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. console.log(this.ctx.query);
  20. const res = await this.service.createQrcodeGroup(this.ctx.query);
  21. this.ctx.ok({ data: res });
  22. }
  23. // POST 检查二维码
  24. async check() {
  25. const { qrcode } = this.ctx.params;
  26. const res = await this.service.checkQrcode(qrcode);
  27. this.ctx.ok(res);
  28. }
  29. // POST 微信扫码登录
  30. async login() {
  31. const { token } = this.ctx.requestparam;
  32. const { qrcode } = this.ctx.params;
  33. await this.service.scanQrcode({ qrcode, token });
  34. this.ctx.ok();
  35. }
  36. // GET 微信扫码确认页面
  37. async scan() {
  38. // TODO: 获得微信认证token
  39. const token = this.ctx.query.token || this.ctx.cookies.get('wxtoken');
  40. if (!token) {
  41. this.ctx.logger.debug('【originalUrl】', this.ctx.originalUrl);
  42. // TODO: 跳转到授权地址
  43. const { baseUrl } = this.app.config;
  44. const { authUrl = this.ctx.path } = this.app.config;
  45. const backUrl = encodeURI(`${baseUrl}${this.ctx.originalUrl}`);
  46. const to_uri = `${authUrl}?response_type=token&redirect_uri=${backUrl}#wechat`;
  47. this.ctx.redirect(to_uri);
  48. return;
  49. }
  50. await this.ctx.render('login.njk', { message: '扫码登录确认', token });
  51. }
  52. // POST 换取微信认证token
  53. async token() {
  54. const { qrcode } = this.ctx.params;
  55. const res = await this.service.qrcodeLogin(qrcode);
  56. this.ctx.ok(res);
  57. }
  58. }
  59. module.exports = QrcodeController;