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