package weixin import ( "enterprise/base/wechat" "enterprise/base/wechat/cache" "enterprise/base/wechat/message" wutil "enterprise/base/wechat/util" "enterprise/common/config" "github.com/gin-gonic/gin" log "github.com/sirupsen/logrus" "net/http" "strings" ) var ( wechatCache cache.Cache = cache.NewMemory() ) type QyWeixinAgentConfig struct { CorpId string Secret string Agent string Replay func(message.MixMessage) *message.Reply } type QyWeixinAgent struct { QyWeixin Token string AesKey string config *QyWeixinAgentConfig replay func(message.MixMessage) *message.Reply } func NewQyWeixinAgent(cfg *QyWeixinAgentConfig) *QyWeixinAgent { return &QyWeixinAgent{ config: cfg, Token: config.QyWeixinAgentToken, AesKey: config.QyWeixinAgentAesKey, QyWeixin: QyWeixin{ CorpId: cfg.CorpId, Secret: cfg.Secret, Agent: cfg.Agent, }, } } func (q *QyWeixinAgent) Request(ctx *gin.Context) { //配置微信参数 wechatConfig := &wechat.Config{ AppID: q.config.CorpId, AppSecret: q.config.Secret, Token: q.Token, EncodingAESKey: q.AesKey, Cache: wechatCache, } // 首次配置 if strings.ToUpper(ctx.Request.Method) == http.MethodGet { sign := wutil.Signature(ctx.Query("timestamp"), ctx.Query("echostr"), ctx.Query("nonce"), wechatConfig.Token) if sign != ctx.Query("msg_signature") { log.Errorf("sign error forcheck config") return } _, resp, err := wutil.DecryptMsg(wechatConfig.AppID, ctx.Query("echostr"), wechatConfig.EncodingAESKey) if err != nil { log.Errorf("DecryptMsg failed! error:%s", err.Error()) return } ctx.Data(http.StatusOK, "Content-type: text/plain", resp) return } // 2.响应消息 wc := wechat.NewWechat(wechatConfig) ctx.Request.URL.RawQuery += "&encrypt_type=aes" server := wc.GetServer(ctx.Request, ctx.Writer) server.SetMessageHandler(q.config.Replay) server.SetDebug(true) err := server.Serve() if err != nil { log.Errorf("qiye weixin Service err:%s", err.Error()) return } err = server.Send() if err != nil { log.Errorf("qiye weixin Send err:%s", err.Error()) return } }