消息能力是小程序能力中的重要组成,我们为开发者提供了订阅消息能力,以便实现服务的闭环和更优的体验。
- 订阅消息推送位置:服务通知
- 订阅消息下发条件:用户自主订阅
- 订阅消息卡片跳转能力:点击查看详情可跳转至该小程序的页面
官方文档:小程序订阅消息 | 微信开放文档 (qq.com)
本文使用.NET Core实现
微信小程序端编写如下代码:
-
申请通知模板消息
官网地址:小程序 (qq.com)
登录以后,在如下位置选择模板消息
先从公共模板消息中选择模板
如果对模板消息不满足当前需求的用户,可以申请属于自己的模板消息
随便点击一个提供的模板,然后根据需要填写需要展示的信息数据(需要注意,一个app一个月仅可申请5次)
-
获取微信授权
下发通知消息,需要用户授权,方能使用,这里简单编写一个授权通知的按钮
//index.wxml
<view>
<button bindtap="view1click"> 获取用户授权通知 </button>
</view>
//index.js
wx.requestSubscribeMessage({
tmplIds: ['HwFhxB3LxtxVFoM1yci1nH1YXL1rHL5wzhQW2q6In4c'],
success(res) {
console.log(res)
}
})
效果图如下
回传信息可参考微信文档说明:用户通知授权微信开放文档
-
下发通知
微信文档地址:下发通知 | 微信开放文档
下发通知需要获取access_token,代码如下:
/// <summary>
/// 获取微信AccessToken
/// </summary>
/// <returns></returns>
private async Task<string> GetAccessToken()
{
try
{
WeChatModels weChatModels = new WeChatModels();
weChatModels.appid = "";//微信openid
weChatModels.secret = ""; //微信secret
weChatModels.grant_type = "authorization_code";
string url = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={weChatModels.appid}&secret={weChatModels.secret}";
using (var client = new HttpClient())
{
var multipartFormDataContent = new MultipartFormDataContent();
var json = JsonConvert.SerializeObject(weChatModels);
multipartFormDataContent.Add(new StringContent(json), "WValue");
HttpResponseMessage response = await client.GetAsync(url);
string wxresp = await response.Content.ReadAsStringAsync();
var res = JsonConvert.DeserializeObject<dynamic>(await response.Content.ReadAsStringAsync());
if (res.access_token != "")
{
return res.access_token;
}
else
{
return "";
}
}
}
catch (Exception ex)
{
return "";
}
}
下发通知需要用户的openid
/// <summary>
/// 获取openid
/// </summary>
/// <param name="code"></param>
/// <returns></returns>
private async Task<string> GetOpenId(string code){
try
{
WeChatModels weChatModels = new WeChatModels();
weChatModels.appid = "";//微信appid
weChatModels.secret = "";//微信secret
weChatModels.js_code = code;
weChatModels.grant_type = "authorization_code";
string url = $"https://api.weixin.qq.com/sns/jscode2session?appid={weChatModels.appid}&" +
$"secret={weChatModels.secret}&js_code={weChatModels.js_code}&grant_type=authorization_code";
using (var client = new HttpClient())
{
var multipartFormDataContent = new MultipartFormDataContent();
var json = JsonConvert.SerializeObject(weChatModels);
multipartFormDataContent.Add(new StringContent(json), "WValue");
HttpResponseMessage response = await client.GetAsync(url);
string wxresp = await response.Content.ReadAsStringAsync();
var res = JsonConvert.DeserializeObject<dynamic>(await response.Content.ReadAsStringAsync());
if (res.session_key != "" && res.session_key != null)
{
return res.openid;
}
else
{
return "";
}
}
}
catch (Exception ex)
{
return null;
}
}
发送通知
/// <summary>
/// 发送通知
/// <param name="openId">用户的openid</param>
/// </summary>
public async Task SenMsg(string openId)
{
string mesUrl = $"https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={await GetAccessToken()}";
using (var client = new HttpClient())
{
DataModels dataModels = new DataModels();
dataModels.touser = openId;
dataModels.data.date1.value = DateTime.Now.ToString();
dataModels.data.thing2.value = "测试数据";
string json = JsonConvert.SerializeObject(dataModels);
HttpContent content = new StringContent(json);
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
HttpResponseMessage response = await client.PostAsync(mesUrl, content);
string wxresp = await response.Content.ReadAsStringAsync();
var res = JsonConvert.DeserializeObject<dynamic>(await response.Content.ReadAsStringAsync());
if (res.errcode == "0")
{
return "ok";
}
else
{
return res.errmsg;
}
}
}
这样就可以在微信上看到刚发送的消息,效果如下:
ps:
本文需要的model文件如下:
//微信用户class
public class WeChatModels
{
public string appid { get; set; }
public string secret { get; set; }
public string js_code { get; set; }
public string grant_type { get; set; } = "authorization_code";
}
//下发数据class
public class DataModels
{
public DataModels()
{
data = new DATAS();
}
public string touser { get; set; }
public string template_id { get; set; }
public string page { get; set; } = "pages/detal/detal";
public DATAS data { get; set; }
public string miniprogram_state { get; set; } = "developer";
public string lang { get; set; } = "zh_CN";
}
public class DATAS
{
public DATAS()
{
thing2 = new Values();
date1 = new Values();
}
public Values date1 { get; set; }
public Values thing2 { get; set; }
}
public class Values
{
public string value { get; set; }
}
至此,小程序获取AccessToken、获取用户openid、发送通知消息功能,全部完成。