golang小程序订阅消息发送
步骤
- 选择或者添加消息模板
- 获取小程序 token
- 调用api(目标用户openid,内容等)
示例代码
package wechat
import (
"bytes"
"encoding/json"
"errors"
"net/http"
"time"
)
const tmplId = "订阅模板id"
type MpgMsg struct {
Touser string `json:"touser"`
TemplateID string `json:"template_id"`
Page string `json:"page"`
MiniprogramState string `json:"miniprogram_state"`
Lang string `json:"lang"`
Data struct {
Thing1 struct {
Value string `json:"value"`
} `json:"thing1"`
Name2 struct {
Value string `json:"value"`
} `json:"name2"`
Date3 struct {
Value string `json:"value"`
} `json:"date3"`
} `json:"data"`
}
func MpgSendMsg(token string, openId string, thing string, name string, date string) error {
mod := MpgMsg{
Touser: openId,
TemplateID: tmplId,
Page: "访问路径",
MiniprogramState: "formal",
}
mod.Data.Thing1.Value = thing
mod.Data.Name2.Value = name
mod.Data.Date3.Value = date
bytesData, err := json.Marshal(mod)
if err != nil {
return err
}
body := bytes.NewReader(bytesData)
client := http.Client{Timeout: 30 * time.Second}
request, err := http.NewRequest("POST", "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="+token, body)
if err != nil {
return err
}
request.Header.Set("Content-Type", "application/json;charset=UTF-8")
resp, err := client.Do(request)
if err != nil {
return err
}
defer resp.Body.Close()
decoder := json.NewDecoder(resp.Body)
reply := &MpgMsgReply{}
err = decoder.Decode(reply)
if err != nil {
return err
}
err = reply.Stat()
if err != nil {
return err
}
return nil
}
type MpgMsgReply struct {
Openid string `json:"openid"`
SessionKey string `json:"session_key"`
Unioid string `json:"unioid"`
Errcode int `json:"errcode"`
Errmsg string `json:"errmsg"`
}
func (mpg *MpgMsgReply) Stat() error {
switch mpg.Errcode {
case 0:
return nil
case -1:
return errors.New("微信系统繁忙")
case 40003:
return errors.New("touser字段openid为空或者不正确")
case 40037:
return errors.New("订阅模板id为空不正确")
case 43101:
return errors.New("用户拒绝接受消息,如果用户之前曾经订阅过,则表示用户取消了订阅关系")
case 47003:
return errors.New("模板参数不准确,可能为空或者不满足规则,errmsg会提示具体是哪个字段出错")
case 41030:
return errors.New("page路径不正确,需要保证在现网版本小程序中存在,与app.json保持一致")
default:
return errors.New(mpg.Errmsg)
}
}
zxysilent
发表于 2021-07-06 16:26:50,最后修改于 2021-07-27 23:29:39
Comments