wechat_send_msg.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. package services
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "eta/eta_pub/models"
  7. "eta/eta_pub/services/alarm_msg"
  8. "eta/eta_pub/utils"
  9. "fmt"
  10. "io/ioutil"
  11. "net/http"
  12. "strconv"
  13. "strings"
  14. "time"
  15. )
  16. type SendTemplateResponse struct {
  17. Errcode int `json:"errcode"`
  18. Errmsg string `json:"errmsg"`
  19. MsgID int `json:"msgid"`
  20. }
  21. type ClearQuotaResponse struct {
  22. Errcode int `json:"errcode"`
  23. Errmsg string `json:"errmsg"`
  24. }
  25. func SendWxTemplateMsg(sendInfo *models.SendWxTemplate) (err error) {
  26. var msg string
  27. defer func() {
  28. if err != nil {
  29. go alarm_msg.SendAlarmMsg("发送模版消息失败,Err:"+err.Error()+";msg:"+msg, 3)
  30. utils.FileLog.Info(fmt.Sprintf("发送模版消息失败,Err:%s,%s", err.Error(), msg))
  31. }
  32. if msg != "" {
  33. utils.FileLog.Info(fmt.Sprintf("发送模版消息失败,msg:%s", msg))
  34. }
  35. }()
  36. utils.FileLog.Info("services SendMsg")
  37. fmt.Println("send start")
  38. utils.FileLog.Info("send start")
  39. sendMap := make(map[string]interface{})
  40. sendData := make(map[string]interface{})
  41. var uniqueCodeStr string
  42. if sendInfo.WxAppId != "" {
  43. uniqueCodeStr += sendInfo.WxAppId
  44. }
  45. if sendInfo.First != "" {
  46. sendData["first"] = map[string]interface{}{"value": sendInfo.First, "color": "#173177"}
  47. uniqueCodeStr += sendInfo.First
  48. }
  49. if sendInfo.Keyword1 != "" {
  50. sendData["keyword1"] = map[string]interface{}{"value": sendInfo.Keyword1, "color": "#173177"}
  51. uniqueCodeStr += sendInfo.Keyword1
  52. }
  53. if sendInfo.Keyword2 != "" {
  54. sendData["keyword2"] = map[string]interface{}{"value": sendInfo.Keyword2, "color": "#173177"}
  55. uniqueCodeStr += sendInfo.Keyword2
  56. }
  57. if sendInfo.Keyword3 != "" {
  58. sendData["keyword3"] = map[string]interface{}{"value": sendInfo.Keyword3, "color": "#173177"}
  59. uniqueCodeStr += sendInfo.Keyword3
  60. }
  61. if sendInfo.Keyword4 != "" {
  62. sendData["keyword4"] = map[string]interface{}{"value": sendInfo.Keyword4, "color": "#173177"}
  63. uniqueCodeStr += sendInfo.Keyword4
  64. }
  65. if sendInfo.Keyword5 != "" {
  66. sendData["keyword5"] = map[string]interface{}{"value": sendInfo.Keyword5, "color": "#173177"}
  67. uniqueCodeStr += sendInfo.Keyword5
  68. }
  69. if sendInfo.Productname != "" {
  70. sendData["productname"] = map[string]interface{}{"value": sendInfo.Productname, "color": "#173177"}
  71. uniqueCodeStr += sendInfo.Productname
  72. }
  73. if sendInfo.Date != "" {
  74. sendData["date"] = map[string]interface{}{"value": sendInfo.Date, "color": "#173177"}
  75. uniqueCodeStr += sendInfo.Date
  76. }
  77. if sendInfo.Remark != "" {
  78. sendData["remark"] = map[string]interface{}{"value": sendInfo.Remark, "color": "#173177"}
  79. uniqueCodeStr += sendInfo.Remark
  80. }
  81. if sendInfo.TemplateId != "" {
  82. sendMap["template_id"] = sendInfo.TemplateId
  83. uniqueCodeStr += sendInfo.TemplateId
  84. }
  85. if sendInfo.RedirectUrl != "" {
  86. if strings.Contains(sendInfo.RedirectUrl, "http") || strings.Contains(sendInfo.RedirectUrl, "https") || sendInfo.RedirectTarget == 0 {
  87. sendMap["url"] = sendInfo.RedirectUrl
  88. } else {
  89. var xcxAppId string
  90. if sendInfo.RedirectTarget == 1 {
  91. xcxAppId = utils.WxYbAppId
  92. } else if sendInfo.RedirectTarget == 2 {
  93. xcxAppId = utils.WxCrmAppId
  94. } else if sendInfo.RedirectTarget == 3 {
  95. xcxAppId = utils.WxCygxAppId
  96. } else {
  97. err = errors.New("无效的微信小程序跳转方式:RedirectTarget" + strconv.Itoa(sendInfo.RedirectTarget))
  98. return err
  99. }
  100. sendMap["miniprogram"] = map[string]interface{}{"appid": xcxAppId, "pagepath": sendInfo.RedirectUrl}
  101. }
  102. uniqueCodeStr += sendInfo.RedirectUrl
  103. }
  104. sendMap["data"] = sendData
  105. uniqueCode := utils.MD5(uniqueCodeStr)
  106. err = sendTemplateMsg(sendInfo.WxAppId, sendMap, sendInfo.OpenIdArr, sendInfo.Resource, uniqueCode, sendInfo.SendType)
  107. if err != nil {
  108. utils.FileLog.Info("send err:" + err.Error())
  109. }
  110. fmt.Println("send end")
  111. utils.FileLog.Info("send end")
  112. return
  113. }
  114. // sendTemplateMsg 整理openid以及以往历史推送记录,移除已经推送的记录,并开始依次推送
  115. func sendTemplateMsg(wxAppId string, sendMap map[string]interface{}, openIdArr []string, resource, uniqueCode string, sendType int) (err error) {
  116. existList, err := models.GetTemplateRecordByUniqueCode(uniqueCode)
  117. if err != nil && err.Error() != utils.ErrNoRow() {
  118. utils.FileLog.Info(fmt.Sprintf("GetTemplateRecordByUniqueCode Err:%s", err.Error()))
  119. return err
  120. }
  121. if len(existList) == 0 {
  122. for _, openId := range openIdArr {
  123. sendMap["touser"] = openId
  124. data, err := json.Marshal(sendMap)
  125. if err != nil {
  126. fmt.Println("SendTemplateMsgOne Marshal Err:", err.Error())
  127. utils.FileLog.Info(fmt.Sprintf("SendTemplateMsgOne Marshal Err:%s", err.Error()))
  128. return err
  129. }
  130. err = toSendTemplateMsg(wxAppId, data, resource, sendType, openId, uniqueCode)
  131. if err != nil {
  132. fmt.Println("send err:", err.Error())
  133. utils.FileLog.Info(fmt.Sprintf("ToSendTemplateMsg Err:%s", err.Error()))
  134. }
  135. }
  136. } else {
  137. existOpenIdMap := make(map[string]string)
  138. for _, v := range existList {
  139. existOpenIdMap[v.OpenId] = v.OpenId
  140. }
  141. for _, openId := range openIdArr {
  142. if _, ok := existOpenIdMap[openId]; !ok {
  143. sendMap["touser"] = openId
  144. data, err := json.Marshal(sendMap)
  145. if err != nil {
  146. fmt.Println("SendTemplateMsgOne Marshal Err:", err.Error())
  147. utils.FileLog.Info(fmt.Sprintf("SendTemplateMsgOne Marshal Err:%s", err.Error()))
  148. return err
  149. }
  150. err = toSendTemplateMsg(wxAppId, data, resource, sendType, openId, uniqueCode)
  151. if err != nil {
  152. fmt.Println("send err:", err.Error())
  153. utils.FileLog.Info(fmt.Sprintf("ToSendTemplateMsg Err:%s", err.Error()))
  154. }
  155. }
  156. }
  157. }
  158. return
  159. }
  160. // toSendTemplateMsg 实际推送微信
  161. func toSendTemplateMsg(wxAppId string, data []byte, resource string, sendType int, openId, uniqueCode string) (err error) {
  162. utils.FileLog.Info("Send:" + string(data))
  163. //获取accessToken
  164. var accessToken string
  165. var errMsg string
  166. accessToken, err, errMsg = getWxAccessToken(wxAppId, "")
  167. if err != nil {
  168. utils.FileLog.Info(fmt.Sprintf("获取Token失败,err:%s,errMsg:%s", err.Error(), errMsg))
  169. return
  170. }
  171. sendUrl := "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken
  172. client := http.Client{}
  173. resp, err := client.Post(sendUrl, "application/json", bytes.NewBuffer(data))
  174. if err != nil {
  175. return
  176. }
  177. defer resp.Body.Close()
  178. body, _ := ioutil.ReadAll(resp.Body)
  179. utils.FileLog.Info("SendResult:" + string(body))
  180. var templateResponse SendTemplateResponse
  181. err = json.Unmarshal(body, &templateResponse)
  182. if err != nil {
  183. utils.FileLog.Info(fmt.Sprintf("SendResult Unmarshal Err:%s", err.Error()))
  184. return err
  185. }
  186. //新增模板消息推送记录
  187. {
  188. tr := new(models.UserTemplateRecord)
  189. tr.OpenId = openId
  190. tr.Resource = resource
  191. tr.SendData = string(data)
  192. tr.Result = string(body)
  193. tr.CreateDate = time.Now().Format(utils.FormatDate)
  194. tr.CreateTime = time.Now().Format(utils.FormatDateTime)
  195. if templateResponse.Errcode == 0 {
  196. tr.SendStatus = 1
  197. } else {
  198. tr.SendStatus = 0
  199. }
  200. tr.UniqueCode = uniqueCode
  201. tr.SendType = sendType
  202. tr.WxAppId = wxAppId
  203. go func() {
  204. err = models.AddUserTemplateRecord(tr)
  205. if err != nil {
  206. utils.FileLog.Info(fmt.Sprintf("AddUserTemplateRecord Err:%s", err.Error()))
  207. }
  208. }()
  209. }
  210. //accessToken过期
  211. if templateResponse.Errcode == 40001 {
  212. //强刷token并重新推送
  213. accessToken, err, errMsg = refreshWxAccessToken(wxAppId, "")
  214. if err != nil {
  215. utils.FileLog.Info(fmt.Sprintf("refreshWxAccessToken Err:%s", err.Error()))
  216. return err
  217. }
  218. return toSendTemplateMsg(wxAppId, data, resource, sendType, openId, uniqueCode)
  219. }
  220. //模板消息发送超过当日10万次限制错误处理
  221. if templateResponse.Errcode == 45009 {
  222. key := "CACHE_SendTemplateMsg_ERR"
  223. isExist := utils.Rc.IsExist(key)
  224. if isExist == true {
  225. return
  226. } else {
  227. result, _ := json.Marshal(templateResponse)
  228. if err != nil {
  229. utils.FileLog.Info(fmt.Sprintf("templateResponse Marshal Err:%s", err.Error()))
  230. return err
  231. }
  232. //发送邮件提醒异常
  233. go alarm_msg.SendAlarmMsg("模板消息发送超过当日10万次限制,templateResponse = "+string(result), 3)
  234. //go utils.SendEmail("异常提醒:", "模板消息发送超过当日10万次限制,templateResponse = "+string(result), utils.EmailSendToUsers)
  235. //设置3分钟缓存,不允许重复添加
  236. utils.Rc.SetNX(key, 1, 6*time.Minute)
  237. }
  238. //清空发送次数
  239. sendUrl := fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/clear_quota?access_token=%s", accessToken)
  240. clearData := make(map[string]interface{})
  241. clearData["appid"] = utils.WxAppId
  242. clearJson, _ := json.Marshal(clearData)
  243. utils.FileLog.Info("clear_quota data:" + string(clearJson))
  244. resp, err := client.Post(sendUrl, "application/json", bytes.NewBuffer(clearJson))
  245. if err != nil {
  246. return err
  247. }
  248. defer resp.Body.Close()
  249. clearBody, err := ioutil.ReadAll(resp.Body)
  250. utils.FileLog.Info("clear_quota result:" + string(clearBody))
  251. var clearQuotaResponse ClearQuotaResponse
  252. err = json.Unmarshal(clearBody, &clearQuotaResponse)
  253. if err != nil {
  254. utils.FileLog.Info(fmt.Sprintf("clearQuotaResponse Unmarshal Err:%s", err.Error()))
  255. return err
  256. }
  257. if clearQuotaResponse.Errcode == 0 {
  258. //发送邮件解决异常
  259. go alarm_msg.SendAlarmMsg("异常已解决,自动清理限制接口,调用成功", 3)
  260. //go utils.SendEmail("异常已解决:", "自动清理限制接口,调用成功", utils.EmailSendToUsers)
  261. //重新推送一次
  262. toSendTemplateMsg(wxAppId, data, resource, sendType, openId, uniqueCode)
  263. }
  264. }
  265. return
  266. }
  267. // GetWxAccessToken 获取微信token
  268. func GetWxAccessToken(wxAppId, wxAppSecret string) (accessToken string, err error, errMsg string) {
  269. accessToken, err, errMsg = getWxAccessToken(wxAppId, wxAppSecret)
  270. if err != nil {
  271. utils.FileLog.Info(fmt.Sprintf("获取Token失败,err:%s,errMsg:%s", err.Error(), errMsg))
  272. return
  273. }
  274. return
  275. }
  276. // getWxAccessToken 获取微信token
  277. func getWxAccessToken(wxAppId, wxAppSecret string) (accessToken string, err error, errMsg string) {
  278. redisKey := getRedisKeyByAppid(wxAppId)
  279. if redisKey == `` {
  280. errMsg = "未配置缓存key"
  281. err = errors.New(errMsg)
  282. return
  283. }
  284. accessToken, err = utils.Rc.RedisString(redisKey)
  285. //fmt.Println(err)
  286. //fmt.Println(accessToken)
  287. //if err != nil {
  288. // errMsg = "GetWxAccessToken Err:" + err.Error()
  289. // utils.FileLog.Info("获取Token失败,msg:" + errMsg)
  290. // return
  291. //}
  292. //取到数据后就直接返回了,没有后续了
  293. if accessToken != "" {
  294. return
  295. }
  296. //缓存中没有取到数据,那么需要去强制刷新新的accessToken
  297. return refreshWxAccessToken(wxAppId, wxAppSecret)
  298. }
  299. // refreshWxAccessToken 强制刷新微信token
  300. func refreshWxAccessToken(wxAppId, wxAppSecret string) (accessToken string, err error, errMsg string) {
  301. fmt.Println("强制刷新" + wxAppId + "微信token")
  302. defer func() {
  303. if errMsg != `` {
  304. utils.FileLog.Info(fmt.Sprintf("强制刷新%s微信token异常:%s", wxAppId, errMsg))
  305. }
  306. }()
  307. redisKey := getRedisKeyByAppid(wxAppId)
  308. if redisKey == `` {
  309. errMsg = "未配置缓存key"
  310. err = errors.New(errMsg)
  311. return
  312. }
  313. if wxAppSecret == "" {
  314. wxAppSecret, _ = utils.WxAppList[wxAppId]
  315. }
  316. if wxAppSecret == "" {
  317. err = errors.New("缺少密钥信息")
  318. utils.FileLog.Info(fmt.Sprintf("获取Token失败, errMsg:%s", err.Error()))
  319. return
  320. }
  321. //调用微信官方接口获取新的accessToken
  322. wxAccessToken, tmpErr := models.GetWxToken(wxAppId, wxAppSecret)
  323. if tmpErr != nil {
  324. err = tmpErr
  325. errMsg = "通过微信接口获取accessToken失败 Err:" + err.Error()
  326. return
  327. }
  328. //如果没有token数据
  329. if wxAccessToken.AccessToken == "" {
  330. errMsg = "微信返回的accessToken异常: Err:" + wxAccessToken.Errmsg
  331. err = errors.New(errMsg)
  332. return
  333. }
  334. accessToken = wxAccessToken.AccessToken
  335. //如果是弘则研究的appid,那么需要更新mysql的accessToken
  336. if wxAppId == utils.WxAppId {
  337. expiresIn := time.Now().Add(time.Duration(wxAccessToken.ExpiresIn) * time.Second).Unix()
  338. err = models.ModifyAccessToken(wxAccessToken.AccessToken, expiresIn)
  339. if err != nil {
  340. errMsg = "更新mysql中的accessToken失败 Err:" + err.Error()
  341. return
  342. }
  343. }
  344. //更新redis的accessToken(过期时间提前十分钟)
  345. redisTimeExpire := time.Duration(wxAccessToken.ExpiresIn-600) * time.Second
  346. err = utils.Rc.Put(redisKey, accessToken, redisTimeExpire)
  347. if err != nil {
  348. errMsg = "更新redis中的accessToken失败 Err:" + err.Error()
  349. return
  350. }
  351. return
  352. }
  353. // 根据微信appid获取对应的缓存key
  354. func getRedisKeyByAppid(wxAppId string) (redisKey string) {
  355. switch wxAppId {
  356. case utils.WxAppId:
  357. redisKey = utils.CACHE_WX_ACCESS_TOKEN_HZ
  358. case utils.AdminWxAppId:
  359. redisKey = utils.HZ_ADMIN_WX_ACCESS_TOEKN + wxAppId
  360. default:
  361. redisKey = utils.HZ_ADMIN_WX_ACCESS_TOEKN + wxAppId
  362. }
  363. return redisKey
  364. }