微信接口地址代码:
weixin_wx=newweixin();
stringpostStr="";
if(Request.HttpMethod.ToLower()=="post")
{
Streams=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))//请求处理
{
_wx.Handle(postStr);
}
}
else
{
_wx.Auth();
}
微信处理类:
publicclassweixin
{
privatestringToken="weixin_token";//换成自己的token
publicvoidAuth()
{
stringechoStr=System.Web.HttpContext.Current.Request.QueryString["echoStr"];
if(CheckSignature())
{
if(!string.IsNullOrEmpty(echoStr))
{
System.Web.HttpContext.Current.Response.Write(echoStr);
System.Web.HttpContext.Current.Response.End();
}
}
}
publicvoidHandle(stringpostStr)
{
//封装请求类
XmlDocumentdoc=newXmlDocument();
doc.LoadXml(postStr);
XmlElementrootElement=doc.DocumentElement;
XmlNodeMsgType=rootElement.SelectSingleNode("MsgType");
RequestXMLrequestXML=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=="image")
{
requestXML.PicUrl=rootElement.SelectSingleNode("PicUrl").InnerText;
}
//回复消息
ResponseMsg(requestXML);
}
///<summary>
///验证微信签名
///</summary>
///*将token、timestamp、nonce三个参数进行字典序排序
///*将三个参数字符串拼接成一个字符串进行sha1加密
///*开发者获得加密后的字符串可与signature对比,标识该请求来源于微信。
///<returns></returns>
privateboolCheckSignature()
{
stringsignature=System.Web.HttpContext.Current.Request.QueryString["signature"];
stringtimestamp=System.Web.HttpContext.Current.Request.QueryString["timestamp"];
stringnonce=System.Web.HttpContext.Current.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;
}
}
///<summary>
///回复消息(微信信息返回)
///</summary>
///<paramname="weixinXML"></param>
privatevoidResponseMsg(RequestXMLrequestXML)
{
try
{
stringresxml="";
mijiyami=newmijiya(requestXML.Content,requestXML.FromUserName);
if(requestXML.MsgType=="text")
{
//在这里执行一系列操作,从而实现自动回复内容.
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>";
}
}
elseif(requestXML.MsgType=="location")
{
stringcity=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>";
}
}
elseif(requestXML.MsgType=="image")
{
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>";
//返回10以内条
//intsize=10;
//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>"+size+"</ArticleCount><Articles>";
//List<string>list=newList<string>();
////假如有20条查询的返回结果
//for(inti=0;i<20;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<size&&i<list.Count;i++)
//{
//resxml+="<item><Title><![CDATA[沈阳-黑龙江]]></Title><Description><![CDATA[元旦特价:¥300市场价:¥400]]></Description><PicUrl><![CDATA["+"http://www.hougelou.com"+piclist[i]+"]]></PicUrl><Url><![CDATA[http://www.hougelou.com]]></Url></item>";
//}
//resxml+="</Articles><FuncFlag>1</FuncFlag></xml>";
}
elseif(wx_tmsg.GetMsgCount(requestXML.FromUserName)==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.GetFirst()+"]]></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>";
}
//WriteTxt(resxml);
System.Web.HttpContext.Current.Response.Write(resxml);
WriteToDB(requestXML,resxml,mi.pid);
}
catch(Exceptionex)
{
//WriteTxt("异常:"+ex.Message+"Struck:"+ex.StackTrace.ToString());
wx_logs.MyInsert("异常:"+ex.Message+"Struck:"+ex.StackTrace.ToString());
}
}
///<summary>
///unix时间转换为datetime
///</summary>
///<paramname="timeStamp"></param>
///<returns></returns>
privateDateTimeUnixTimeToTime(stringtimeStamp)
{
DateTimedtStart=TimeZone.CurrentTimeZone.ToLocalTime(newDateTime(1970,1,1));
longlTime=long.Parse(timeStamp+"0000000");
TimeSpantoNow=newTimeSpan(lTime);
returndtStart.Add(toNow);
}
///<summary>
///datetime转换为unixtime
///</summary>
///<paramname="time"></param>
///<returns></returns>
privateintConvertDateTimeInt(System.DateTimetime)
{
System.DateTimestartTime=TimeZone.CurrentTimeZone.ToLocalTime(newSystem.DateTime(1970,1,1));
return(int)(time-startTime).TotalSeconds;
}
///<summary>
///调用百度地图,返回坐标信息
///</summary>
///<paramname="y">经度</param>
///<paramname="x">纬度</param>
///<returns></returns>
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);
XmlDocumentdoc=newXmlDocument();
doc.LoadXml(res);
XmlElementrootElement=doc.DocumentElement;
stringStatus=rootElement.SelectSingleNode("status").InnerText;
if(Status=="OK")
{
//仅获取城市
XmlNodeListxmlResults=rootElement.SelectSingleNode("/GeocodeResponse").ChildNodes;
for(inti=0;i<xmlResults.Count;i++)
{
XmlNodechildNode=xmlResults[i];
if(childNode.Name=="status")
{
continue;
}
stringcity="0";
for(intw=0;w<childNode.ChildNodes.Count;w++)
{
for(intq=0;q<childNode.ChildNodes[w].ChildNodes.Count;q++)
{
XmlNodechildeTwo=childNode.ChildNodes[w].ChildNodes[q];
if(childeTwo.Name=="long_name")
{
city=childeTwo.InnerText;
}
elseif(childeTwo.InnerText=="locality")
{
returncity;
}
}
}
returncity;
}
}
}
catch(Exceptionex)
{
//WriteTxt("map异常:"+ex.Message.ToString()+"Struck:"+ex.StackTrace.ToString());
return"0";
}
return"0";
}
///<summary>
///Post提交调用抓取
///</summary>
///<paramname="url">提交地址</param>
///<paramname="param">参数</param>
///<returns>string</returns>
publicstringwebRequestPost(stringurl,stringparam)
{
byte[]bs=System.Text.Encoding.UTF8.GetBytes(param);
HttpWebRequestreq=(HttpWebRequest)HttpWebRequest.Create(url+"?"+param);
req.Method="Post";
req.Timeout=120*1000;
req.ContentType="application/x-www-form-urlencoded;";
req.ContentLength=bs.Length;
using(StreamreqStream=req.GetRequestStream())
{
reqStream.Write(bs,0,bs.Length);
reqStream.Flush();
}
using(WebResponsewr=req.GetResponse())
{
//在这里对接收到的页面内容进行处理
Streamstrm=wr.GetResponseStream();
StreamReadersr=newStreamReader(strm,System.Text.Encoding.UTF8);
stringline;
System.Text.StringBuildersb=newSystem.Text.StringBuilder();
while((line=sr.ReadLine())!=null)
{
sb.Append(line+System.Environment.NewLine);
}
sr.Close();
strm.Close();
returnsb.ToString();
}
}
privatevoidWriteToDB(RequestXMLrequestXML,string_xml,int_pid)
{
wx_tmsgwx=newwx_tmsg();
wx.AddNew();
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.Update();
}
catch(Exceptionex)
{
wx_logs.MyInsert(ex.Message);
//ex.message;
}
}
}
//微信请求类
publicclassRequestXML
{
privatestringtoUserName="";
///<summary>
///消息接收方微信号,一般为公众平台账号微信号
///</summary>
publicstringToUserName
{
get{returntoUserName;}
set{toUserName=value;}
}
privatestringfromUserName="";
///<summary>
///消息发送方微信号
///</summary>
publicstringFromUserName
{
get{returnfromUserName;}
set{fromUserName=value;}
}
privatestringcreateTime="";
///<summary>
///创建时间
///</summary>
publicstringCreateTime
{
get{returncreateTime;}
set{createTime=value;}
}
privatestringmsgType="";
///<summary>
///信息类型地理位置:location,文本消息:text,消息类型:image
///</summary>
publicstringMsgType
{
get{returnmsgType;}
set{msgType=value;}
}
privatestringcontent="";
///<summary>
///信息内容
///</summary>
publicstringContent
{
get{returncontent;}
set{content=value;}
}
privatestringlocation_X="";
///<summary>
///地理位置纬度
///</summary>
publicstringLocation_X
{
get{returnlocation_X;}
set{location_X=value;}
}
privatestringlocation_Y="";
///<summary>
///地理位置经度
///</summary>
publicstringLocation_Y
{
get{returnlocation_Y;}
set{location_Y=value;}
}
privatestringscale="";
///<summary>
///地图缩放大小
///</summary>
publicstringScale
{
get{returnscale;}
set{scale=value;}
}
privatestringlabel="";
///<summary>
///地理位置信息
///</summary>
publicstringLabel
{
get{returnlabel;}
set{label=value;}
}
privatestringpicUrl="";
///<summary>
///图片链接,开发者可以用HTTPGET获取
///</summary>
publicstringPicUrl
{
get{returnpicUrl;}
set{picUrl=value;}
}
}
说明: 其中用到的mijiya类,主要是调用数据库进行关键词匹配自动回复内容,可以根据自己的业务情况编写。