sendWxTmplMsg.go 8.9 KB

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