template.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package template
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/silenceper/wechat/context"
  6. "github.com/silenceper/wechat/util"
  7. )
  8. const (
  9. templateSendURL = "https://api.weixin.qq.com/cgi-bin/message/template/send"
  10. )
  11. //Template 模板消息
  12. type Template struct {
  13. *context.Context
  14. }
  15. //NewTemplate 实例化
  16. func NewTemplate(context *context.Context) *Template {
  17. tpl := new(Template)
  18. tpl.Context = context
  19. return tpl
  20. }
  21. //Message 发送的模板消息内容
  22. type Message struct {
  23. ToUser string `json:"touser"` // 必须, 接受者OpenID
  24. TemplateID string `json:"template_id"` // 必须, 模版ID
  25. URL string `json:"url,omitempty"` // 可选, 用户点击后跳转的URL, 该URL必须处于开发者在公众平台网站中设置的域中
  26. Color string `json:"color,omitempty"` // 可选, 整个消息的颜色, 可以不设置
  27. Data map[string]*DataItem `json:"data"` // 必须, 模板数据
  28. MiniProgram struct {
  29. AppID string `json:"appid"` //所需跳转到的小程序appid(该小程序appid必须与发模板消息的公众号是绑定关联关系)
  30. PagePath string `json:"pagepath"` //所需跳转到小程序的具体页面路径,支持带参数,(示例index?foo=bar)
  31. } `json:"miniprogram"` //可选,跳转至小程序地址
  32. }
  33. //DataItem 模版内某个 .DATA 的值
  34. type DataItem struct {
  35. Value string `json:"value"`
  36. Color string `json:"color,omitempty"`
  37. }
  38. type resTemplateSend struct {
  39. util.CommonError
  40. MsgID int64 `json:"msgid"`
  41. }
  42. //Send 发送模板消息
  43. func (tpl *Template) Send(msg *Message) (msgID int64, err error) {
  44. var accessToken string
  45. accessToken, err = tpl.GetAccessToken()
  46. if err != nil {
  47. return
  48. }
  49. uri := fmt.Sprintf("%s?access_token=%s", templateSendURL, accessToken)
  50. response, err := util.PostJSON(uri, msg)
  51. var result resTemplateSend
  52. err = json.Unmarshal(response, &result)
  53. if err != nil {
  54. return
  55. }
  56. if result.ErrCode != 0 {
  57. err = fmt.Errorf("template msg send error : errcode=%v , errmsg=%v", result.ErrCode, result.ErrMsg)
  58. return
  59. }
  60. msgID = result.MsgID
  61. return
  62. }