sendWxTmplMsg.go 7.3 KB

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