微信公眾號關注/取消關注回撥---.net core 5.0
[HttpPost, HttpGet]
public async Task WXSubscribeCallBack()
{
WeiXinXmlmessage wx = new WeiXinXmlmessage();
//校驗微信公眾號伺服器配置是否一致
if (HttpContext.Request.Method.ToLower() == "get")
{
string signature = HttpContext.Request.Query["signature"];
string timestamp = HttpContext.Request.Query["timestamp"];
string nonce = HttpContext.Request.Query["nonce"];
string echostr = HttpContext.Request.Query["echostr"];
string token = "hbzsb1234567";
List<string> list = new List<string>() { token, timestamp, nonce };
list.Sort();
string data = string.Join("", list);
byte[] temp1 = Encoding.UTF8.GetBytes(data);
SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider();
byte[] temp2 = sha.ComputeHash(temp1);
var hashCode = BitConverter.ToString(temp2);
hashCode = hashCode.Replace("-", "").ToLower();
if (hashCode == signature)
{
Response.WriteAsync(echostr);
}
}
else
{
HttpContext.Request.EnableBuffering();
Stream TmpBody = HttpContext.Request.Body;
string requestData = "";
TmpBody.Position = 0;
using (StreamReader streamReader = new StreamReader(TmpBody, Encoding.UTF8))
{
//讀取Body的時候,請儘量使用非同步方式讀取。ASP.NET Core預設是不支援同步讀取的,會丟擲異常
//解決方法 啟用 KestrelServerOptions 中 AllowSynchronousIO
requestData = streamReader.ReadToEndAsync().Result;
TmpBody.Position = 0;
}
XmlDocument xml = new XmlDocument();
xml.LoadXml(requestData);
wx.ToUserName = xml.SelectSingleNode("xml").SelectSingleNode("ToUserName").InnerText;
wx.FromUserName = xml.SelectSingleNode("xml").SelectSingleNode("FromUserName").InnerText;
wx.MsgType = xml.SelectSingleNode("xml").SelectSingleNode("MsgType").InnerText;
if (wx.MsgType.Trim() == "event")
{
//是否關注
wx.EventName = xml.SelectSingleNode("xml").SelectSingleNode("Event").InnerText;
if (wx.EventName.Trim() == "subscribe" || wx.EventName.Trim() == "unsubscribe")
{
//處理業務邏輯
var openid = wx.FromUserName;
}
//測試返回關注回覆
if (wx.EventName.Trim() == "subscribe")
{
var messageXml = sendTextMessage(wx, "關注成功!");
HttpContext.Response.WriteAsync(messageXml);
}
}
}
}
/// <summary>
/// 傳送文字訊息
/// </summary>
/// <param name="wx" />獲取的收發者資訊
/// <param name="content" />內容
/// <returns></returns>
private string sendTextMessage(WeiXinXmlmessage wx, string content)
{
string res = string.Format(Message_Text,
wx.FromUserName, wx.ToUserName, DateTime.Now.Ticks, content);
return res;
}
/// <summary>
/// 普通文字訊息
/// </summary>
private static string Message_Text
{
get
{
return @"<xml>
<ToUserName><![CDATA[{0}]]></ToUserName>
<FromUserName><![CDATA[{1}]]></FromUserName>
<CreateTime>{2}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[{3}]]></Content>
</xml>";
}
}