sendWxTmplMsg.go 5.6 KB

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