sendWxTmplMsg.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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. if err := json.Unmarshal([]byte(formatValue), &bValue); err != nil {
  128. return nil, fmt.Errorf("格式化信息内容异常 %s", err.Error())
  129. }
  130. for _, item := range bValue {
  131. val := []rune(item.Value)
  132. if len(val) > 20 {
  133. item.Value = string(val[:17]) + "..."
  134. }
  135. }
  136. return bValue, nil
  137. }
  138. // RollBack 发送失败数量回滚
  139. func (stm *WxTmplPush) RollBack() {
  140. uCache, allCache := getSendTotalRedisKey(stm.OpenId), getSendTotalRedisKey()
  141. redis.Decrby(CacheDb, allCache, 1)
  142. redis.Decrby(CacheDb, uCache, 1)
  143. redis.Del(CacheDb, fmt.Sprintf("%s_sendwait", uCache)) //清除发送间隔
  144. }
  145. func (stm *WxTmplPush) IncrCount() (error, func()) {
  146. uCache, allCache := getSendTotalRedisKey(stm.OpenId), getSendTotalRedisKey() //当日微信模版消息发送总量
  147. //校验发送间隔
  148. if sendWait, _ := redis.Exists(CacheDb, fmt.Sprintf("%s_sendwait", uCache)); sendWait {
  149. return fmt.Errorf("发送模版消息频繁,稍后重试"), nil
  150. }
  151. var total int64
  152. if total = redis.Incr(CacheDb, allCache); total == 1 {
  153. _ = redis.SetExpire(CacheDb, allCache, 60*60*24)
  154. }
  155. if total > config.ConfigJson.WxTmplConfig.Limit.Total {
  156. redis.Decrby(CacheDb, allCache, 1)
  157. return fmt.Errorf("已达发送总量上限"), nil
  158. }
  159. uTotal := redis.Incr(CacheDb, uCache)
  160. if uTotal == 1 {
  161. _ = redis.SetExpire(CacheDb, uCache, 60*60*24)
  162. } //当日用户发送数量
  163. if uTotal > config.ConfigJson.WxTmplConfig.Limit.OneDayLimit {
  164. redis.Decrby(CacheDb, allCache, 1)
  165. redis.Decrby(CacheDb, uCache, 1)
  166. return fmt.Errorf("已达单该用户发送总量上限"), nil
  167. }
  168. //下次发送时间
  169. redis.Put(CacheDb, fmt.Sprintf("%s_sendwait", uCache), 1, config.ConfigJson.WxTmplConfig.Limit.DuringMine*60)
  170. return nil, func() {
  171. for _, num := range config.ConfigJson.WxTmplConfig.Limit.Alert.Nums {
  172. if total == num {
  173. util.SendRetryMail(3, strings.Join(config.ConfigJson.WxTmplConfig.Limit.Alert.ToMail, ","), strings.Join(config.ConfigJson.WxTmplConfig.Limit.Alert.CcMail, ","),
  174. "剑鱼微信模版告警邮件", fmt.Sprintf("今日发送微信模版信息数量已达%d条,总量%d条", total, config.ConfigJson.WxTmplConfig.Limit.Total), entity.GmailAuth)
  175. }
  176. }
  177. }
  178. }
  179. // getUserOpenIdAndWxPushState 查询微信openid微信消息通知状态
  180. // mId mongoUserid、oId 用户openid、pId positionId 用户职位id
  181. func (stm *WxTmplPush) getUserOpenIdAndWxPushState() error {
  182. uData := stm.GetUserPushInfo()
  183. if uData == nil {
  184. return fmt.Errorf("未查询到用户信息")
  185. }
  186. stm.OpenId = common.ObjToString(uData["s_m_openid"])
  187. if stm.OpenId == "" {
  188. return fmt.Errorf("未查询到用户微信信息")
  189. }
  190. log.Println("======", stm.Config.Switch)
  191. if pushSetMap := common.ObjToMap(uData["o_pushset"]); pushSetMap != nil && len(*pushSetMap) > 0 {
  192. if pushKeyMap := common.ObjToMap((*pushSetMap)[stm.Config.Switch]); pushKeyMap != nil && len(*pushKeyMap) > 0 {
  193. if common.Int64All((*pushKeyMap)["i_wxpush"]) == 1 {
  194. return nil
  195. }
  196. }
  197. }
  198. return fmt.Errorf("未开启推送设置")
  199. }
  200. func (stm *WxTmplPush) GetUserPushInfo() map[string]interface{} {
  201. uData := func() map[string]interface{} {
  202. query := map[string]interface{}{}
  203. if stm.OpenId != "" {
  204. query["s_m_openid"] = stm.OpenId
  205. } else if stm.MgoId != "" {
  206. query["_id"] = m.StringTOBsonId(stm.MgoId)
  207. } else if stm.Position != "" {
  208. uInfo := entity.Mysql.SelectBySql("SELECT user_id FROM base_service.base_position WHERE id = ? ", stm.Position)
  209. if uInfo != nil && len(*uInfo) > 0 {
  210. if baseUserId := common.Int64All((*uInfo)[0]["user_id"]); baseUserId != 0 {
  211. query["base_user_id"] = baseUserId
  212. }
  213. }
  214. }
  215. if len(query) > 0 {
  216. 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))
  217. if rData != nil && len(*rData) > 0 {
  218. return *rData
  219. }
  220. }
  221. return nil
  222. }()
  223. return uData
  224. }
  225. // Send 发送微信模版消息
  226. func (stm *WxTmplPush) Send(link string, msg map[string]*qrpc.TmplItem) (pushOk bool, err error) {
  227. return qrpc.WxSendTmplMsg(config.ConfigJson.WxTmplConfig.RpcAddr, &qrpc.WxTmplMsg{
  228. OpenId: stm.OpenId,
  229. TplId: stm.Config.TmplId,
  230. TmplData: msg,
  231. Url: link,
  232. })
  233. }