sendWxTmplMsg.go 8.0 KB

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