/
message.go
71 lines (64 loc) · 2.01 KB
/
message.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
* Copyright (c) 2018. Brickman.
*/
package wechat
import (
"fmt"
"github.com/brickman-source/golang-utilities/errors"
"github.com/brickman-source/golang-utilities/http"
"github.com/brickman-source/golang-utilities/json"
"github.com/brickman-source/golang-utilities/log"
)
// SubscribeMessageData 订阅消息模板数据
type SubscribeMessageData map[string]SubscribeMessageDataValue
type SubscribeMessageDataValue struct {
Value string `json:"value"`
}
type SubscribeMessage struct {
ToUser string `json:"touser"`
TemplateID string `json:"template_id"`
Page string `json:"page,omitempty"`
Data SubscribeMessageData `json:"data"`
}
type SubscribeMessageResponse struct {
ErrCode int `json:"errcode"` // 错误码
ErrMSG string `json:"errmsg"` // 错误描述
}
func (wx *Wechat) SendSubscribeMessage(
appID, appSecret string,
templateID string,
toOpenID string,
page string,
data SubscribeMessageData,
) (*SubscribeMessageResponse, error) {
accessToken, err := wx.GetAccessTokenByClient(
appID, //wx.config.GetString("wechat.offiaccount.appId"),
appSecret, //wx.config.GetString("wechat.offiaccount.appSecret"),
)
if err != nil {
return nil, err
}
if accessToken == nil || accessToken.AccessToken == "" {
return nil, errors.New("GetAccessTokenBceByClient error")
}
sendMsgUrl := fmt.Sprintf(`https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=%s`, accessToken.AccessToken)
sendM := &SubscribeMessage{
ToUser: toOpenID,
TemplateID: templateID,
Page: page,
Data: data,
}
log.Infof("send subscribe msg: %s", sendMsgUrl)
log.Infof("send subscribe msg: %s", string(json.ShouldMarshal(sendM)))
httpData, err := http.PostData(sendMsgUrl, "application/json", json.ShouldMarshal(sendM))
log.Infof("send subscribe msg: %v", string(httpData))
if err != nil {
return nil, err
}
ret := &SubscribeMessageResponse{}
err = json.Unmarshal(httpData, ret)
if err != nil {
return nil, err
}
return ret, nil
}