sendWxTmplMsg.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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. autoLoginHref := fmt.Sprintf("%s/swordfish/SingleLogin?toHref=%s", config.ConfigJson.WxWebdomain, link)
  81. if _, err := stm.Send(autoLoginHref, msg); err != nil {
  82. return err
  83. }
  84. // 发送数量计数
  85. stm.IncrCount()
  86. return nil
  87. }
  88. // getMessage 获取消息内容
  89. func (stm *WxTmplPush) getMessage(title, detail, date string) (map[string]*qrpc.TmplItem, error) {
  90. var formatValue string = stm.Config.TmplValue
  91. for _, key := range allMsgValueKeys {
  92. switch key {
  93. case "$class":
  94. formatValue = strings.ReplaceAll(formatValue, key, stm.Config.Name)
  95. case "$title":
  96. formatValue = strings.ReplaceAll(formatValue, key, title)
  97. case "$detail":
  98. formatValue = strings.ReplaceAll(formatValue, key, detail)
  99. case "$date":
  100. formatValue = strings.ReplaceAll(formatValue, key, date)
  101. case "$note":
  102. formatValue = strings.ReplaceAll(formatValue, key, config.ConfigJson.WxTmplConfig.CloseNotice)
  103. }
  104. }
  105. bValue := map[string]*qrpc.TmplItem{}
  106. if err := json.Unmarshal([]byte(formatValue), &bValue); err != nil {
  107. return nil, fmt.Errorf("格式化信息内容异常 %s", err.Error())
  108. }
  109. return bValue, nil
  110. }
  111. // Check 校验发送量和频率
  112. func (stm *WxTmplPush) Check() error {
  113. uCache, allCache := getSendTotalRedisKey(stm.OpenId), getSendTotalRedisKey()
  114. //校验当日微信模版发送总量
  115. if total := redis.GetInt(CacheDb, allCache); total > config.ConfigJson.WxTmplConfig.Limit.Total {
  116. return fmt.Errorf("已达发送总量上限")
  117. }
  118. //校验当日单用户发送总量
  119. if uTotal := redis.GetInt(CacheDb, uCache); uTotal > config.ConfigJson.WxTmplConfig.Limit.OneDayLimit {
  120. return fmt.Errorf("已达单该用户发送总量上限")
  121. }
  122. //校验发送间隔
  123. if sendWait, _ := redis.Exists(CacheDb, fmt.Sprintf("%s_sendwait", uCache)); sendWait {
  124. return fmt.Errorf("发送模版消息频繁,稍后重试")
  125. }
  126. return nil
  127. }
  128. func (stm *WxTmplPush) IncrCount() {
  129. uCache, allCache := getSendTotalRedisKey(stm.OpenId), getSendTotalRedisKey() //当日微信模版消息发送总量
  130. var total int64
  131. if total = redis.Incr(CacheDb, allCache); total == 1 {
  132. _ = redis.SetExpire(CacheDb, allCache, 60*60*24)
  133. }
  134. if uTotal := redis.Incr(CacheDb, uCache); uTotal == 1 {
  135. _ = redis.SetExpire(CacheDb, uCache, 60*60*24)
  136. } //当日用户发送数量
  137. redis.Put(CacheDb, fmt.Sprintf("%s_sendwait", uCache), 1, config.ConfigJson.WxTmplConfig.Limit.DuringMine*60) //下次发送时间
  138. for _, num := range config.ConfigJson.WxTmplConfig.Limit.Alert.Nums {
  139. if total == num {
  140. util.SendRetryMail(3, strings.Join(config.ConfigJson.WxTmplConfig.Limit.Alert.ToMail, ","), strings.Join(config.ConfigJson.WxTmplConfig.Limit.Alert.ToMail, ","),
  141. "剑鱼微信模版告警邮件", fmt.Sprintf("今日发送微信模版信息数量已达%d条,总量%d条", total, config.ConfigJson.WxTmplConfig.Limit.Total), entity.GmailAuth)
  142. }
  143. }
  144. }
  145. // getUserOpenIdAndWxPushState 查询微信openid微信消息通知状态
  146. // mId mongoUserid、oId 用户openid、pId positionId 用户职位id
  147. func (stm *WxTmplPush) getUserOpenIdAndWxPushState() error {
  148. uData := func() map[string]interface{} {
  149. query := map[string]interface{}{}
  150. if stm.OpenId != "" {
  151. query["s_m_openid"] = stm.OpenId
  152. } else if stm.MgoId != "" {
  153. query["_id"] = m.StringTOBsonId(stm.MgoId)
  154. } else if stm.Position != "" {
  155. uInfo := entity.Mysql.SelectBySql("SELECT user_id FROM base_service.base_position WHERE id = ? ", stm.Position)
  156. if uInfo != nil && len(*uInfo) > 0 {
  157. if baseUserId := common.Int64All((*uInfo)[0]["user_id"]); baseUserId != 0 {
  158. query["base_user_id"] = baseUserId
  159. }
  160. }
  161. }
  162. if len(query) > 0 {
  163. rData, _ := entity.MQFW.FindOneByField("user", query, fmt.Sprintf(`{"s_m_openid":1,"o_pushset.%s.i_wxpush":1}`, stm.Config.Switch))
  164. if rData != nil && len(*rData) > 0 {
  165. return *rData
  166. }
  167. }
  168. return nil
  169. }()
  170. if uData == nil {
  171. return fmt.Errorf("未查询到用户信息")
  172. }
  173. stm.OpenId = common.ObjToString(uData["s_m_openid"])
  174. if stm.OpenId == "" {
  175. return fmt.Errorf("未查询到用户微信信息")
  176. }
  177. if pushSetMap := common.ObjToMap(uData["o_pushset"]); pushSetMap != nil && len(*pushSetMap) > 0 {
  178. if pushKeyMap := common.ObjToMap((*pushSetMap)[stm.Config.Switch]); pushKeyMap != nil && len(*pushKeyMap) > 0 {
  179. if common.Int64All((*pushKeyMap)["i_wxpush"]) == 1 {
  180. return nil
  181. }
  182. }
  183. }
  184. return fmt.Errorf("未开启推送设置")
  185. }
  186. // Send 发送微信模版消息
  187. func (stm *WxTmplPush) Send(link string, msg map[string]*qrpc.TmplItem) (pushOk bool, err error) {
  188. return qrpc.WxSendTmplMsg(config.ConfigJson.WxTmplConfig.RpcAddr, &qrpc.WxTmplMsg{
  189. OpenId: stm.OpenId,
  190. TplId: stm.Config.TmplId,
  191. TmplData: msg,
  192. Url: link,
  193. })
  194. }