sendWxTmplMsg.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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. "encoding/json"
  12. "fmt"
  13. "strings"
  14. "time"
  15. )
  16. type WxTmplPush struct {
  17. MgoId, OpenId, Position string //UserId 用户mgoId, OpenId 微信id, Position 职位id
  18. Config *WxTmplConfig
  19. }
  20. var AllMsgType func() map[string]WxTmplConfig
  21. var allMsgValueKeys = []string{"$class", "$title", "$detail", "$date", "$note"}
  22. type WxTmplConfig struct {
  23. Name string //信息名称
  24. Switch string //开关
  25. TmplId string //微信模版id
  26. TmplValue string //微信模版
  27. }
  28. const CacheDb = "msgCount"
  29. func MessageType() (func() map[string]WxTmplConfig, []map[string]interface{}) {
  30. var data []map[string]interface{}
  31. rData := entity.Mysql.SelectBySql("SELECT * FROM message_column ORDER BY sequence ASC")
  32. switchName := map[string]WxTmplConfig{}
  33. if rData != nil && len(*rData) > 0 {
  34. data = *rData
  35. for _, mData := range *rData {
  36. if settingKey, messageName, tmplId, tmplValue := util.ObjToString(mData["switch"]), util.ObjToString(mData["name"]), util.ObjToString(mData["wxtmplId"]), util.ObjToString(mData["wxtmpValue"]); settingKey != "" && messageName != "" && tmplId != "" && tmplValue != "" {
  37. switchName[settingKey] = WxTmplConfig{
  38. Name: messageName,
  39. Switch: settingKey,
  40. TmplId: tmplId,
  41. TmplValue: tmplValue,
  42. }
  43. }
  44. }
  45. }
  46. return func() map[string]WxTmplConfig {
  47. return switchName
  48. }, data
  49. }
  50. var getSendTotalRedisKey = func(uFlag ...string) string {
  51. if len(uFlag) == 0 { //统计当日信息总发送量
  52. return fmt.Sprintf("messageCenter_SendWxMsgTotal_%s", time.Now().Format(dataFormat.Date_yyyyMMdd))
  53. } //统计单用户今日发送量
  54. return fmt.Sprintf("messageCenter_SendWxMsgTotal_%s_%s", time.Now().Format(dataFormat.Date_yyyyMMdd), uFlag[0])
  55. }
  56. func GetWxTmplConfig(class string) (*WxTmplConfig, error) {
  57. if val, ok := AllMsgType()[class]; ok {
  58. return &val, nil
  59. }
  60. return nil, fmt.Errorf("未知消息类型")
  61. }
  62. func (stm *WxTmplPush) SendMsg(link, title, detail, date string) error {
  63. if stm.Config.TmplId == "" || (stm.MgoId != "" && stm.OpenId != "" && stm.Position != "") {
  64. return fmt.Errorf("缺少参数")
  65. }
  66. // 校验推送是否开启
  67. if err := stm.getUserOpenIdAndWxPushState(); err != nil {
  68. return err
  69. }
  70. // 校验发送量及频率
  71. if err := stm.Check(); err != nil {
  72. return err
  73. }
  74. // 获取消息
  75. msg, err := stm.getMessage(title, detail, date)
  76. if err != nil {
  77. return err
  78. }
  79. // 发送信息
  80. if _, err := stm.Send(link, msg); err != nil {
  81. return err
  82. }
  83. // 发送数量计数
  84. stm.IncrCount()
  85. return nil
  86. }
  87. // getMessage 获取消息内容
  88. func (stm *WxTmplPush) getMessage(title, detail, date string) (map[string]*qrpc.TmplItem, error) {
  89. var formatValue string = stm.Config.TmplValue
  90. for _, key := range allMsgValueKeys {
  91. switch key {
  92. case "$class":
  93. formatValue = strings.ReplaceAll(formatValue, key, stm.Config.Name)
  94. case "$title":
  95. formatValue = strings.ReplaceAll(formatValue, key, title)
  96. case "$detail":
  97. formatValue = strings.ReplaceAll(formatValue, key, detail)
  98. case "$date":
  99. formatValue = strings.ReplaceAll(formatValue, key, date)
  100. case "$note":
  101. formatValue = strings.ReplaceAll(formatValue, key, config.ConfigJson.WxTmplConfig.CloseNotice)
  102. }
  103. }
  104. bValue := map[string]*qrpc.TmplItem{}
  105. if err := json.Unmarshal([]byte(formatValue), &bValue); err != nil {
  106. return nil, fmt.Errorf("格式化信息内容异常 %s", err.Error())
  107. }
  108. return bValue, nil
  109. }
  110. // Check 校验发送量和频率
  111. func (stm *WxTmplPush) Check() error {
  112. uCache, allCache := getSendTotalRedisKey(stm.OpenId), getSendTotalRedisKey()
  113. //校验当日微信模版发送总量
  114. if total := redis.GetInt(CacheDb, allCache); total > config.ConfigJson.WxTmplConfig.Limit.Total {
  115. return fmt.Errorf("已达发送总量上限")
  116. }
  117. //校验当日单用户发送总量
  118. if uTotal := redis.GetInt(CacheDb, uCache); uTotal > config.ConfigJson.WxTmplConfig.Limit.OneDayLimit {
  119. return fmt.Errorf("已达单该用户发送总量上限")
  120. }
  121. //校验发送间隔
  122. if sendWait, _ := redis.Exists(CacheDb, fmt.Sprintf("%s_sendwait", uCache)); sendWait {
  123. return fmt.Errorf("发送模版消息频繁,稍后重试")
  124. }
  125. return nil
  126. }
  127. func (stm *WxTmplPush) IncrCount() {
  128. uCache, allCache := getSendTotalRedisKey(stm.OpenId), getSendTotalRedisKey() //当日微信模版消息发送总量
  129. var total int64
  130. if total = redis.Incr(CacheDb, allCache); total == 1 {
  131. _ = redis.SetExpire(CacheDb, allCache, 60*60*24)
  132. }
  133. if uTotal := redis.Incr(CacheDb, uCache); uTotal == 1 {
  134. _ = redis.SetExpire(CacheDb, uCache, 60*60*24)
  135. } //当日用户发送数量
  136. redis.Put(CacheDb, fmt.Sprintf("%s_sendwait", uCache), 1, config.ConfigJson.WxTmplConfig.Limit.DuringMine*60) //下次发送时间
  137. for _, num := range config.ConfigJson.WxTmplConfig.Limit.Alert.Nums {
  138. if total == num {
  139. util.SendRetryMail(3, strings.Join(config.ConfigJson.WxTmplConfig.Limit.Alert.ToMail, ","), strings.Join(config.ConfigJson.WxTmplConfig.Limit.Alert.ToMail, ","),
  140. "剑鱼微信模版告警邮件", fmt.Sprintf("今日发送微信模版信息数量已达%d条,总量%d条", total, config.ConfigJson.WxTmplConfig.Limit.Total), entity.GmailAuth)
  141. }
  142. }
  143. }
  144. // getUserOpenIdAndWxPushState 查询微信openid微信消息通知状态
  145. // mId mongoUserid、oId 用户openid、pId positionId 用户职位id
  146. func (stm *WxTmplPush) getUserOpenIdAndWxPushState() error {
  147. uData := func() map[string]interface{} {
  148. query := map[string]interface{}{}
  149. if stm.OpenId != "" {
  150. query["s_m_openid"] = stm.OpenId
  151. } else if stm.MgoId != "" {
  152. query["_id"] = m.StringTOBsonId(stm.MgoId)
  153. } else if stm.Position != "" {
  154. uInfo := entity.Mysql.SelectBySql("SELECT user_id FROM base_service.base_position WHERE id = ? ", stm.Position)
  155. if uInfo != nil && len(*uInfo) > 0 {
  156. if baseUserId := common.Int64All((*uInfo)[0]["user_id"]); baseUserId != 0 {
  157. query["base_user_id"] = baseUserId
  158. }
  159. }
  160. }
  161. if len(query) > 0 {
  162. rData, _ := entity.MQFW.FindOneByField("user", query, fmt.Sprintf(`{"s_m_openid":1,"o_pushset.%s.i_wxpush":1}`, stm.Config.Switch))
  163. if rData != nil && len(*rData) > 0 {
  164. return *rData
  165. }
  166. }
  167. return nil
  168. }()
  169. if uData == nil {
  170. return fmt.Errorf("未查询到用户信息")
  171. }
  172. stm.OpenId = common.ObjToString(uData["s_m_openid"])
  173. if stm.OpenId == "" {
  174. return fmt.Errorf("未查询到用户微信信息")
  175. }
  176. if pushSetMap := common.ObjToMap(uData["o_pushset"]); pushSetMap != nil && len(*pushSetMap) > 0 {
  177. if pushKeyMap := common.ObjToMap((*pushSetMap)[stm.Config.Switch]); pushKeyMap != nil && len(*pushKeyMap) > 0 {
  178. if common.Int64All((*pushKeyMap)["i_wxpush"]) == 1 {
  179. return nil
  180. }
  181. }
  182. }
  183. return fmt.Errorf("未开启推送设置")
  184. }
  185. // Send 发送微信模版消息
  186. func (stm *WxTmplPush) Send(link string, msg map[string]*qrpc.TmplItem) (pushOk bool, err error) {
  187. return qrpc.WxSendTmplMsg(config.ConfigJson.WxTmplConfig.RpcAddr, &qrpc.WxTmplMsg{
  188. OpenId: stm.OpenId,
  189. TplId: stm.Config.TmplId,
  190. TmplData: msg,
  191. Url: link,
  192. })
  193. }