12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394 |
- package public
- import (
- "app.yhyue.com/moapp/jybase/common"
- "app.yhyue.com/moapp/jybase/redis"
- "biBackService/config"
- "bytes"
- "encoding/json"
- "fmt"
- "io/ioutil"
- "log"
- "net/http"
- )
- const (
- TOKEN = "qywx_token"
- )
- type tokeObj struct {
- Errcode int `json:"errcode"`
- Errmsg string `json:"errmsg"`
- Access_token string `json:"access_token"`
- Expires_in int `json:"expires_in"`
- }
- /*func SendInfo(key, msg string) {
- if t, err := redis.Exists("workChat", key); !t && err == nil {
- redis.Put("workChat", key, 1, 86400)
- SendMsg("rr", "", msg)
- }
- }*/
- func SendMsg(userid string, msg ...string) (bool, error) {
- con := ""
- if len(msg) == 1 {
- con = msg[0]
- }
- m := map[string]interface{}{
- "touser": userid,
- "msgtype": "text",
- "agentid": config.SysConfig.WorkPrivateMsg.AgentID,
- "text": map[string]string{
- "content": con,
- },
- }
- b, _ := json.Marshal(m)
- reqUrl := fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s", getToken())
- //log.Println("发送url:", reqUrl)
- res, err := http.Post(reqUrl, "application/json", bytes.NewReader(b))
- if err != nil {
- log.Print(err)
- } else {
- defer res.Body.Close()
- bs, _ := ioutil.ReadAll(res.Body)
- //log.Info(string(bs))
- var respData map[string]interface{}
- json.Unmarshal(bs, &respData)
- log.Println("respData", respData)
- if respData != nil && fmt.Sprintf("%v", respData["errcode"]) == "0" {
- return true, nil
- }
- }
- return false, err
- }
- func getToken() string {
- token := common.InterfaceToStr(redis.Get("workChat", TOKEN))
- if token == "" {
- tokenUrl := fmt.Sprintf("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s", config.SysConfig.WorkPrivateMsg.WxCorpid, config.SysConfig.WorkPrivateMsg.WxSecret)
- //log.Println("tokenUrl", tokenUrl)
- res, err := http.Get(tokenUrl)
- if err != nil {
- log.Print(err)
- } else {
- defer res.Body.Close()
- bs, err1 := ioutil.ReadAll(res.Body)
- if err1 != nil {
- log.Print(err1)
- } else {
- var tokes tokeObj
- err2 := json.Unmarshal(bs, &tokes)
- if err2 != nil {
- log.Print(err2)
- } else {
- token = tokes.Access_token
- if tokes.Expires_in > 1800 {
- redis.Put("workChat", TOKEN, token, 1800)
- }
- }
- }
- }
- }
- return token
- }
|