wechat_send_msg.go 13 KB

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