小程序订阅消息官方配置教程文档链接:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/subscribe-message.html
wxml页面代码:
<view>
<button class="btn" type="primary" bindtap="subscribe">订阅消息</button>
</view>
js页面代码:
subscribe: function(e) {
wx.requestSubscribeMessage({
tmplIds: ['XXXXXXXXXXXXXXXXXXX'],//模板id
success:function(res){
wx.request({
url: 'xxxxxxxxxxxxxxxxxxxxxxxxx',//接口地址
data: { },
success: function(res) {
console.log("订阅成功");
}
});
}
})
}
后端代码(C#)(这里我以“天气提醒”模板为示例,在接口中写了一个方法如下):
#region 发送订阅消息===============================
/// <summary>
/// 发送订阅消息
/// <param name="touser">用户openid</param>
/// <param name="city">城市</param>
/// <param name="location">地址</param>
/// <param name="weather">天气</param>
/// <returns>返回值{"errcode":0,"errmsg":"ok"}</returns>
/// </summary>
public void Send_Subscribe(string touser, string city, string location, string weather)
{
string access_token = "Access_Token";//Access_Token
string _url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + access_token;
string timenow = Convert.ToDateTime(DateTime.Now).ToString("yyyy年MM月dd日");
//json参数
string jsonParam = "{\"touser\": \"" + touser + "\",\"template_id\": \"XXXXXXXXXXXXXX\",\"page\": \"pages/weather/weather\",\"data\": {\"date1\": { \"value\": \"" + timenow + "\"},\"phrase2\": {\"value\": \"" + city + "\"},\"phrase3\": {\"value\": \"" + location + "\"},\"character_string4\": {\"value\": \"" + weather + "\"}}}";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_url);
request.Method = "POST";
request.Timeout = 5000;
request.ContentType = "application/json;charset=UTF-8";
byte[] byteData = Encoding.UTF8.GetBytes(jsonParam);
int length = byteData.Length;
request.ContentLength = length;
using (Stream writer = request.GetRequestStream())
{
writer.Write(byteData, 0, length);
writer.Close();
}
string jsonStrings = string.Empty;
using (HttpWebResponse responses = (HttpWebResponse)request.GetResponse())
{
using (Stream streams = responses.GetResponseStream())
{
using (StreamReader readers = new StreamReader(streams, System.Text.Encoding.UTF8))
{
jsonStrings = readers.ReadToEnd();
responses.Close();
streams.Close();
readers.Close();
}
}
}
//{"errcode":0,"errmsg":"ok"}
JObject jo = (JObject)JsonConvert.DeserializeObject(jsonStrings);
string errcode = jo["errcode"].ToString();
string errmsg = jo["errmsg"].ToString();
//写日志
LogUtils.Write(errcode + "," + errmsg);
}
#endregion
示例: