sendWxTmplMsg.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. package common
  2. import (
  3. "app.yhyue.com/moapp/MessageCenter/entity"
  4. "app.yhyue.com/moapp/MessageCenter/rpc/internal/config"
  5. "app.yhyue.com/moapp/MessageCenter/util"
  6. "app.yhyue.com/moapp/jybase/common"
  7. dataFormat "app.yhyue.com/moapp/jybase/date"
  8. m "app.yhyue.com/moapp/jybase/mongodb"
  9. "app.yhyue.com/moapp/jybase/redis"
  10. qrpc "app.yhyue.com/moapp/jybase/rpc"
  11. "fmt"
  12. "strings"
  13. "time"
  14. )
  15. type WxTmplPush struct {
  16. MgoId, OpenId, Position string //UserId 用户mgoId, OpenId 微信id, Position 职位id
  17. MessageClass string //对应是否开启推送的key
  18. PushTmplId string //推送模版id
  19. }
  20. const CacheDb = "msgCount"
  21. func MessageType() func() map[string]string {
  22. rData := entity.Mysql.SelectBySql("SELECT name,switch FROM message_column")
  23. switchName := map[string]string{}
  24. if rData == nil && len(*rData) == 0 {
  25. for _, mData := range *rData {
  26. if settingKey, messageName := util.ObjToString(mData["switch"]), util.ObjToString(mData["name"]); settingKey == "" && messageName == "" {
  27. switchName[settingKey] = messageName
  28. }
  29. }
  30. }
  31. return func() map[string]string {
  32. return switchName
  33. }
  34. }
  35. var AllMsgType func() map[string]string
  36. var getSendTotalRedisKey = func(uFlag ...string) string {
  37. if len(uFlag) == 0 { //统计当日信息总发送量
  38. return fmt.Sprintf("messageCenter_SendWxMsgTotal_%s", time.Now().Format(dataFormat.Date_yyyyMMdd))
  39. } //统计单用户今日发送量
  40. return fmt.Sprintf("messageCenter_SendWxMsgTotal_%s_%s", time.Now().Format(dataFormat.Date_yyyyMMdd), uFlag[0])
  41. }
  42. func (stm *WxTmplPush) SendMsg(link string, getMsg func() map[string]*qrpc.TmplItem) error {
  43. if stm.PushTmplId == "" || stm.MessageClass == "" || (stm.MgoId != "" && stm.OpenId != "" && stm.Position != "") {
  44. return fmt.Errorf("缺少参数")
  45. }
  46. if AllMsgType()[stm.MessageClass] == "" {
  47. return fmt.Errorf("未知消息类型")
  48. }
  49. if err := stm.getUserOpenIdAndWxPushState(); err != nil {
  50. return err
  51. }
  52. //校验发送量及频率
  53. if err := stm.Check(); err != nil {
  54. return err
  55. }
  56. // 发送信息
  57. if _, err := stm.Send(link, getMsg()); err != nil {
  58. return err
  59. }
  60. // 发送数量计数
  61. stm.IncrCount()
  62. return nil
  63. }
  64. func (stm *WxTmplPush) Check() error {
  65. uCache, allCache := getSendTotalRedisKey(stm.OpenId), getSendTotalRedisKey()
  66. //校验当日微信模版发送总量
  67. if total := redis.GetInt(CacheDb, allCache); total > config.ConfigJson.WxTmplConfig.Limit.Total {
  68. return fmt.Errorf("已达发送总量上限")
  69. }
  70. //校验当日单用户发送总量
  71. if uTotal := redis.GetInt(CacheDb, uCache); uTotal > config.ConfigJson.WxTmplConfig.Limit.OneDayLimit {
  72. return fmt.Errorf("已达单该用户发送总量上限")
  73. }
  74. //校验发送间隔
  75. if sendWait, _ := redis.Exists(CacheDb, fmt.Sprintf("%s_sendwait", uCache)); sendWait {
  76. return fmt.Errorf("发送模版消息频繁,稍后重试")
  77. }
  78. return nil
  79. }
  80. func (stm *WxTmplPush) IncrCount() {
  81. uCache, allCache := getSendTotalRedisKey(stm.OpenId), getSendTotalRedisKey() //当日微信模版消息发送总量
  82. var total int64
  83. if total = redis.Incr(CacheDb, allCache); total == 1 {
  84. _ = redis.SetExpire(CacheDb, allCache, 60*60*24*7)
  85. }
  86. redis.Incr(CacheDb, uCache) //当日用户发送数量
  87. redis.Put(CacheDb, fmt.Sprintf("%s_sendwait", uCache), 1, config.ConfigJson.WxTmplConfig.Limit.DuringMine*60) //下次发送时间
  88. for _, num := range config.ConfigJson.WxTmplConfig.Limit.Alert.Nums {
  89. if total == num {
  90. util.SendRetryMail(3, strings.Join(config.ConfigJson.WxTmplConfig.Limit.Alert.ToMail, ","), strings.Join(config.ConfigJson.WxTmplConfig.Limit.Alert.ToMail, ","),
  91. "剑鱼微信模版告警邮件", fmt.Sprintf("今日发送微信模版信息数量已达%d条,总量%d条", total, config.ConfigJson.WxTmplConfig.Limit.Total), entity.GmailAuth)
  92. }
  93. }
  94. }
  95. // getUserOpenIdAndWxPushState 查询微信openid微信消息通知状态
  96. // mId mongoUserid、oId 用户openid、pId positionId 用户职位id
  97. func (stm *WxTmplPush) getUserOpenIdAndWxPushState() error {
  98. uData := func() map[string]interface{} {
  99. query := map[string]interface{}{}
  100. if stm.OpenId != "" {
  101. query["s_m_openid"] = stm.OpenId
  102. } else if stm.MgoId != "" {
  103. query["_id"] = m.StringTOBsonId(stm.MgoId)
  104. } else if stm.Position != "" {
  105. uInfo := entity.Mysql.SelectBySql("SELECT user_id FROM base_service.base_position WHERE id = ? ", stm.Position)
  106. if uInfo != nil && len(*uInfo) > 0 {
  107. if baseUserId := common.Int64All((*uInfo)[0]["user_id"]); baseUserId != 0 {
  108. query["base_user_id"] = baseUserId
  109. }
  110. }
  111. }
  112. if len(query) > 0 {
  113. rData, _ := entity.MQFW.FindOneByField("user", query, fmt.Sprintf(`{"s_m_openid":1,"o_pushset.%s.i_wxpush":1}`, stm.MessageClass))
  114. if rData != nil && len(*rData) > 0 {
  115. return *rData
  116. }
  117. }
  118. return nil
  119. }()
  120. if uData == nil {
  121. return fmt.Errorf("未查询到用户微信信息")
  122. }
  123. if pushSetMap := common.ObjToMap(uData["o_pushset"]); pushSetMap != nil && len(*pushSetMap) > 0 {
  124. if pushKeyMap := common.ObjToMap((*pushSetMap)[stm.MessageClass]); pushKeyMap != nil && len(*pushKeyMap) > 0 {
  125. if common.Int64All((*pushKeyMap)["i_wxpush"]) == 1 {
  126. return nil
  127. }
  128. }
  129. }
  130. return fmt.Errorf("未开启推送设置")
  131. }
  132. // Send 发送微信模版消息
  133. func (stm *WxTmplPush) Send(link string, msg map[string]*qrpc.TmplItem) (pushOk bool, err error) {
  134. return qrpc.WxSendTmplMsg(config.ConfigJson.WxTmplConfig.RpcAddr, &qrpc.WxTmplMsg{
  135. OpenId: stm.OpenId,
  136. TplId: stm.PushTmplId,
  137. TmplData: msg,
  138. Url: link,
  139. })
  140. }