template_msg.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. package services
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "eta/eta_mini_crm_ht/models"
  6. "eta/eta_mini_crm_ht/utils"
  7. "fmt"
  8. "io"
  9. "net/http"
  10. "strings"
  11. "time"
  12. )
  13. var (
  14. TemplateMsgSendUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s"
  15. TemplateMsgClearQuotaUrl = "https://api.weixin.qq.com/cgi-bin/clear_quota?access_token=%s"
  16. )
  17. type TemplateMsgSendClient struct {
  18. AccessToken string
  19. Data []byte
  20. }
  21. type SendTemplateResponse struct {
  22. Errcode int `json:"errcode"`
  23. Errmsg string `json:"errmsg"`
  24. MsgID int `json:"msgid"`
  25. }
  26. type ClearQuotaResponse struct {
  27. Errcode int `json:"errcode"`
  28. Errmsg string `json:"errmsg"`
  29. }
  30. type OpenIdList struct {
  31. OpenId string
  32. UserId int
  33. FollowingGzh bool
  34. }
  35. //// TemplateMsgSendClient.ClearQuota 清除发送超过当日10万次限制
  36. //func (c *TemplateMsgSendClient) ClearQuota() (result *ClearQuotaResponse, err error) {
  37. // key := "CACHE_SendTemplateMsg_ERR"
  38. // exists := utils.Rc.IsExist(key)
  39. // if exists {
  40. // return
  41. // }
  42. // _ = utils.Rc.SetEX(key, 1, 6*time.Minute)
  43. //
  44. // sendUrl := fmt.Sprintf(TemplateMsgClearQuotaUrl, c.AccessToken)
  45. // client := http.Client{}
  46. // clearData := make(map[string]interface{})
  47. // clearData["appid"] = utils.HT_WX_APPID
  48. // clearJson, _ := json.Marshal(clearData)
  49. // resp, err := client.Post(sendUrl, "application/json", bytes.NewBuffer(clearJson))
  50. // if err != nil {
  51. // return
  52. // }
  53. // defer func() {
  54. // _ = resp.Body.Close()
  55. // }()
  56. // clearBody, err := io.ReadAll(resp.Body)
  57. // err = json.Unmarshal(clearBody, &result)
  58. // return
  59. //}
  60. //// TemplateMsgSendClient.SendMsg 推送消息
  61. //func (c *TemplateMsgSendClient) SendMsg() (sendRes *SendTemplateResponse, err error) {
  62. // // 请求接口
  63. // sendUrl := fmt.Sprintf(TemplateMsgSendUrl, c.AccessToken)
  64. // client := http.Client{}
  65. // resp, err := client.Post(sendUrl, "application/json", bytes.NewBuffer(c.Data))
  66. // if err != nil {
  67. // return
  68. // }
  69. // defer func() {
  70. // _ = resp.Body.Close()
  71. // }()
  72. // body, _ := io.ReadAll(resp.Body)
  73. // if err = json.Unmarshal(body, &sendRes); err != nil {
  74. // return
  75. // }
  76. // // 模板消息发送超过当日10万次限制错误处理
  77. // if sendRes.Errcode == 45009 {
  78. // // 发送提示邮件
  79. // // go alarm_msg.SendAlarmMsg("模板消息发送超过当日10万次限制, SendTemplateResponse: "+string(body), 3)
  80. // // 清理限制
  81. // clearRes, e := c.ClearQuota()
  82. // if e != nil {
  83. // err = e
  84. // return
  85. // }
  86. // if clearRes.Errcode != 0 {
  87. // clearJson, er := json.Marshal(clearRes)
  88. // if er != nil {
  89. // return nil, er
  90. // }
  91. // fmt.Println("自动清理模板消息限制接口, 调用失败, ClearQuotaResponse: " + string(clearJson))
  92. // // go alarm_msg.SendAlarmMsg("自动清理模板消息限制接口, 调用失败, ClearQuotaResponse: "+string(clearJson), 3)
  93. // return
  94. // }
  95. // // 发送成功邮件
  96. // // go alarm_msg.SendAlarmMsg("自动清理模板消息限制接口, 调用成功", 1)
  97. // // 重新推送
  98. // go func() {
  99. // _, e := c.SendMsg()
  100. // if e != nil {
  101. // return
  102. // // reSendJson, _ := json.Marshal(reSend)
  103. // // alarm_msg.SendAlarmMsg("重新推送模板消息失败, SendTemplateResponse: "+string(reSendJson), 3)
  104. // }
  105. // }()
  106. // }
  107. // if sendRes.Errcode != 0 {
  108. // err = errors.New("推送模板消息失败, SendTemplateResponse: " + string(body))
  109. // }
  110. // return
  111. //}
  112. // AddUserTemplateRecord 新增模板消息推送记录
  113. func AddUserTemplateRecord(userId, sendStatus int, sendType string, openid, sendData, result string) (err error) {
  114. item := &models.UserTemplateRecord{
  115. UserId: userId,
  116. OpenId: openid,
  117. SendData: sendData,
  118. Result: result,
  119. CreateDate: time.Now().Format(utils.FormatDate),
  120. CreateTime: time.Now().Format(utils.FormatDateTime),
  121. SendStatus: sendStatus,
  122. SendType: sendType,
  123. }
  124. err = item.Insert()
  125. return
  126. }
  127. // SendMultiTemplateMsg 推送模板消息至多个用户
  128. func SendMultiTemplateMsg(templateData SendWxTemplate, items []*OpenIdList, Id int, sendType string) (err error) {
  129. if err != nil {
  130. utils.FileLog.Info("获取微信token失败, Err:" + err.Error())
  131. return
  132. }
  133. var path string
  134. switch sendType {
  135. case "report":
  136. path = "/pages-report/reportDetail/index?id=%d"
  137. case "audio":
  138. path = "/pages-media/audioDetail/index?id=%d"
  139. case "video":
  140. path = "/pages-media/videoDetail/index?id=%d"
  141. default:
  142. return errors.New("非法的消息类型")
  143. }
  144. templateData.WxAppId = utils.HT_WX_APPID
  145. templateData.TemplateId = utils.TEMPLATE_ID_BY_PRODUCT
  146. templateData.RedirectUrl = fmt.Sprintf(path, Id)
  147. templateData.Resource = templateData.RedirectUrl
  148. templateData.SendType = 8
  149. for _, item := range items {
  150. templateData.OpenIdArr = append(templateData.OpenIdArr, item.OpenId)
  151. }
  152. templateData.RedirectTarget = 5
  153. return sendMsg(templateData)
  154. }
  155. type SendWxTemplate struct {
  156. WxAppId string `description:"公众号appId"`
  157. First string `description:"模板消息first字段"`
  158. Keyword1 string `description:"模板消息keyword1字段"`
  159. Keyword2 string `description:"模板消息keyword2字段"`
  160. Keyword3 string `description:"模板消息keyword3字段"`
  161. Keyword4 string `description:"模板消息keyword4字段"`
  162. Keyword5 string `description:"模板消息keyword5字段"`
  163. Productname string `description:"模板消息productname字段"`
  164. Date string `description:"模板消息date字段"`
  165. Remark string `description:"模板消息remark字段"`
  166. TemplateId string `description:"模板id"`
  167. RedirectUrl string `description:"跳转地址"`
  168. RedirectTarget int `description:"小程序跳转目标:1:弘则研报小程序,2:随手办公小程序,3:查研观向"`
  169. Resource string `description:"资源唯一标识"`
  170. SendType int `description:"发送的消息类型:1:报告,2:指标更新提醒,3:审批通知,4:销售领取客户通知,5:活动取消通知,6活动更改时间通知,7:关注的作者发布报告通知,8:发送日报(周报、双周报、月报)模板消息,9:活动预约/报名时间通知"`
  171. OpenIdArr []string `description:"消息接收者openid"`
  172. }
  173. func sendMsg(template SendWxTemplate) (err error) {
  174. if utils.ETA_PUB_URL == `` {
  175. // 找不到推送服务
  176. return
  177. }
  178. // 设置请求 URL
  179. // 设置 POST 请求的数据
  180. data, err := json.Marshal(template)
  181. if err != nil {
  182. utils.FileLog.Error("发送消息模板失败,请求data json序列化失败,err:%v", err)
  183. }
  184. body := io.NopCloser(strings.NewReader(string(data)))
  185. req, _ := http.NewRequest("POST", utils.ETA_PUB_URL, body)
  186. if err != nil {
  187. fmt.Println("发送模板消息失败,创建请求失败:", err)
  188. return
  189. }
  190. // 设置 Content-Type
  191. req.Header.Set("Authorization", utils.ETA_PUB_TOKEN)
  192. req.Header.Set("Content-Type", "application/json;charset=utf-8")
  193. // 发送 POST 请求
  194. client := &http.Client{}
  195. resp, err := client.Do(req)
  196. if err != nil {
  197. utils.FileLog.Error("发送消息模板失败,请求失败,err:%v", err)
  198. return
  199. }
  200. defer resp.Body.Close()
  201. // 处理响应
  202. repBody, err := io.ReadAll(resp.Body)
  203. if err != nil {
  204. return err
  205. }
  206. if resp.StatusCode != http.StatusOK {
  207. utils.FileLog.Error("发送消息模板失败,请求失败,err:%v", string(repBody))
  208. return
  209. }
  210. utils.FileLog.Info("发送消息模板成功,请求成功,body:%v", string(repBody))
  211. return
  212. }