微信公眾平台開發的核心在於「被動回覆」與「主動推送」兩類訊息交互。本文系統整理 ASP.NET (C#) 端接收 POST 請求、判斷加密模式、解密訊息、構建回覆 XML 的完整流程,並提供可直接落地的封裝類別。
微信伺服器以 POST 將 XML 訊息推送至配置的 URL,參數包含 msg_signature、timestamp、nonce。Controller Action 需直接讀取 Request.InputStream:
[HttpPost]
public ActionResult WeChat(WeChatMsgRequestModel model) {
using (var stream = Request.InputStream) {
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, (int)stream.Length);
string postXml = Encoding.UTF8.GetString(bytes);
return HandleMessage(postXml, model);
}
}
公眾平台後台可選「明文模式」「相容模式」「安全模式」。安全模式下訊息體為 Encrypt 節點,需解密後得到明文 XML。官方提供 WXBizMsgCrypt.cs、Cryptography.cs 兩檔,建議再封裝為 WeChatSecurityHelper:
public class WeChatSecurityHelper {
private const string Token = "YourToken";
private const string AppId = "YourAppId";
private const string AESKey = "YourEncodingAESKey";
private readonly WXBizMsgCrypt _wxcpt = new WXBizMsgCrypt(Token, AESKey, AppId);
public string DecryptMsg(string msgSignature, string timestamp, string nonce, string encryptXml) {
string decryptMsg = "";
int ret = _wxcpt.DecryptMsg(msgSignature, timestamp, nonce, encryptXml, ref decryptMsg);
if (ret != 0) throw new Exception($"解密失敗, code={ret}");
return decryptMsg;
}
public string EncryptMsg(string replyXml, string timestamp, string nonce) {
string encryptMsg = "";
int ret = _wxcpt.EncryptMsg(replyXml, timestamp, nonce, ref encryptMsg);
if (ret != 0) throw new Exception($"加密失敗, code={ret}");
return encryptMsg;
}
}
解密後的 XML 含 MsgType 區分文字、圖片、語音、事件等。以文字訊息為例,回覆 XML 模板:
<xml>
<ToUserName><![CDATA[{0}]]></ToUserName>
<FromUserName><![CDATA[{1}]]></FromUserName>
<CreateTime>{2}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[{3}]]></Content>
</xml>
程式碼組裝:
string replyXml = string.Format(ReplyTemplate.Text,
fromUser, toUser, DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
string.IsNullOrEmpty(replyText) ? "收到,謝謝!" : replyText);
圖片訊息同理,只需填入 MediaId。
private ActionResult HandleMessage(string postXml, WeChatMsgRequestModel model) {
// 1. 依模式決定是否解密
string plainXml = model.EncryptType == "aes"
? _securityHelper.DecryptMsg(model.MsgSignature, model.Timestamp, model.Nonce, postXml)
: postXml;
// 2. 反序列化
var msg = XmlHelper.Deserialize<WeChatRequestMessage>(plainXml);
// 3. 業務邏輯:這裡示範簡單 Echo
string replyText = $"您說:{msg.Content}";
string replyXml = BuildTextReply(msg.FromUserName, msg.ToUserName, replyText);
// 4. 依模式決定是否加密
string finalXml = model.EncryptType == "aes"
? _securityHelper.EncryptMsg(replyXml, model.Timestamp, model.Nonce)
: replyXml;
return Content(finalXml, "application/xml");
}
掌握上述流程,即可在 ASP.NET 中穩健接入微信公眾平台訊息通道,為後續業務邏輯奠定基礎。