wxchat.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package util
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/vmihailenco/msgpack/v5"
  6. "log"
  7. "time"
  8. )
  9. // oZMR-6SQHsxGdO9mMmvsQEz4lyHA/hy2246102093|
  10. type WxMessagetemplate struct {
  11. Openid string //微信ID
  12. Templateid string // 模板id
  13. Parameter string // 参数
  14. Reqdata string //消息体
  15. Ttime int64 // 发布时间
  16. }
  17. // **
  18. // {{character_string14.DATA}}
  19. // 企业名称
  20. // {{thing13.DATA}}
  21. // 设备名称
  22. // {{thing3.DATA}}
  23. // 传感器名称
  24. // {{thing45.DATA}}
  25. // 预警时间
  26. // {{time2.DATA}}
  27. type WxStruct struct {
  28. Character string `json:"character_string14"`
  29. Thing13 string `json:"thing13"`
  30. Thing3 string `json:"thing3"`
  31. Thing45 string `json:"thing45"`
  32. Time2 string `json:"time2"`
  33. }
  34. func Send(openid string, message WxStruct) {
  35. data := map[string]interface{}{
  36. "character_string14": map[string]interface{}{
  37. "value": message.Character,
  38. },
  39. "thing13": map[string]interface{}{
  40. "value": message.Thing13,
  41. },
  42. "thing3": map[string]interface{}{
  43. "value": message.Thing3,
  44. },
  45. "thing45": map[string]interface{}{
  46. "value": message.Thing45,
  47. },
  48. "time2": map[string]interface{}{
  49. "value": message.Time2,
  50. },
  51. }
  52. marshal, _ := json.Marshal(data)
  53. fmt.Println(string(marshal))
  54. b, _ := msgpack.Marshal(&WxMessagetemplate{
  55. Openid: openid,
  56. Templateid: "4jtNEZ--zp1QcfkN--lhJMCULgz3fxiYwRqR8dTG-WA",
  57. Parameter: "index",
  58. Reqdata: string(marshal),
  59. Ttime: time.Now().Unix(),
  60. })
  61. msg, err := Nats.Request("Wx_MessageTemplate", b, 30*time.Second) // 30 秒, 订阅端 超时 30秒 将丢弃消息
  62. if err != nil {
  63. fmt.Println(err)
  64. log.Printf("Wx_MessageTemplate : %s\n", err)
  65. }
  66. fmt.Printf("Wx_MessageTemplate : %s\n", string(msg.Data))
  67. }
  68. func Intercept(str string) string {
  69. if len(str) > 20 {
  70. return str[:20] + "..."
  71. }
  72. return str
  73. }