微信公共号服务器配置,微信公众帐号 服务器配置 代码

这个代码示例展示了如何处理微信公众号的POST请求,解析XML消息并根据消息类型(如文本、位置、图片)做出相应。它包含了验证微信签名、获取百度地图信息以及回复消息的逻辑。此外,还实现了错误日志记录和HTTP POST请求的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

usingSystem;

usingSystem.Collections;

usingSystem.Configuration;

usingSystem.Data;

usingSystem.Linq;

usingSystem.Web;

usingSystem.Web.Security;

usingSystem.Web.UI;

usingSystem.Web.UI.HtmlControls;

usingSystem.Web.UI.WebControls;

usingSystem.Web.UI.WebControls.WebParts;

usingSystem.Xml.Linq;

usingSystem.Xml;

usingSystem.IO;

usingSystem.Text;

usingSystem.Collections.Generic;

usingSystem.Net;

namespaceOAuth2Demo

{

publicpartialclassWebForm1 : System.Web.UI.Page

{

conststringToken ="token";//与那边填写的token一致

protectedvoidPage_Load(objectsender, EventArgs e)

{

stringpostStr ="";

if(Request.HttpMethod.ToLower() =="post")

{

Stream s = System.Web.HttpContext.Current.Request.InputStream;

byte[] b =newbyte[s.Length];

s.Read(b, 0, (int)s.Length);

postStr = Encoding.UTF8.GetString(b);

if(!string.IsNullOrEmpty(postStr))

{

//封装请求类

XmlDocument doc = newXmlDocument();

doc.LoadXml(postStr);

XmlElement rootElement = doc.DocumentElement;

XmlNode MsgType = rootElement.SelectSingleNode("MsgType");

RequestXML requestXML = newRequestXML();

requestXML.ToUserName = rootElement.SelectSingleNode("ToUserName").InnerText;

requestXML.FromUserName = rootElement.SelectSingleNode("FromUserName").InnerText;

requestXML.CreateTime = rootElement.SelectSingleNode("CreateTime").InnerText;

requestXML.MsgType = MsgType.InnerText;

if(requestXML.MsgType =="text")

{

requestXML.Content = rootElement.SelectSingleNode("Content").InnerText;

}

elseif(requestXML.MsgType =="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;

}

elseif(requestXML.MsgType =="p_w_picpath")

{

requestXML.PicUrl = rootElement.SelectSingleNode("PicUrl").InnerText;

}

//回复消息

ResponseMsg(requestXML);

}

}

else

{

Valid();

}

}

/// 

/// 验证微信签名

/// 

/// * 将token、timestamp、nonce三个参数进行字典序排序

/// * 将三个参数字符串拼接成一个字符串进行sha1加密

/// * 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信。

/// 

privateboolCheckSignature()

{

stringsignature = Request.QueryString["signature"];

stringtimestamp = Request.QueryString["timestamp"];

stringnonce = Request.QueryString["nonce"];

string[] ArrTmp = { Token, timestamp, nonce };

Array.Sort(ArrTmp);     //字典排序

stringtmpStr =string.Join("", ArrTmp);

tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");

tmpStr = tmpStr.ToLower();

if(tmpStr == signature)

{

returntrue;

}

else

{

returnfalse;

}

}

privatevoidValid()

{

stringechoStr = Request.QueryString["echoStr"];

if(CheckSignature())

{

if(!string.IsNullOrEmpty(echoStr))

{

Response.Write(echoStr);

Response.End();

}

}

}

/// 

/// 回复消息(微信信息返回)

/// 

/// 

privatevoidResponseMsg(RequestXML requestXML)

{

try

{

stringresxml ="";

if(requestXML.MsgType =="text")

{

resxml = ""+ ConvertDateTimeInt(DateTime.Now) +"0";

}

elseif(requestXML.MsgType =="location")

{

stringcity = GetMapInfo(requestXML.Location_X, requestXML.Location_Y);

if(city =="0")

{

resxml = ""+ ConvertDateTimeInt(DateTime.Now) +"0";

}

else

{

resxml = ""+ ConvertDateTimeInt(DateTime.Now) +"0";

}

}

elseif(requestXML.MsgType =="p_w_picpath")

{

//返回10以内条

intsize = 10;

resxml = ""+ ConvertDateTimeInt(DateTime.Now) +""+ size +"";

List list =newList();

//假如有20条查询的返回结果

for(inti = 0; i 

{

list.Add("1");

}

string[] piclist =newstring[] {"/Abstract_Pencil_Scribble_Background_Vector_main.jpg","/balloon_tree.jpg","/bloom.jpg","/colorful_flowers.jpg","/colorful_summer_flower.jpg","/fall.jpg","/fall_tree.jpg","/growing_flowers.jpg","/shoes_illustration.jpg","/splashed_tree.jpg"};

for(inti = 0; i 

{

resxml += "";

}

resxml += "1";

}

WriteTxt(resxml);

Response.Write(resxml);

}

catch(Exception ex)

{

WriteTxt("异常:"+ex.Message+"Struck:"+ex.StackTrace.ToString());

}

}

/// 

/// unix时间转换为datetime

/// 

/// 

/// 

privateDateTime UnixTimeToTime(stringtimeStamp)

{

DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(newDateTime(1970, 1, 1));

longlTime =long.Parse(timeStamp +"0000000");

TimeSpan toNow = newTimeSpan(lTime);

returndtStart.Add(toNow);

}

/// 

/// datetime转换为unixtime

/// 

/// 

/// 

privateintConvertDateTimeInt(System.DateTime time)

{

System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(newSystem.DateTime(1970, 1, 1));

return(int)(time - startTime).TotalSeconds;

}

/// 

/// 记录bug,以便调试

/// 

/// 

publicboolWriteTxt(stringstr)

{

try

{

FileStream fs = newFileStream(Server.MapPath("/bugLog.txt"), FileMode.Append);

StreamWriter sw = newStreamWriter(fs);

//开始写入

sw.WriteLine(str);

//清空缓冲区

sw.Flush();

//关闭流

sw.Close();

fs.Close();

}

catch(Exception)

{

returnfalse;

}

returntrue;

}

/// 

/// 调用百度地图,返回坐标信息

/// 

/// 经度

/// 纬度

/// 

publicstringGetMapInfo(stringx,stringy)

{

try

{

stringres =string.Empty;

stringparame =string.Empty;

stringurl ="http://maps.googleapis.com/maps/api/geocode/xml";

parame = "latlng="+ x +","+ y +"&language=zh-CN&sensor=false";//此key为个人申请

res = webRequestPost(url, parame);

XmlDocument doc = newXmlDocument();

doc.LoadXml(res);

XmlElement rootElement = doc.DocumentElement;

stringStatus = rootElement.SelectSingleNode("status").InnerText;

if(Status =="OK")

{

//仅获取城市

XmlNodeList xmlResults = rootElement.SelectSingleNode("/GeocodeResponse").ChildNodes;

for(inti = 0; i 

{

XmlNode childNode = xmlResults[i];

if(childNode.Name =="status")

{

continue;

}

stringcity ="0";

for(intw = 0; w 

{

for(intq = 0; q 

{

XmlNode childeTwo = childNode.ChildNodes[w].ChildNodes[q];

if(childeTwo.Name =="long_name")

{

city = childeTwo.InnerText;

}

elseif(childeTwo.InnerText =="locality")

{

returncity;

}

}

}

returncity;

}

}

}

catch(Exception ex)

{

WriteTxt("map异常:"+ ex.Message.ToString() +"Struck:"+ ex.StackTrace.ToString());

return"0";

}

return"0";

}

/// 

/// Post 提交调用抓取

/// 

/// 提交地址

/// 参数

/// string

publicstringwebRequestPost(stringurl,stringparam)

{

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())

{

//在这里对接收到的页面内容进行处理

Stream strm = wr.GetResponseStream();

StreamReader sr = newStreamReader(strm, System.Text.Encoding.UTF8);

stringline;

System.Text.StringBuilder sb = newSystem.Text.StringBuilder();

while((line = sr.ReadLine()) !=null)

{

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

}

sr.Close();

strm.Close();

returnsb.ToString();

}

}

}

//微信请求类

publicclassRequestXML

{

privatestringtoUserName;

/// 

/// 消息接收方微信号,一般为公众平台账号微信号

/// 

publicstringToUserName

{

get{returntoUserName; }

set{ toUserName = value; }

}

privatestringfromUserName;

/// 

/// 消息发送方微信号

/// 

publicstringFromUserName

{

get{returnfromUserName; }

set{ fromUserName = value; }

}

privatestringcreateTime;

/// 

/// 创建时间

/// 

publicstringCreateTime

{

get{returncreateTime; }

set{ createTime = value; }

}

privatestringmsgType;

/// 

/// 信息类型 地理位置:location,文本消息:text,消息类型:p_w_picpath

/// 

publicstringMsgType

{

get{returnmsgType; }

set{ msgType = value; }

}

privatestringcontent;

/// 

/// 信息内容

/// 

publicstringContent

{

get{returncontent; }

set{ content = value; }

}

privatestringlocation_X;

/// 

/// 地理位置纬度

/// 

publicstringLocation_X

{

get{returnlocation_X; }

set{ location_X = value; }

}

privatestringlocation_Y;

/// 

/// 地理位置经度

/// 

publicstringLocation_Y

{

get{returnlocation_Y; }

set{ location_Y = value; }

}

privatestringscale;

/// 

/// 地图缩放大小

/// 

publicstringScale

{

get{returnscale; }

set{ scale = value; }

}

privatestringlabel;

/// 

/// 地理位置信息

/// 

publicstringLabel

{

get{returnlabel; }

set{ label = value; }

}

privatestringpicUrl;

/// 

/// 图片链接,开发者可以用HTTP GET获取

/// 

publicstringPicUrl

{

get{returnpicUrl; }

set{ picUrl = value; }

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值