'use strict'; /** * * * @author Ellisran * @date 2020/7/2 * @version */ const moment = require('moment'); // const Controller = require('egg').Controller; const crypto = require('crypto'); const maintainConst = require('../const/maintain'); module.exports = app => { class WechatController extends app.BaseController { /** * 接入微信 * * @param {Object} ctx - egg全局页面 * @return {void} */ async index(ctx) { try { const signature = ctx.query.signature; const timestamp = ctx.query.timestamp; const nonce = ctx.query.nonce; const echostr = ctx.query.echostr; const array = [ctx.app.config.wechatAll.token, timestamp, nonce]; array.sort(); const tempStr = array.join(''); const hashCode = crypto.createHash('sha1'); const resultCode = hashCode.update(tempStr, 'utf8').digest('hex'); if (resultCode === signature) { ctx.body = echostr; // res.send(echostr); } else { throw '验证失败'; } } catch (e) { console.log(e); } } /** * 微信登录验证 * * @param {Object} ctx - egg全局页面 * @return {void} */ async oauth(ctx) { const url = await app.wechat.oauth.getAuthorizeURL('http://jluat.smartcost.com.cn/wx/bind', '', 'snsapi_userinfo'); ctx.redirect(url); } /** * 绑定页面 * * @param {Object} ctx - egg全局页面 * @return {void} */ async bind(ctx) { try { if (!ctx.session.wechatToken) { const token = await app.wechat.oauth.getAccessToken(ctx.query.code); ctx.session.wechatToken = token.data; } const user = await app.wechat.oauth.getUser(ctx.session.wechatToken.openid); const errorMessage = ctx.session.loginError; // 获取系统维护信息 const maintainData = await ctx.service.maintain.getDataById(1); const renderData = { maintainData, maintainConst, errorMessage, user, }; // ctx.body = renderData; await ctx.render('wechat/bind.ejs', renderData); } catch (e) { console.log(e); ctx.body = e; } } async bindwx(ctx) { try { const result = await ctx.service.projectAccount.accountCheck(ctx.request.body); if (!result) { throw '用户名或密码错误'; } if (result === 2) { throw '该账号已被停用,请联系销售人员'; } const accountData = result; if (accountData.wx_openid || ctx.session.wechatToken.openid === accountData.wx_openid) { throw '该账号已经绑定过微信'; } const wxAccountData = await ctx.service.projectAccount.getDataByCondition({ wx_openid: ctx.session.wechatToken.openid }); if (wxAccountData) { throw '该微信号已绑定过本项目账号'; } const user = await app.wechat.oauth.getUser(ctx.session.wechatToken.openid); const result2 = await ctx.service.projectAccount.bindWx(accountData.id, ctx.session.wechatToken.openid, user.nickname); if (!result2) { throw '绑定失败'; } ctx.body = '绑定成功'; } catch (error) { this.log(error); ctx.session.loginError = error; ctx.redirect('/wx/bind'); } } async oauthTxt(ctx) { ctx.body = 't3MkWAMqplVxPjmr'; } } return WechatController; };