WXNotifyTest.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package main
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io/ioutil"
  7. "log"
  8. "net/http"
  9. "strings"
  10. "time"
  11. )
  12. type TemplateMsg struct {
  13. ToUser string `json:"touser"`
  14. TemplateId string `json:"template_id"`
  15. Url string `json:"url"`
  16. MiniProgram TemplateMsgMiniprogramInfo `json:"miniprogram"`
  17. Data map[string]TemplateMsgDataItem `json:"data"`
  18. }
  19. type TemplateMsgMiniprogramInfo struct {
  20. AppId string `json:"appid"`
  21. PagePath string `json:"pagepath"`
  22. }
  23. type TemplateMsgDataItem struct {
  24. Value string `json:"value"`
  25. Color string `json:"color"`
  26. }
  27. func sendTemplateMsg(bytesData []byte) string {
  28. reader := bytes.NewReader(bytesData)
  29. url := "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=13_NI_fTDDbC34LHbs1qtNPxbCdL1dnzzL9vLadYLcc_fPufMWtaNpKadstYk_PvNrD8aeBHrJeeMjvEv_oI29WjTFyPlja2VEpma1paIpAoDm9TTwtNm45zsRdFhVP_QfbJUU0xypR1zM1Dd9XUSHjABAGET"
  30. resp, err := http.Post(url, "application/json;charset=utf-8", reader)
  31. if err != nil {
  32. fmt.Println(err.Error())
  33. return "request error"
  34. }
  35. respBytes, err := ioutil.ReadAll(resp.Body)
  36. defer resp.Body.Close()
  37. if err != nil {
  38. fmt.Println(err.Error())
  39. return "response error"
  40. }
  41. return string(respBytes)
  42. }
  43. func main() {
  44. data := make(map[string]TemplateMsgDataItem)
  45. data["first"] = TemplateMsgDataItem{Value: "您发布的房源已经上线7天了,请确认房源状态是否已发生变化。"}
  46. data["keyword3"] = TemplateMsgDataItem{Value: "金地梅陇镇F栋3001"}
  47. data["remark"] = TemplateMsgDataItem{Value: "如房源仍然有效,请忽略本消息。"}
  48. msg := TemplateMsg{ToUser: "oAj8Y07DX2guxp-vmtATurBLt9PQ", TemplateId: "GBuf5jfz6oj1YNUaPBpieQrR8IK6cnxiL0BGNZ-bueA", Data: data} // 有屋叽里咕噜爷房源状态更新提醒
  49. bytesData, err := json.Marshal(msg)
  50. if err != nil {
  51. log.Fatal(err.Error())
  52. return
  53. }
  54. now := time.Now()
  55. n := 1
  56. counter := make(chan bool, n)
  57. for i := 0; i < n; i++ {
  58. go func(bytes []byte) {
  59. respStr := sendTemplateMsg(bytes)
  60. //fmt.Println(respStr)
  61. if !strings.Contains(respStr, `"errcode":0,"errmsg":"ok"`) {
  62. fmt.Println(respStr)
  63. }
  64. counter <- false
  65. }(bytesData)
  66. }
  67. for i := 0; i < n; i++ {
  68. <-counter
  69. }
  70. fmt.Println("The end")
  71. fmt.Println("cost time:", float64(time.Since(now).Nanoseconds())/1000000.0, "ms")
  72. }