template_msg.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. package wechat
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "errors"
  7. "eta/eta_mini_api/models"
  8. "eta/eta_mini_api/utils"
  9. "fmt"
  10. "io"
  11. "net/http"
  12. "time"
  13. )
  14. var (
  15. TemplateMsgSendUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s"
  16. TemplateMsgClearQuotaUrl = "https://api.weixin.qq.com/cgi-bin/clear_quota?access_token=%s"
  17. )
  18. type TemplateMsgSendClient struct {
  19. AccessToken string
  20. Data []byte
  21. }
  22. type SendTemplateResponse struct {
  23. Errcode int `json:"errcode"`
  24. Errmsg string `json:"errmsg"`
  25. MsgID int `json:"msgid"`
  26. }
  27. type ClearQuotaResponse struct {
  28. Errcode int `json:"errcode"`
  29. Errmsg string `json:"errmsg"`
  30. }
  31. type OpenIdList struct {
  32. OpenId string
  33. UserId int
  34. }
  35. // TemplateMsgSendClient.ClearQuota 清除发送超过当日10万次限制
  36. func (c *TemplateMsgSendClient) ClearQuota() (result *ClearQuotaResponse, err error) {
  37. key := "CACHE_SendTemplateMsg_ERR"
  38. exists, _ := utils.Redis.Exists(context.TODO(), key).Result()
  39. if exists == 1 {
  40. return
  41. }
  42. _ = utils.Redis.SetEX(context.TODO(), key, 1, 6*time.Minute)
  43. sendUrl := fmt.Sprintf(TemplateMsgClearQuotaUrl, c.AccessToken)
  44. client := http.Client{}
  45. clearData := make(map[string]interface{})
  46. clearData["appid"] = WxAppId
  47. clearJson, _ := json.Marshal(clearData)
  48. resp, err := client.Post(sendUrl, "application/json", bytes.NewBuffer(clearJson))
  49. if err != nil {
  50. return
  51. }
  52. defer func() {
  53. _ = resp.Body.Close()
  54. }()
  55. clearBody, err := io.ReadAll(resp.Body)
  56. err = json.Unmarshal(clearBody, &result)
  57. return
  58. }
  59. // TemplateMsgSendClient.SendMsg 推送消息
  60. func (c *TemplateMsgSendClient) SendMsg() (sendRes *SendTemplateResponse, err error) {
  61. // 请求接口
  62. sendUrl := fmt.Sprintf(TemplateMsgSendUrl, c.AccessToken)
  63. client := http.Client{}
  64. resp, err := client.Post(sendUrl, "application/json", bytes.NewBuffer(c.Data))
  65. if err != nil {
  66. return
  67. }
  68. defer func() {
  69. _ = resp.Body.Close()
  70. }()
  71. body, _ := io.ReadAll(resp.Body)
  72. if err = json.Unmarshal(body, &sendRes); err != nil {
  73. return
  74. }
  75. // 模板消息发送超过当日10万次限制错误处理
  76. if sendRes.Errcode == 45009 {
  77. // 发送提示邮件
  78. // 清理限制
  79. clearRes, e := c.ClearQuota()
  80. if e != nil {
  81. err = e
  82. return
  83. }
  84. if clearRes.Errcode != 0 {
  85. clearJson, er := json.Marshal(clearRes)
  86. if er != nil {
  87. return nil, er
  88. }
  89. fmt.Println("自动清理模板消息限制接口, 调用失败, ClearQuotaResponse: " + string(clearJson))
  90. return
  91. }
  92. // 发送成功邮件
  93. // 重新推送
  94. go func() {
  95. _, e := c.SendMsg()
  96. if e != nil {
  97. return
  98. }
  99. }()
  100. }
  101. if sendRes.Errcode != 0 {
  102. err = errors.New("推送模板消息失败, SendTemplateResponse: " + string(body))
  103. }
  104. return
  105. }
  106. // AddUserTemplateRecord 新增模板消息推送记录
  107. func AddUserTemplateRecord(userId, sendStatus, sendType int, openid, resource, sendData, result string) (err error) {
  108. item := &models.UserTemplateRecord{
  109. UserID: userId,
  110. OpenID: openid,
  111. Resource: resource,
  112. SendData: sendData,
  113. Result: result,
  114. CreateDate: time.Now().Format(utils.FormatDate),
  115. CreateTime: time.Now().Format(utils.FormatDateTime),
  116. SendStatus: sendStatus,
  117. SendType: sendType,
  118. }
  119. err = item.Insert()
  120. return
  121. }
  122. // SendMultiTemplateMsg 推送模板消息至多个用户
  123. func SendMultiTemplateMsg(sendMap map[string]interface{}, items []*OpenIdList, resource string, sendType int) (err error) {
  124. ws := GetWxChat()
  125. accessToken, err := ws.GetAccessToken()
  126. if err != nil {
  127. return
  128. }
  129. for _, item := range items {
  130. sendMap["touser"] = item.OpenId
  131. data, e := json.Marshal(sendMap)
  132. if e != nil {
  133. err = e
  134. return
  135. }
  136. ts := &TemplateMsgSendClient{
  137. AccessToken: accessToken,
  138. Data: data,
  139. }
  140. result, e := ts.SendMsg()
  141. if result == nil {
  142. return
  143. }
  144. // 推送消息记录
  145. {
  146. go func(v *OpenIdList) {
  147. sendStatus := 1
  148. if e != nil {
  149. sendStatus = 0
  150. }
  151. resultJson, _ := json.Marshal(result)
  152. _ = AddUserTemplateRecord(v.UserId, sendStatus, sendType, v.OpenId, resource, string(data), string(resultJson))
  153. }(item)
  154. }
  155. if e != nil {
  156. err = e
  157. return
  158. }
  159. }
  160. return
  161. }