主頁 > 知識(shí)庫 > .net實(shí)現(xiàn)微信公眾賬號(hào)接口開發(fā)實(shí)例代碼

.net實(shí)現(xiàn)微信公眾賬號(hào)接口開發(fā)實(shí)例代碼

熱門標(biāo)簽:電銷機(jī)器人 數(shù)據(jù) 地圖標(biāo)注多少錢一張 ai電銷機(jī)器人對(duì)貸款有幫助嗎 怎樣給陜西地圖標(biāo)注顏色 400電話辦理信任翰諾科技 廣州銷售外呼系統(tǒng)定制 福州人工智能電銷機(jī)器人加盟 宿遷智能外呼系統(tǒng)排名 云狐人工智能電話機(jī)器人

說起微信公眾帳號(hào),大家都不會(huì)陌生,使用這個(gè)平臺(tái)能給網(wǎng)站或系統(tǒng)增加一個(gè)新亮點(diǎn),直接進(jìn)入正題吧,在使用之前一定要仔細(xì)閱讀官方API文檔。
API文檔地址:http://mp.weixin.qq.com/wiki/index.php

使用.net實(shí)現(xiàn)的方法:
//微信接口地址 頁面代碼:

復(fù)制代碼 代碼如下:

weixin _wx = new weixin(); 
string postStr = ""; 
if (Request.HttpMethod.ToLower() == "post") 

Stream s = System.Web.HttpContext.Current.Request.InputStream; 
byte[] b = new byte[s.Length]; 
s.Read(b, 0, (int)s.Length); 
postStr = Encoding.UTF8.GetString(b); 
if (!string.IsNullOrEmpty(postStr)) //請(qǐng)求處理 

_wx.Handle(postStr);  


else

_wx.Auth(); 
}

具體處理類

復(fù)制代碼 代碼如下:

/// summary> 
/// 微信公眾平臺(tái)操作類 
/// /summary> 
public class weixin 

private string Token = "my_weixin_token"; //換成自己的token 
public void Auth() 

string echoStr = System.Web.HttpContext.Current.Request.QueryString["echoStr"]; 
if (CheckSignature()) //校驗(yàn)簽名是否正確 

if (!string.IsNullOrEmpty(echoStr)) 

System.Web.HttpContext.Current.Response.Write(echoStr); //返回原值表示校驗(yàn)成功 
System.Web.HttpContext.Current.Response.End(); 




 
public void Handle(string postStr) 

//封裝請(qǐng)求類 
XmlDocument doc = new XmlDocument(); 
doc.LoadXml(postStr); 
XmlElement rootElement = doc.DocumentElement; 
//MsgType 
XmlNode MsgType = rootElement.SelectSingleNode("MsgType"); 
//接收的值--->接收消息類(也稱為消息推送) 
RequestXML requestXML = new RequestXML(); 
requestXML.ToUserName = rootElement.SelectSingleNode("ToUserName").InnerText; 
requestXML.FromUserName = rootElement.SelectSingleNode("FromUserName").InnerText; 
requestXML.CreateTime = rootElement.SelectSingleNode("CreateTime").InnerText; 
requestXML.MsgType = MsgType.InnerText; 

//根據(jù)不同的類型進(jìn)行不同的處理 
switch (requestXML.MsgType) 

case "text": //文本消息 
requestXML.Content = rootElement.SelectSingleNode("Content").InnerText; 
break; 
case "image": //圖片 
requestXML.PicUrl = rootElement.SelectSingleNode("PicUrl").InnerText; 
break; 
case "location": //位置 
requestXML.Location_X = rootElement.SelectSingleNode("Location_X").InnerText; 
requestXML.Location_Y = rootElement.SelectSingleNode("Location_Y").InnerText; 
requestXML.Scale = rootElement.SelectSingleNode("Scale").InnerText; 
requestXML.Label = rootElement.SelectSingleNode("Label").InnerText; 
break; 
case "link": //鏈接 
break; 
case "event": //事件推送 支持V4.5+ 
break; 


//消息回復(fù) 
ResponseMsg(requestXML); 


 
/// summary> 
/// 驗(yàn)證微信簽名 
/// * 將token、timestamp、nonce三個(gè)參數(shù)進(jìn)行字典序排序 
/// * 將三個(gè)參數(shù)字符串拼接成一個(gè)字符串進(jìn)行sha1加密 
/// * 開發(fā)者獲得加密后的字符串可與signature對(duì)比,標(biāo)識(shí)該請(qǐng)求來源于微信。 
/// /summary> 
/// returns>/returns> 
private bool CheckSignature() 

string signature = System.Web.HttpContext.Current.Request.QueryString["signature"]; 
string timestamp = System.Web.HttpContext.Current.Request.QueryString["timestamp"]; 
string nonce = System.Web.HttpContext.Current.Request.QueryString["nonce"]; 
//加密/校驗(yàn)流程: 
//1. 將token、timestamp、nonce三個(gè)參數(shù)進(jìn)行字典序排序 
string[] ArrTmp = { Token, timestamp, nonce };  
Array.Sort(ArrTmp);//字典排序 
//2.將三個(gè)參數(shù)字符串拼接成一個(gè)字符串進(jìn)行sha1加密 
string tmpStr = string.Join("", ArrTmp); 
tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1"); 
tmpStr = tmpStr.ToLower(); 
//3.開發(fā)者獲得加密后的字符串可與signature對(duì)比,標(biāo)識(shí)該請(qǐng)求來源于微信。 
if (tmpStr == signature) 

return true; 

else

return false; 



/// summary> 
/// 消息回復(fù)(微信信息返回) 
/// /summary> 
/// param name="requestXML">The request XML./param> 
private void ResponseMsg(RequestXML requestXML) 

try

string resxml = ""; 
//主要是調(diào)用數(shù)據(jù)庫進(jìn)行關(guān)鍵詞匹配自動(dòng)回復(fù)內(nèi)容,可以根據(jù)自己的業(yè)務(wù)情況編寫。 
//1.通常有,沒有匹配任何指令時(shí),返回幫助信息 
AutoResponse mi = new AutoResponse(requestXML.Content, requestXML.FromUserName); 

switch (requestXML.MsgType) 

case "text": 
//在這里執(zhí)行一系列操作,從而實(shí)現(xiàn)自動(dòng)回復(fù)內(nèi)容.  
string _reMsg = mi.GetReMsg(); 
if (mi.msgType == 1) 

resxml = "xml>ToUserName>![CDATA[" + requestXML.FromUserName + "]]>/ToUserName>FromUserName>![CDATA[" + requestXML.ToUserName + "]]>/FromUserName>CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "/CreateTime>MsgType>![CDATA[news]]>/MsgType>Content>![CDATA[]]>/Content>ArticleCount>2/ArticleCount>Articles>"; 
resxml += mi.GetRePic(requestXML.FromUserName); 
resxml += "/Articles>FuncFlag>1/FuncFlag>/xml>"; 

else

resxml = "xml>ToUserName>![CDATA[" + requestXML.FromUserName + "]]>/ToUserName>FromUserName>![CDATA[" + requestXML.ToUserName + "]]>/FromUserName>CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "/CreateTime>MsgType>![CDATA[text]]>/MsgType>Content>![CDATA[" + _reMsg + "]]>/Content>FuncFlag>1/FuncFlag>/xml>"; 

break; 
case "location": 
string city = GetMapInfo(requestXML.Location_X, requestXML.Location_Y); 
if (city == "0") 

resxml = "xml>ToUserName>![CDATA[" + requestXML.FromUserName + "]]>/ToUserName>FromUserName>![CDATA[" + requestXML.ToUserName + "]]>/FromUserName>CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "/CreateTime>MsgType>![CDATA[text]]>/MsgType>Content>![CDATA[好啦,我們知道您的位置啦。您可以:" + mi.GetDefault() + "]]>/Content>FuncFlag>1/FuncFlag>/xml>"; 

else

resxml = "xml>ToUserName>![CDATA[" + requestXML.FromUserName + "]]>/ToUserName>FromUserName>![CDATA[" + requestXML.ToUserName + "]]>/FromUserName>CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "/CreateTime>MsgType>![CDATA[text]]>/MsgType>Content>![CDATA[好啦,我們知道您的位置啦。您可以:" + mi.GetDefault() + "]]>/Content>FuncFlag>1/FuncFlag>/xml>"; 

break; 
case "image": 
//圖文混合的消息 具體格式請(qǐng)見官方API“回復(fù)圖文消息”  
break; 


System.Web.HttpContext.Current.Response.Write(resxml); 
WriteToDB(requestXML, resxml, mi.pid); 

catch (Exception ex) 

//WriteTxt("異常:" + ex.Message + "Struck:" + ex.StackTrace.ToString()); 
//wx_logs.MyInsert("異常:" + ex.Message + "Struck:" + ex.StackTrace.ToString()); 



 
/// summary> 
/// unix時(shí)間轉(zhuǎn)換為datetime 
/// /summary> 
/// param name="timeStamp">/param> 
/// returns>/returns> 
private DateTime UnixTimeToTime(string timeStamp) 

DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); 
long lTime = long.Parse(timeStamp + "0000000"); 
TimeSpan toNow = new TimeSpan(lTime); 
return dtStart.Add(toNow); 


 
/// summary> 
/// datetime轉(zhuǎn)換為unixtime 
/// /summary> 
/// param name="time">/param> 
/// returns>/returns> 
private int ConvertDateTimeInt(System.DateTime time) 

System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); 
return (int)(time - startTime).TotalSeconds; 


 
/// summary> 
/// 調(diào)用百度地圖,返回坐標(biāo)信息 
/// /summary> 
/// param name="y">經(jīng)度/param> 
/// param name="x">緯度/param> 
/// returns>/returns> 
public string GetMapInfo(string x, string y) 

try

string res = string.Empty; 
string parame = string.Empty; 
string url = "http://maps.googleapis.com/maps/api/geocode/xml"; 

parame = "latlng=" + x + "," + y + "language=zh-CNsensor=false";//此key為個(gè)人申請(qǐng) 
res = webRequestPost(url, parame); 

XmlDocument doc = new XmlDocument(); 
doc.LoadXml(res); 

XmlElement rootElement = doc.DocumentElement; 
string Status = rootElement.SelectSingleNode("status").InnerText; 

if (Status == "OK") 

//僅獲取城市 
XmlNodeList xmlResults = rootElement.SelectSingleNode("/GeocodeResponse").ChildNodes; 
for (int i = 0; i xmlResults.Count; i++) 

XmlNode childNode = xmlResults[i]; 
if (childNode.Name == "status") { 
continue; 

string city = "0"; 
for (int w = 0; w childNode.ChildNodes.Count; w++) 

for (int q = 0; q childNode.ChildNodes[w].ChildNodes.Count; q++) 

XmlNode childeTwo = childNode.ChildNodes[w].ChildNodes[q]; 
if (childeTwo.Name == "long_name") 

city = childeTwo.InnerText; 

else if (childeTwo.InnerText == "locality") 

return city; 



return city; 



catch (Exception ex) 

//WriteTxt("map異常:" + ex.Message.ToString() + "Struck:" + ex.StackTrace.ToString()); 
return "0"; 
}  
return "0"; 


 
/// summary> 
/// Post 提交調(diào)用抓取 
/// /summary> 
/// param name="url">提交地址/param> 
/// param name="param">參數(shù)/param> 
/// returns>string/returns> 
public string webRequestPost(string url, string param) 

byte[] bs = System.Text.Encoding.UTF8.GetBytes(param); 
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url + "?" + param); 
req.Method = "Post"; 
req.Timeout = 120 * 1000; 
req.ContentType = "application/x-www-form-urlencoded;"; 
req.ContentLength = bs.Length; 

using (Stream reqStream = req.GetRequestStream()) 

reqStream.Write(bs, 0, bs.Length); 
reqStream.Flush(); 


using (WebResponse wr = req.GetResponse()) 

//在這里對(duì)接收到的頁面內(nèi)容進(jìn)行處理 
Stream strm = wr.GetResponseStream(); 
StreamReader sr = new StreamReader(strm, System.Text.Encoding.UTF8); 

string line; 
System.Text.StringBuilder sb = new System.Text.StringBuilder(); 
while ((line = sr.ReadLine()) != null) 

sb.Append(line + System.Environment.NewLine); 

sr.Close(); 
strm.Close(); 
return sb.ToString(); 



/// summary> 
/// 將本次交互信息保存至數(shù)據(jù)庫中 
/// /summary> 
/// param name="requestXML">/param> 
/// param name="_xml">/param> 
/// param name="_pid">/param> 
private void WriteToDB(RequestXML requestXML, string _xml, int _pid) 

WeiXinMsg wx = new WeiXinMsg(); 
wx.FromUserName = requestXML.FromUserName; 
wx.ToUserName = requestXML.ToUserName; 
wx.MsgType = requestXML.MsgType; 
wx.Msg = requestXML.Content; 
wx.Creatime = requestXML.CreateTime; 
wx.Location_X = requestXML.Location_X; 
wx.Location_Y = requestXML.Location_Y; 
wx.Label = requestXML.Label; 
wx.Scale = requestXML.Scale; 
wx.PicUrl = requestXML.PicUrl; 
wx.reply = _xml; 
wx.pid = _pid; 
try

wx.Add(); 

catch (Exception ex) 

//wx_logs.MyInsert(ex.Message); 
//ex.message; 


}

響應(yīng)類MODEL

復(fù)制代碼 代碼如下:

#region 微信請(qǐng)求類 RequestXML 
/// summary> 
/// 微信請(qǐng)求類 
/// /summary> 
public class RequestXML 

private string toUserName = ""; 
/// summary> 
/// 消息接收方微信號(hào),一般為公眾平臺(tái)賬號(hào)微信號(hào) 
/// /summary> 
public string ToUserName 

get { return toUserName; } 
set { toUserName = value; } 


private string fromUserName = ""; 
/// summary> 
/// 消息發(fā)送方微信號(hào) 
/// /summary> 
public string FromUserName 

get { return fromUserName; } 
set { fromUserName = value; } 


private string createTime = ""; 
/// summary> 
/// 創(chuàng)建時(shí)間 
/// /summary> 
public string CreateTime 

get { return createTime; } 
set { createTime = value; } 


private string msgType = ""; 
/// summary> 
/// 信息類型 地理位置:location,文本消息:text,消息類型:image 
/// /summary> 
public string MsgType 

get { return msgType; } 
set { msgType = value; } 


private string content = ""; 
/// summary> 
/// 信息內(nèi)容 
/// /summary> 
public string Content 

get { return content; } 
set { content = value; } 


private string location_X = ""; 
/// summary> 
/// 地理位置緯度 
/// /summary> 
public string Location_X 

get { return location_X; } 
set { location_X = value; } 


private string location_Y = ""; 
/// summary> 
/// 地理位置經(jīng)度 
/// /summary> 
public string Location_Y 

get { return location_Y; } 
set { location_Y = value; } 


private string scale = ""; 
/// summary> 
/// 地圖縮放大小 
/// /summary> 
public string Scale 

get { return scale; } 
set { scale = value; } 


private string label = ""; 
/// summary> 
/// 地理位置信息 
/// /summary> 
public string Label 

get { return label; } 
set { label = value; } 


private string picUrl = ""; 
/// summary> 
/// 圖片鏈接,開發(fā)者可以用HTTP GET獲取 
/// /summary> 
public string PicUrl 

get { return picUrl; } 
set { picUrl = value; } 


#endregion

您可能感興趣的文章:
  • java微信開發(fā)API第一步 服務(wù)器接入
  • C#微信開發(fā)(服務(wù)器配置)
  • 微信JS接口匯總及使用詳解
  • PHP對(duì)接微信公眾平臺(tái)消息接口開發(fā)流程教程
  • 微信API接口大全
  • 微信公眾號(hào)支付(二)實(shí)現(xiàn)統(tǒng)一下單接口
  • ASP 微信公共平臺(tái)接口實(shí)現(xiàn)代碼
  • c#使用微信接口開發(fā)微信門戶應(yīng)用
  • 微信公眾平臺(tái)開發(fā)接口PHP SDK完整版
  • 微信公眾平臺(tái)開發(fā)-微信服務(wù)器IP接口實(shí)例(含源碼)

標(biāo)簽:綿陽 宜春 延安 黃南 焦作 大興安嶺 新疆 曲靖

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《.net實(shí)現(xiàn)微信公眾賬號(hào)接口開發(fā)實(shí)例代碼》,本文關(guān)鍵詞  .net,實(shí)現(xiàn),微信,公眾,賬號(hào),;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《.net實(shí)現(xiàn)微信公眾賬號(hào)接口開發(fā)實(shí)例代碼》相關(guān)的同類信息!
  • 本頁收集關(guān)于.net實(shí)現(xiàn)微信公眾賬號(hào)接口開發(fā)實(shí)例代碼的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章