微信小程序訂閱消息推送
開發配置配置
服務器配置
- 在小程序后台開啟消息推送(開發-開發設置-消息推送)文檔地址
- 這里需要服務提供驗證簽名的接口 將下面代碼發布到服務器並使用80或443端口訪問(我在使用其他端口時出現問題 80和443端口正常) 例如:https://www.baidu.com/api/wx/CheckWxSignature
/// <summary> /// 接口認證 /// </summary> /// <param name="echostr">回傳參數</param> /// <param name="signature">加密字段</param> /// <param name="timestamp">時間搓</param> /// <param name="nonce">隨機字符串</param> /// <returns></returns> [HttpGet,Route("api/wx/CheckWxSignature")] public IActionResult CheckWxSignature(string echostr, string signature, string timestamp, string nonce) { string token = "test"; if (!CheckSignature(token, signature, timestamp, nonce)) { return Ok("error"); } return Ok(echostr); } /// <summary> /// 驗證微信簽名 /// </summary> private bool CheckSignature(string token, string signature, string timestamp, string nonce) { string[] ArrTmp = { token, timestamp, nonce }; Array.Sort(ArrTmp); string tmpStr = string.Join("", ArrTmp); var data = SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(tmpStr)); var sb = new StringBuilder(); foreach (var t in data) { sb.Append(t.ToString("X2")); } tmpStr = sb.ToString(); tmpStr = tmpStr.ToLower(); if (tmpStr == signature) { return true; } else { return false; } }
小程序配置
小程序訂閱消息在每次發送消息前需要詢問用戶是否授權,授權成功后才能調用。每次授權后只有一次調用權限。
服務器配置成功后還需要在小程序授權后才能調用,一次性授權的意思是授權后只有一次
的調用權限.
wx.requestSubscribeMessage({
tmplIds: ['template_id'], // 此處可填寫多個模板 ID,但低版本微信不兼容只能授權一個
success (res) {
console.log('已授權接收訂閱消息')
}
})
開發者工具目前無法調用接口,只能在真機上運行
服務端消息發送
WeChatHelper.cs
public class WeChatHelper{
private static string WXAppId="";
private static string WXAppSecret="";
/// <summary>
/// 對頁面是否要用授權
/// </summary>
/// <param name="Appid">微信應用id</param>
/// <param name="redirect_uri">回調頁面</param>
/// <param name="scope">應用授權作用域snsapi_base(不彈出授權頁面,直接跳轉,只能獲取用戶openid),snsapi_userinfo (彈出授權頁面,可通過openid拿到昵稱、性別、所在地。並且,即使在未關注的情況下,只要用戶授權,也能獲取其信息)</param>
/// <returns>授權地址</returns>
public static string GetToken()
{
string url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", WXAppId, WXAppSecret);
string ReText = HttpClients.WebRequestPostOrGet(url, "");//post/get方法獲取信息
try
{
var obj = JsonConvert.DeserializeObject<Tokens>(ReText);
return obj.access_token;
}
catch (Exception ex)
{
return "";
}
}
public static object SendMessage(string token)
{
var access_token = token;
string url = $"https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={access_token}";
var dic = new Dictionary<string,object>();//組裝模板內容
dic.Add("character_string8",new { value = "2020071212121351" });//訂單編號
dic.Add("amount5",new { value= "20.00" });//訂單金額
dic.Add("time10", new { value = "2020-07-13 12:00:00" });//訂單時間
dic.Add("name3", new { value = "商戶名稱" });//商戶名稱
dic.Add("phrase1", new { value = "已支付" });//訂單狀態
var data = new MessageData()
{
touser = "微信openid",
template_id = "模板id",
page = "需要跳轉的小程序地址 不跳轉就不填寫",
data = dic
};
string ReText = HttpClients.WebRequestPostOrGet(url, JsonConvert.SerializeObject(data));//post/get方法獲取信息
return ReText;
}
}
HttpClients.cs
public class HttpClients{
//發起Http請求
public static string HttpPost(string url, Stream data, IDictionary<object, string> headers = null)
{
System.Net.WebRequest request = HttpWebRequest.Create(url);
request.Method = "POST";
if (data != null)
request.ContentLength = data.Length;
//request.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
if (headers != null)
{
foreach (var v in headers)
{
if (v.Key is HttpRequestHeader)
request.Headers[(HttpRequestHeader)v.Key] = v.Value;
else
request.Headers[v.Key.ToString()] = v.Value;
}
}
HttpWebResponse response = null;
try
{
// Get the response.
response = (HttpWebResponse)request.GetResponse();
// Display the status.
Console.WriteLine(response.StatusDescription);
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Cleanup the streams and the response.
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}
catch (Exception e)
{
return e.Message;
}
}
}
template_Id在小程序后台進行設置(功能-訂閱消息-我的模板中進行添加)
這里代碼只做參考 具體實現請不要使用靜態類 並且access_token也需要緩存1-2小時 access_token過期時進行刷新