.net开发菜鸟微信之一:菜中菜.....

先废话几句:第一次写博客,还真有点小激动,不为啥,我这烂技术,也不好拿出来炫,之所以厚着脸皮发一贴,主要是想帮和我一样准备开发微信的朋友一个小的借鉴,在学习微信开发之前,看了很多的示例,说实话,看得真心不明白所以然,可能是自己悟性不够的原因,不过大多数都是大神写的,我这只能发挥拿来主义了,多次各位大神的无私奉献、在此直接贴码。

先创建  WeixinServer 类:

public class WeixinServer
    {
       const string token = "你的token"; 
        /// <summary>
        /// 验证签名
        /// </summary>
        /// <param name="signature"></param>
        /// <param name="timestamp"></param>
        /// <param name="nonce"></param>
        /// <returns></returns>
        public static bool CheckSignature(String signature, String timestamp, String nonce)
        {
            String[] arr = new String[] { token, timestamp, nonce };
            // 将token、timestamp、nonce三个参数进行字典序排序  
            Array.Sort<String>(arr);


            StringBuilder content = new StringBuilder();
            for (int i = 0; i < arr.Length; i++)
            {
                content.Append(arr[i]);
            }
            String tmpStr = SHA1_Encrypt(content.ToString());
            // 将sha1加密后的字符串可与signature对比,标识该请求来源于微信  
            return tmpStr != null ? tmpStr.Equals(signature) : false;
        }


        /// <summary>
        /// 使用缺省密钥给字符串加密
        /// </summary>
        /// <param name="Source_String"></param>
        /// <returns></returns>
        public static string SHA1_Encrypt(string Source_String)
        {
            byte[] StrRes = Encoding.Default.GetBytes(Source_String);
            HashAlgorithm iSHA = new SHA1CryptoServiceProvider();
            StrRes = iSHA.ComputeHash(StrRes);
            StringBuilder EnText = new StringBuilder();
            foreach (byte iByte in StrRes)
            {
                EnText.AppendFormat("{0:x2}", iByte);
            }
            return EnText.ToString();
        }


        /// <summary>
        /// 将xml文件转换成Hashtable
        /// </summary>
        /// <param name="xml"></param>
        /// <returns></returns>
        public static Hashtable ParseXml(String xml)
        {
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.LoadXml(xml);
            XmlNode bodyNode = xmlDocument.ChildNodes[0];
            Hashtable ht = new Hashtable();
            if (bodyNode.ChildNodes.Count > 0)
            {
                foreach (XmlNode xn in bodyNode.ChildNodes)
                {
                    ht.Add(xn.Name, xn.InnerText);
                }
            }
            return ht;
        }
    }

新建一个 aspx页面:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;
using System.Net;
using PCM.Business;

public partial class Modules_Test_wx : System.Web.UI.Page
{
    const string Token = "你的token"; 


    protected void Page_Load(object sender, EventArgs e)
    {
        string postStr = "";
        if (Request.HttpMethod.ToUpper() == "GET")
        {
            bindcs();
            // 微信加密签名  
            string signature = Request.QueryString["signature"];
            // 时间戳  
            string timestamp = Request.QueryString["timestamp"];
            // 随机数  
            string nonce = Request.QueryString["nonce"];
            // 随机字符串  
            string echostr = Request.QueryString["echostr"];
            if (WeixinServer.CheckSignature(signature, timestamp, nonce))
            {
                Response.Write(echostr);
                Response.End();
            }
        }
        else if (Request.HttpMethod.ToUpper() == "POST")
        {
            StreamReader stream = new StreamReader(Request.InputStream);
            string xml = stream.ReadToEnd();
            //WriteLog(xml);
            
            processRequest(xml);
        }
       
    }


    public void bindcs()
    {
        string xml = "<xml>";
        xml += " <ToUserName><![CDATA[server]]></ToUserName>";
        xml += " <FromUserName><![CDATA[sa]]></FromUserName>";
        xml += " <CreateTime>1449229434</CreateTime>";
        xml += " <MsgType><![CDATA[event]]></MsgType>";
        xml += " <Event><![CDATA[CLICK]]></Event>";
        xml += " <EventKey><![CDATA[椅]]></EventKey>";
        xml += " </xml>";


        processRequest(xml);
        
    }


    /// <summary>
    /// 处理微信发来的请求 
    /// </summary>
    /// <param name="xml"></param>
    public void processRequest(String xml)
    {
        try
        {
            // xml请求解析  
            Hashtable requestHT = WeixinServer.ParseXml(xml);


            // 发送方帐号(open_id)  
            string fromUserName = (string)requestHT["FromUserName"];
            // 公众帐号  
            string toUserName = (string)requestHT["ToUserName"];
            // 消息类型  
            string msgType = (string)requestHT["MsgType"];


            //WriteLog("postStr:" + msgType + " 判断传入的是什么类型!");


            //公共部份
            string strresponse = "";
            strresponse += "<xml>";
            strresponse +=  "<ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>";
            strresponse += "<FromUserName><![CDATA[" + toUserName + "]]></FromUserName>";
            strresponse += "<CreateTime>" + DateTime.Now.Ticks.ToString() + "</CreateTime>";
            //文字消息
            if (msgType == "text")
            {
               string content = (string)requestHT["Content"];
               string menu = "";
               switch (content)
               {
                   case "1":
                       menu = "得礼品!";
                       strresponse += "<Content><![CDATA[" + menu + "]]></Content>";
                       break;
                   case "2":
                       menu = "上当了吧!";
                       strresponse += "<Content><![CDATA[" + menu + "]]></Content>";
                       break;
                   case "3":
                       string postdate="{ \"touser\":\"OPENID\",\"msgtype\":\"text\",\"text\":{\"content\":\"Hello World\"}";
                       //string str = GetPage("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=hskjpcmsoft", postdate);
                       //strresponse += "<Content><![CDATA[" + postdate + "]]></Content>";
                       //WriteLog(str);
                       break;
                   default:
                       menu = "您好,我是SuperMan!很高兴为您服务!\n 回复内容:\n 1(得礼品)\n 2(抽奖) ";
                       strresponse +=  "<Content><![CDATA[" + menu + "]]></Content>";
                       break;
               }
               strresponse +=  "<MsgType><![CDATA[text]]></MsgType>";
               strresponse +=  "<FuncFlag>1<FuncFlag>";
               strresponse +=  "</xml>";
               //WriteLog("postStr:" + content);
               Response.Write(strresponse);
               Response.End(); 
           }
           else if (msgType == "event")
           {
               // 事件类型  
               String eventType = (string)requestHT["Event"];
               // 订阅  
               if (eventType=="Subscribe")
               {
                  
                   //Response.Write(GetMainMenuMessage(toUserName, fromUserName, "谢谢您的关注!,"));
                   
               }
               // 取消订阅  
               else if (eventType=="Unsubscribe")
               {
                   // TODO 取消订阅后用户再收不到公众号发送的消息,因此不需要回复消息  "ReqEventType.Unsubscribe"
               }
               // 自定义菜单点击事件  
               else if (eventType=="CLICK")
               {
                   string postdate = "{ \"touser\":\"OPENID\",\"msgtype\":\"text\",\"text\":{\"content\":\"Hello World\"}";
                   strresponse +="<MsgType><![CDATA[event]]></MsgType>";
                   strresponse +=  "<Event><![CDATA[CLICK]]></Event>";
                   strresponse += "<EventKey><![CDATA[" + postdate + "]]></EventKey>";
                   strresponse += "</xml>";
                   
                   Response.Write(strresponse);
                   Response.End(); 
               }  
           }
           else if (msgType == "image")
           {
               //ReqMsgType.Location
           }


  
        }
        catch (Exception e)
        {
            
        }
    }


    public string GetPage(string posturl, string postData)
    {
        Stream outstream = null;
        Stream instream = null;
        StreamReader sr = null;
        HttpWebResponse response = null;
        HttpWebRequest request = null;
        Encoding encoding = Encoding.UTF8;
        byte[] data = encoding.GetBytes(postData);
        // 准备请求...
        try
        {
            // 设置参数
            request = WebRequest.Create(posturl) as HttpWebRequest;
            CookieContainer cookieContainer = new CookieContainer();
            request.CookieContainer = cookieContainer;
            request.AllowAutoRedirect = true;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;
            outstream = request.GetRequestStream();
            outstream.Write(data, 0, data.Length);
            outstream.Close();
            //发送请求并获取相应回应数据
            response = request.GetResponse() as HttpWebResponse;
            //直到request.GetResponse()程序才开始向目标网页发送Post请求
            instream = response.GetResponseStream();
            sr = new StreamReader(instream, encoding);
            //返回结果网页(html)代码
            string content = sr.ReadToEnd();
            string err = string.Empty;
            return content;
        }
        catch (Exception ex)
        {
            string err = ex.Message;
            return string.Empty;
        }
    }


    /// <summary>
    /// 写日志(用于跟踪)
    /// </summary>
    private void WriteLog(string strMemo)
    {
        string strFilePath = Server.MapPath("..\\..\\PCMLog");
        if (!Directory.Exists(strFilePath))
        {
            Directory.CreateDirectory(strFilePath);
        }
        string filename = Server.MapPath("..\\..\\PCMLog\\log.txt");


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

好了,码已贴完,简单的实现了,通过微信发送请求到公众号,公众号通过服务器地址响应到.net页面。页面处理返回文本数据到微信里面。

因本人注册公众号的时候选择了 订阅号,现在反悔莫及。大伙还是用 服务号 好些。 在此,未实现菜单功能!

好了,拼命般的贴出来了,欢迎大家吐水,如果有大神愿意提点的,麻烦加好友,微信路上,需要大神照扶!!!!! 

小菜微信号:hejingrose


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值