package util import ( "../../models" "../../pkg/logging" "../../pkg/setting" "crypto/sha1" "fmt" "github.com/fastwego/offiaccount" template1 "github.com/fastwego/offiaccount/apis/message/template" "github.com/fastwego/offiaccount/apis/oauth" user1 "github.com/fastwego/offiaccount/apis/user" "github.com/fastwego/offiaccount/type/type_message" "github.com/fastwego/offiaccount/util" "github.com/fastwego/wxwork/corporation" "github.com/fastwego/wxwork/corporation/apis/contact" message1 "github.com/fastwego/wxwork/corporation/apis/message" "github.com/gin-gonic/gin" "github.com/robfig/cron" "html/template" "io/ioutil" "log" "net/url" "strconv" "time" ) //企业微信 var OffiAccount *offiaccount.OffiAccount var Corp *corporation.Corporation var App *corporation.App var MsgChan chan []map[string]interface{} type UserMsg struct { Touser string `json:"touser"` Msgtype string `json:"msgtype"` Agentid string `json:"agentid"` Text interface{} `json:"text"` } func init() { //initOffiAccount() //initWXwork() //Getuseinfor() } func CronWXwork() { //Getuseinfor1() defer func() { // 必须要先声明defer if err := recover(); err != nil { fmt.Printf("CronTest pnic err%+v \n", err) logging.Error("panic recover err ", err) //println("pnic err",err.(error).Error()) // 这里的err其实就是panic传入的内容,55 } }() initWXwork() go SendRun() log.Println("Starting CronWXwork...") c := cron.New() // _, err := c.AddFunc("30 00 * * *", Getuseinfor) //* * * * *, 从分钟开始 // if err != nil { println("cron4 err", err.Error()) } //_, err = c.AddFunc("0/1 * * * *", GetMsg) //* * * * *, 从分钟开始 // //_, err := c.AddFunc("0 0 7 * * ?", GetPartsInfo) //* * * * *, 每天早上7点 //_, err := c.AddFunc("CRON_TZ=Asia/Shanghai 48 13 * * *", Ceshi) //* * * * *, 每天早上7点 //_, err := c.AddFunc("@every 1m", Ceshi) //* * * * *, 每天早上7点 //_, err := c.AddFunc("@every 5s", Getuseinfor) //* * * * *, 从分钟开始 //_, err := c.AddFunc("@every 30s", GetPartsInfo) //* * * * *, 每天早上7点 _, err = c.AddFunc("@every 1m", GetMsg) //* * * * *, 从分钟开始 _, err = c.AddFunc("CRON_TZ=Asia/Shanghai 01 07 * * *",GetPartsInfo ) //* * * * *, 每天七点 if err != nil { println("cron5 err", err.Error()) } c.Start() } func Ceshi(){ fmt.Println("sasdsdadasa") } func GetPartsInfo(){ tx := models.Engine.NewSession() //Engine := models.Engine err1 := tx.Begin() defer func() { switch { case err1 != nil: println("tx.Begin 事务启动失败__error:", err1.Error()) if tx != nil { tx.Rollback() } default: if tx != nil { err1 = tx.Commit() } } if tx != nil { tx.Close() } }() query,err := tx.SQL("select count(*) success,(select count(*) from parts ps "+ " where ps.chargeDate >= DATE_SUB(now(),INTERVAL 1 DAY) and ps.issync=0 ) woring "+ " from parts where parts.chargeDate >= DATE_SUB(now(),INTERVAL 1 DAY) and parts.issync=1 ").Query().List() query1,err := tx.SQL(" select empid from user where id in(select user_id from user_role " + "where role_id in (select id from role where easInformationReception = 1))").Query().List() if err !=nil{ logging.Error("获取备件同步成功与否__error:", err.Error()) }else { if len(query1) > 0 && len(query ) > 0{ for i:=0;i 0 { department = value.(map[string]interface{})["department"].([]interface{})[0] } var empcode interface{} if len(value.(map[string]interface{})["extattr"].(map[string]interface{})["attrs"].([]interface{})) == 1 { empcode = value.(map[string]interface{})["extattr"].(map[string]interface{})["attrs"].([]interface{})[0].(map[string]interface{})["value"] } else if len(value.(map[string]interface{})["extattr"].(map[string]interface{})["attrs"].([]interface{})) > 1 { for _, va := range value.(map[string]interface{})["extattr"].(map[string]interface{})["attrs"].([]interface{}) { if va.(map[string]interface{})["name"].(string) == "工号" { empcode = va.(map[string]interface{})["value"] break } } } //jvalue,_ :=json.Marshal(value) _, err = tx.Exec("insert into wxworkuser(userid,name,department,empcode)values(?,?,?,?)ON DUPLICATE KEY UPDATE empcode =?,department=?", userid, name, department, empcode, empcode,department) //_,err =tx.Exec("insert into wxworkuser(userid,name,department,empcode,json)values(?,?,?,?,?)ON DUPLICATE KEY UPDATE empcode =?",userid,name,department,empcode,string(jvalue),empcode) if err != nil { logging.Error("insert into wxworkuser err ", err.Error()) } } } logging.Info("update wxworkuser success ") } func SendRun() { defer func(){ if err:=recover();err!=nil{ logging.Error("GetMsg pnic err",err) } }() for{ msgs := <- MsgChan println(len(msgs)) for _, value := range msgs { content := make(map[string]interface{}) content["content"] = value["msg"].(string) msg := UserMsg{ Touser: value["userid"].(string), Agentid: setting.ServerSetting.WXworkAgentid, Text: content, Msgtype: "text", } msgbyte, err := json.Marshal(msg) if err != nil { logging.Error("json.Marshal err ", err.Error()) } _, err = message1.Send(App, msgbyte) if err != nil { logging.Error("message1.Send err ", err.Error()) fmt.Println("message1.Send err",err.Error()) }else{ } //println("resp==========",string(resp)) } } } func GetMsgv1(){ //defer func(){ // 必须要先声明defer // if err:=recover();err!=nil{ // logging.Error("GetMsg pnic err",err) // 这里的err其实就是panic传入的内容,55 // } //}() //time.Sleep(time.Second) //a := 0 //b := 1/a //println(b) go GetMsgv2() } func GetMsgv2(){ defer func(){ // 必须要先声明defer if err:=recover();err!=nil{ logging.Error("GetMsg pnic err",err) // 这里的err其实就是panic传入的内容,55 } }() time.Sleep(time.Second) a := 0 b := 1/a println(b) } func GetMsg() { defer func(){ // 必须要先声明defer if err:=recover();err!=nil{ logging.Error("GetMsg pnic err",err) // 这里的err其实就是panic传入的内容,55 } }() tx := models.Engine.NewSession() err1 := tx.Begin() defer func() { switch { case err1 != nil: println("tx.Begin 事务启动失败__error:", err1.Error()) if tx != nil { tx.Rollback() } default: if tx != nil { err1 = tx.Commit() } } if tx != nil { tx.Close() } }() sqls, err := tx.SQL("select sqlstr from apisql where sqlname in ('getWXworkMsg','updateWXworkMsg') order by sqlname").Query().List() if err != nil { logging.Error("select from sqls err ", err.Error()) } if len(sqls)< 2 { return } sqlmsg := sqls[0]["sqlstr"].(string) sqlupdate := sqls[1]["sqlstr"].(string) var query []map[string]interface{} if len(sqls) > 0 { query, err = tx.SQL(sqlmsg).Query().List() if err != nil { logging.Error("select from wxworkmsg err ", err.Error(), len(query)) } else { _, err = tx.Exec(sqlupdate) if err != nil { logging.Error("update wxworkmsg err ", err.Error(), len(query)) } } } if len(query) > 0 { go func(){ msgs := query MsgChan <- msgs } () //for _, value := range query { // content := make(map[string]interface{}) // content["content"] = value["msg"].(string) // msg := UserMsg{ // Touser: value["userid"].(string), // Agentid: setting.ServerSetting.WXworkAgentid, // Text: content, // Msgtype: "text", // } // // msgbyte, err := json.Marshal(msg) // if err != nil { // logging.Error("json.Marshal err ", err.Error()) // } // _, err = message1.Send(App, msgbyte) // if err != nil { // logging.Error("message1.Send err ", err.Error()) // } // //println("resp==========",string(resp)) //} } } func SendMsgtest() { message1.Send(App, []byte(`{ "touser": "18322596935", "toparty": "PartyID1|PartyID2", "totag": "TagID1 | TagID2", "msgtype": "text", "agentid": 1000022, "text": { "content": "你的快递已到,请携带工卡前往邮件中心领取。\n出发前可查看邮件中心视频实况,聪明避开排队。" }, "safe": 0, "enable_id_trans": 0, "enable_duplicate_check": 0 }`)) } func initOffiAccount() { // 加载配置文件 // 创建公众号实例 OffiAccount = offiaccount.New(offiaccount.Config{ Appid: "wxe1cc563ba393dd1a", Secret: "25e56243da9581eab6f4d67a12ef4658", Token: "123", EncodingAESKey: "6yYJ4sS5y1hJgvIXEqavV2rmCutyXkywndxUQFgX54f", }) //payload := []byte(` //{ // "button":[ // { // "name":"菜单", // "sub_button":[ // { // "type":"view", // "name":"搜索", // "url":"http://www.baidu.com/" // }] // }] //}`) //resp, err := menu.Create(OffiAccount, payload) //fmt.Println(resp, err) //guide.SetGuideConfig(OffiAccount,[]byte("欢迎关注")) } func initWXwork() { // 加载配置文件 // 创建企业微信实例 Corp = corporation.New(corporation.Config{Corpid: setting.ServerSetting.WXworkCorpid}) App = Corp.NewApp(corporation.AppConfig{ AgentId: setting.ServerSetting.WXworkAgentid, Secret: setting.ServerSetting.WXworkSecret, Token: "", EncodingAESKey: "", }) MsgChan = make(chan []map[string]interface{},1000) } func InitRouter() *gin.Engine { r := gin.New() // ginpprof.Wrap(r) r.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string { // 你的自定义格式 return fmt.Sprintf(" %+v \n", param.Keys, ) })) r.Use(gin.Logger()) // 日志 //r.Use(Cors()) // 跨域请求rolemenus r.Use(gin.Recovery()) r.GET("/", func(c *gin.Context) { //OffiAccount.Server.EchoStr(c.Writer, c.Request) config, err := jsapiConfig(c) if err != nil { fmt.Println("==========1", err) return } t1, err := template.ParseFiles("index.html") if err != nil { fmt.Println("==========2", err) return } println("===========", t1.Name()) t1.Execute(c.Writer, config) }) r.POST("/", HandleMessage) return r } func jsapiConfig(c *gin.Context) (config template.JS, err error) { // 优先从环缓存获取 jsapi_ticket, err := OffiAccount.AccessToken.Cache.Fetch("jsapi_ticket:" + OffiAccount.Config.Appid) if len(jsapi_ticket) == 0 { var ttl int64 jsapi_ticket, ttl, err = oauth.GetJSApiTicket(OffiAccount) if err != nil { return } err = OffiAccount.AccessToken.Cache.Save("jsapi_ticket:"+OffiAccount.Config.Appid, jsapi_ticket, time.Duration(ttl)*time.Second) if err != nil { return } } nonceStr := util.GetRandString(6) timestamp := strconv.FormatInt(time.Now().Unix(), 10) pageUrl := "http://" + c.Request.Host + c.Request.RequestURI plain := "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonceStr + "×tamp=" + timestamp + "&url=" + pageUrl signature := fmt.Sprintf("%x", sha1.Sum([]byte(plain))) fmt.Println(plain, signature) configMap := map[string]string{ "url": pageUrl, "nonceStr": nonceStr, "appid": OffiAccount.Config.Appid, "timestamp": timestamp, "signature": signature, } marshal, err := json.Marshal(configMap) if err != nil { return } return template.JS(marshal), nil } func HandleMessage(c *gin.Context) { // 区分不同账号 //account := path.Base(c.Request.URL.Path) // 调用相应公众号服务 body, _ := ioutil.ReadAll(c.Request.Body) log.Println(string(body)) message, err := OffiAccount.Server.ParseXML(body) if err != nil { log.Println(err) } var output interface{} switch message.(type) { case type_message.MessageText: // 文本 消息 msg := message.(type_message.MessageText) // 回复文本消息 output = type_message.ReplyMessageText{ ReplyMessage: type_message.ReplyMessage{ ToUserName: type_message.CDATA(msg.FromUserName), FromUserName: type_message.CDATA(msg.ToUserName), CreateTime: strconv.FormatInt(time.Now().Unix(), 10), MsgType: type_message.ReplyMsgTypeText, }, Content: type_message.CDATA(msg.Content), } resp, err := template1.Send(OffiAccount, []byte(` { "touser":"`+msg.FromUserName+`", "template_id":"BtkN1rWKOJtKP0C64lGxIrPzLRFsYFas-4gupX2-pFo", "data":{ "first": { "value":"恭喜你购买成功!", "color":"#173177" }, "keyword1":{ "value":"巧克力", "color":"#173177" }, "keyword2": { "value":"39.8元", "color":"#173177" }, "keyword3": { "value":"2014年9月22日", "color":"#173177" }, "remark":{ "value":"欢迎再次购买!", "color":"#173177" } } }`)) println("msg", resp, err, msg.FromUserName) } //var value url.Values //value.Add("access_token","40_oJz5xKDgTEAPXV66Ydlx3Xu-9OsltBLEfuIZ7qPkaxJBafOCr6B83Td2t5B5glJ8dpCvEnPUTrgnbmFI7T6AYE6jYL5iJOo7UcdvCg9437lc8OfyyzsEFMUZF4JekDYQUqjiAiaLrmwRwbwrGCTjAJAMIZ") //println(value.Get("access_token")) res, _ := user1.Get(OffiAccount, nil) println("res======", string(res)) OffiAccount.Server.Response(c.Writer, c.Request, output) }