首页 > 代码库 > 微信公众号服务 - 简单demo(C#)

微信公众号服务 - 简单demo(C#)

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.Security;using System.Collections;using System.Xml;using System.Xml.Linq;using System.IO;using System.Text;using System.Text.RegularExpressions;public partial class wx : System.Web.UI.Page{    const string Token = "mrlenon";//你的token    protected void Page_Load(object sender, EventArgs e)    {        string postStr = "";        if (Request.HttpMethod.ToLower() == "post")        {            System.IO.Stream s = System.Web.HttpContext.Current.Request.InputStream;            byte[] b = new byte[s.Length];            s.Read(b, 0, (int)s.Length);            postStr = System.Text.Encoding.UTF8.GetString(b);            if (!string.IsNullOrEmpty(postStr))            {                //ResponseMsg(postStr);                Response.Write(ResponseMsg(postStr));                Response.End();            }            //WriteLog("postStr:" + postStr);        }        else        {            Valid();        }    }    /// <summary>    /// 验证微信签名    /// </summary>    /// * 将token、timestamp、nonce三个参数进行字典序排序    /// * 将三个参数字符串拼接成一个字符串进行sha1加密    /// * 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信。    /// <returns></returns>    private bool CheckSignature()    {        string signature = Request.QueryString["signature"].ToString();        string timestamp = Request.QueryString["timestamp"].ToString();        string nonce = Request.QueryString["nonce"].ToString();        string[] ArrTmp = { Token, timestamp, nonce };        Array.Sort(ArrTmp);     //字典排序        string tmpStr = string.Join("", ArrTmp);        tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");        tmpStr = tmpStr.ToLower();        if (tmpStr == signature)        {            return true;        }        else        {            return false;        }    }    private void Valid()    {        string echoStr = Request.QueryString["echoStr"].ToString();        if (CheckSignature())        {            if (!string.IsNullOrEmpty(echoStr))            {                Response.Write(echoStr);                Response.End();            }        }    }    /// <summary>    /// 返回微信POST过来的结果(微信信息返回)    /// </summary>    /// <param name="weixinXML">微信服务器post过来的数据</param>    private string ResponseMsg(string weixinXML)    {        Hashtable ht = GetXmlName(weixinXML);        //这里写你的返回信息代码        StringBuilder sb = new StringBuilder();        sb.Append("<xml>");        sb.Append("<ToUserName><![CDATA[" + ht["FromUserName"].ToString() + "]]></ToUserName>");        sb.Append("<FromUserName><![CDATA[" + ht["ToUserName"].ToString() + "]]></FromUserName>");        sb.Append("<CreateTime>" + ht["CreateTime"].ToString() + "</CreateTime>");        sb.Append("<MsgType><![CDATA[" + ht["MsgType"].ToString() + "]]></MsgType>");        sb.Append("<Content><![CDATA[" + ht["Content"].ToString() + "]]></Content>");        //switch (ht["MsgType"].ToString())        //{        //    case "text":        //        sb.Append("<MsgType><![CDATA[" + ht["MsgType"].ToString() + "]]></MsgType>");        //        sb.Append("<Content><![CDATA[" + ht["Content"].ToString() + "]]></Content>");        //        break;        //    case "image":        //        sb.Append("<MsgType><![CDATA[" + ht["MsgType"].ToString() + "]]></MsgType>");        //        sb.Append("<Content><![CDATA[亲,目前还没有做图片消息处理的功能哦!]]></Content>");        //        sb.Append("<Image>");        //        sb.Append("<MediaId><![CDATA[" + ht["MediaId"].ToString() + "]]></MediaId>");        //        sb.Append("</Image>");        //        break;        //    case "voice":        //        sb.Append("<Content><![CDATA[亲,目前还没有做语音消息处理的功能哦!]]></Content>");        //        break;        //    case "video":        //        sb.Append("<Content><![CDATA[亲,目前还没有做视频消息处理的功能哦!]]></Content>");        //        break;        //    case "location":        //        sb.Append("<Content><![CDATA[亲,目前还没有做地理位置处理的功能哦!]]></Content>");        //        break;        //    case "link":        //        sb.Append("<Content><![CDATA[亲,目前还没有做链接消息处理的功能哦!]]></Content>");        //        break;        //}        sb.Append("</xml>");        return sb.ToString();    }    /// <summary>    /// unix时间转换为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转换为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>    /// 写日志(用于跟踪)    /// </summary>    private void WriteLog(string strMemo)    {        string filename = Server.MapPath("/logs/log.txt");        if (!Directory.Exists(Server.MapPath("//logs//")))            Directory.CreateDirectory("//logs//");        StreamWriter sr = null;        try        {            if (!File.Exists(filename))            {                sr = File.CreateText(filename);            }            else            {                sr = File.AppendText(filename);            }            sr.WriteLine(strMemo);        }        catch        {        }        finally        {            if (sr != null)                sr.Close();        }    }    /// <summary>    /// 解析post过来的数据    /// </summary>    /// <param name="xmlStr"></param>    /// <returns></returns>    private Hashtable GetXmlName(string xmlStr)    {        Hashtable ht = new Hashtable(); //创建一个Hashtable实例        XmlDocument xx = new XmlDocument();        xx.LoadXml(xmlStr);//加载xml        //开发者微信号        XmlNodeList toList = xx.GetElementsByTagName("ToUserName"); //取得节点名为ToUserName的XmlNode集合        XmlNode toNode = toList[0];        string toName = toNode.InnerText;        //发送方帐号(一个OpenID)        XmlNodeList fromList = xx.GetElementsByTagName("FromUserName"); //取得节点名为FromUserName的XmlNode集合        XmlNode fromNode = fromList[0];        string fromName = fromNode.InnerText;        //消息创建时间 (整型)        XmlNodeList createTimeList = xx.GetElementsByTagName("CreateTime"); //取得节点名为CreateTime的XmlNode集合        XmlNode createTimeNode = createTimeList[0];        string createTimeName = createTimeNode.InnerText;        //消息类型 text/image/voice/video/location/link        XmlNodeList msgTypeList = xx.GetElementsByTagName("MsgType"); //取得节点名为MsgType的XmlNode集合        XmlNode msgTypeNode = msgTypeList[0];        string msgTypeName = msgTypeNode.InnerText;        //文本消息内容        XmlNodeList contentList = xx.GetElementsByTagName("Content"); //取得节点名为CreateTime的XmlNode集合        XmlNode contentNode = contentList[0];        string contentName = contentNode.InnerText;        //图片链接        XmlNodeList picUrlList = xx.GetElementsByTagName("PicUrl"); //取得节点名为PicUrl的XmlNode集合        XmlNode picUrlNode = picUrlList[0];        string picUrlName = picUrlNode.InnerText;        //图片消息媒体id,可以调用多媒体文件下载接口拉取数据。        XmlNodeList mediaIdList = xx.GetElementsByTagName("MediaId"); //取得节点名为PicUrl的XmlNode集合        XmlNode mediaIdNode = mediaIdList[0];        string mediaIdName = mediaIdNode.InnerText;        //消息id,64位整型        XmlNodeList msgIdList = xx.GetElementsByTagName("MsgId"); //取得节点名为MsgId的XmlNode集合        XmlNode msgIdNode = msgIdList[0];        string msgIdName = msgIdNode.InnerText;        ht.Add("ToUserName", toName);        ht.Add("FromUserName", fromName);        ht.Add("CreateTime", createTimeName);        ht.Add("MsgType", msgTypeName);        ht.Add("Content", contentName);        //ht.Add("PicUrl", picUrlName);        //ht.Add("MediaId", mediaIdName);        //ht.Add("MsgId", msgIdName);        return ht;    }}

  

微信公众号服务 - 简单demo(C#)