github.com/chanxuehong/wechat@v0.0.0-20230222024006-36f0325263cd/mp/message/template/send.go (about)

     1  package template
     2  
     3  import (
     4  	"encoding/json"
     5  
     6  	"github.com/chanxuehong/wechat/mp/core"
     7  )
     8  
     9  type TemplateMessage struct {
    10  	ToUser      string          `json:"touser"`                // 必须, 接受者OpenID
    11  	TemplateId  string          `json:"template_id"`           // 必须, 模版ID
    12  	URL         string          `json:"url,omitempty"`         // 可选, 用户点击后跳转的URL, 该URL必须处于开发者在公众平台网站中设置的域中
    13  	MiniProgram *MiniProgram    `json:"miniprogram,omitempty"` // 可选, 跳小程序所需数据,不需跳小程序可不用传该数据
    14  	Data        json.RawMessage `json:"data"`                  // 必须, 模板数据, JSON 格式的 []byte, 满足特定的模板需求
    15  }
    16  
    17  type TemplateMessage2 struct {
    18  	ToUser      string       `json:"touser"`                // 必须, 接受者OpenID
    19  	TemplateId  string       `json:"template_id"`           // 必须, 模版ID
    20  	URL         string       `json:"url,omitempty"`         // 可选, 用户点击后跳转的URL, 该URL必须处于开发者在公众平台网站中设置的域中
    21  	MiniProgram *MiniProgram `json:"miniprogram,omitempty"` // 可选, 跳小程序所需数据,不需跳小程序可不用传该数据
    22  	Data        interface{}  `json:"data"`                  // 必须, 模板数据, struct 或者 *struct, encoding/json.Marshal 后满足格式要求.
    23  }
    24  
    25  type MiniProgram struct {
    26  	AppId    string `json:"appid"`    // 必选; 所需跳转到的小程序appid(该小程序appid必须与发模板消息的公众号是绑定关联关系)
    27  	PagePath string `json:"pagepath"` // 必选; 所需跳转到的小程序appid(该小程序appid必须与发模板消息的公众号是绑定关联关系)
    28  }
    29  
    30  // 模版内某个 .DATA 的值
    31  type DataItem struct {
    32  	Value string `json:"value"`
    33  	Color string `json:"color,omitempty"`
    34  }
    35  
    36  // 发送模板消息, msg 是经过 encoding/json.Marshal 得到的结果符合微信消息格式的任何数据结构, 一般为 *TemplateMessage 类型.
    37  func Send(clt *core.Client, msg interface{}) (msgid int64, err error) {
    38  	const incompleteURL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="
    39  
    40  	var result struct {
    41  		core.Error
    42  		MsgId int64 `json:"msgid"`
    43  	}
    44  	if err = clt.PostJSON(incompleteURL, msg, &result); err != nil {
    45  		return
    46  	}
    47  	if result.ErrCode != core.ErrCodeOK {
    48  		err = &result.Error
    49  		return
    50  	}
    51  	msgid = result.MsgId
    52  	return
    53  }