123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539 |
- 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<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.(string)+"条"+"同步失败"+woring.(string)+"条",
- "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 := contact.UserList(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 := models.Engine.NewSession()
- err1 := tx.Begin()
- 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 tx != nil {
- tx.Close()
- }
- }()
- 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"].(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出发前可查看<a href=\"http://work.weixin.qq.com\">邮件中心视频实况</a>,聪明避开排队。"
- },
- "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)
- }
|