sendWxTmplMsg.go 5.7 KB

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