package util import ( "crypto/sha1" "fmt" "html/template" "io/ioutil" "log" "net/url" "strconv" "time" "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/external_contact/customer" message1 "github.com/fastwego/wxwork/corporation/apis/message" "github.com/gin-gonic/gin" // "github.com/robfig/cron" "github.com/robfig/cron/v3" "kpt.xdmy/apiserver/routers/restful" "kpt.xdmy/pkg/logging" "kpt.xdmy/pkg/setting" ) //企业微信 var OffiAccount *offiaccount.OffiAccount var Corp *corporation.Corporation var App *corporation.App var MsgChan chan []map[string]string type UserMsg struct { Touser string `json:"touser"` Msgtype string `json:"msgtype"` Agentid string `json:"agentid"` Text interface{} `json:"text"` } func CronWXwork() { defer func() { // 必须要先声明defer if err := recover(); err != nil { fmt.Printf("CronTest pnic err%+v \n", err) logging.Error("panic recover err ", err) } }() initWXwork() go SendRun() log.Println("Starting CronWXwork...") c := cron.New() _, err := c.AddFunc("00 00 06 * * *", Getuseinfor) //* * * * *, 从分钟开始 if err != nil { println("cron4 err", err.Error()) } _, err = c.AddFunc("30 * * * * *", GetMsg) //* * * * *, 从分钟开始 _, err = c.AddFunc("00 00 07 * * *", GetPartsInfo) //* * * * *, 每天七点 if err != nil { println("cron5 err", err.Error()) } c.Start() } func Ceshi() { fmt.Println("sasdsdadasa") } func GetPartsInfo() { tx, err1 := restful.Dbs.Beginx() defer func() { switch { case err1 != nil: println("tx.Begin 事务启动失败__error:", err1.Error()) if tx != nil { tx.Rollback() } default: if tx != nil { err1 = tx.Commit() } } }() query, err := restful.MapStrListTx(tx, "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 ") query1, err := restful.MapStrListTx(tx, " select empid from user where id in(select user_id from user_role "+ "where role_id in (select id from role where easInformationReception = 1))") if err != nil { logging.Error("获取备件同步成功与否__error:", err.Error()) } else { if len(query1) > 0 && len(query) > 0 { for i := 0; i < len(query1); i++ { success := query[0]["success"] personId := query1[i]["empid"] woring := query[0]["woring"] _, err = tx.Exec("INSERT INTO wxworkmsg(date,userid,msg,formcode,type,note) VALUES(?,?,?,?,?,?)", time.Now().Format("2006-01-02"), personId, "【eas】同步成功"+success+"条"+"同步失败"+woring+"条", "eas", 0, nil) if err != nil { } } } if err != nil { logging.Error("插入eas同步信息到微信信息表__error:", err.Error()) } } } func Getuseinfor1() { logging.Error("PostDataByNames========= ") } func Getuseinfor() { defer func() { // 必须要先声明defer if err := recover(); err != nil { logging.Error("Getuseinfor pnic err", err) // 这里的err其实就是panic传入的内容,55 } }() value := make(url.Values, 1) value.Add("department_id", "1") value.Add("fetch_child", "1") msgmap := make(map[string]interface{}) resp, err := customer.List(App, value) if err != nil { println("contact.UserList err", err.Error()) } err = json.Unmarshal(resp, &msgmap) if err != nil { println("json.Unmarshal err", err.Error()) } tx, err1 := restful.Dbs.Beginx() defer func() { switch { case err1 != nil: logging.Error("tx.Begin 事务启动失败__error:", err.Error()) if tx != nil { tx.Rollback() } default: if tx != nil { err = tx.Commit() } } }() if _, ok := msgmap["userlist"]; ok { for _, value := range msgmap["userlist"].([]interface{}) { userid := value.(map[string]interface{})["userid"] name := value.(map[string]interface{})["name"] var department interface{} if len(value.(map[string]interface{})["department"].([]interface{})) > 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"] == "工号" { 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"] msg := UserMsg{ Touser: value["userid"], 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 { } } } } func GetMsgv1() { 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, err1 := restful.Dbs.Beginx() defer func() { switch { case err1 != nil: println("tx.Begin 事务启动失败__error:", err1.Error()) if tx != nil { tx.Rollback() } default: if tx != nil { err1 = tx.Commit() } } }() sqls, err := restful.MapStrListTx(tx, "select sqlstr from apisql where sqlname in ('getWXworkMsg','updateWXworkMsg') order by sqlname") if err != nil { logging.Error("select from sqls err ", err.Error()) } if len(sqls) < 2 { return } sqlmsg := sqls[0]["sqlstr"] sqlupdate := sqls[1]["sqlstr"] var query []map[string]string if len(sqls) > 0 { query, err = restful.MapStrListTx(tx, sqlmsg) 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 }() } } 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{ // wxe1cc563ba393dd1a Appid: "wxe1cc563ba393dd1a", Secret: "25e56243da9581eab6f4d67a12ef4658", Token: "123", // 6yYJ4sS5y1hJgvIXEqavV2rmCutyXkywndxUQFgX54f 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]string, 100) } 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) } res, _ := user1.Get(OffiAccount, nil) println("res======", string(res)) OffiAccount.Server.Response(c.Writer, c.Request, output) }