代码改变世界

如何用Azure Web App Services接入微信公众号

2016-10-19 13:25  微软一站式示例代码库  阅读(1273)  评论(0编辑  收藏  举报

注:本文提到的代码示例下载地址>如何用Azure Web App Services接入微信公众号

如何用Azure Web App Services接入微信公众号

简介

此示例演示如何创建Azure Web App Services、开发、部暑、接入微信公众号。

先决条件

Microsoft Visual Studio 2015

运行示例

• 登录http://portal.azure.com,创建Microsoft Azure 应用程序服务


 

  

 

 

  

• 设置FTP部署凭据


 


• 设置Web.configTOKENvalue,Token可由开发者可以任意填写,用作生成微信公众号签名(该Token会和接口URL中包含的Token进行比对,从而验证安全性。



• 通过FTP把程序发布部暑到Azure应用程序服务


 

 


• 登录微信公众平台https://mp.weixin.qq.com,创建公众平台测试账号 



填写服务器配置,验证服务器地址的有效性,URL是开发者用来接收微信消息和事件的接口URL。TOKEN值需跟web.confi设置的值一致


 

• 关注测试公众号发送信息到公众号,测试程序是否自动回复内容


 

代码

 

 public static void Valid()
        {
            string signature = HttpContext.Current.Request["signature"];
            string timestamp = HttpContext.Current.Request["timestamp"];
            string nonce = HttpContext.Current.Request["nonce"];
            string echostr = HttpContext.Current.Request["echostr"];

            if (HttpContext.Current.Request.HttpMethod == "GET")
            {
                if (CheckSignature(signature, timestamp, nonce))
                {
                    HttpContext.Current.Response.Output.Write(echostr);
                }
                else
                {
                    HttpContext.Current.Response.Output.Write("Failed valid");
                }
                HttpContext.Current.Response.End();
            }
        }

        public static void ResponseMsg()
        {
            if (HttpContext.Current.Request.HttpMethod.ToUpper() == "POST")
            {
                try
                {
                    string postString = string.Empty;
                    using (Stream stream = HttpContext.Current.Request.InputStream)
                    {
                        Byte[] postBytes = new Byte[stream.Length];
                        stream.Read(postBytes, 0, (Int32)stream.Length);
                        postString = Encoding.UTF8.GetString(postBytes);
                    }
                    Hashtable postObj = ParseXml(postString);
                    string fromUsername = postObj["FromUserName"].ToString();
                    string toUsername = postObj["ToUserName"].ToString();
                    string keyword = postObj["Content"].ToString();
                    if (!String.IsNullOrEmpty(keyword))
                    {
                        String responseContent = string.Format(Message_Text, fromUsername, toUsername, DateTime.Now.Ticks,
                            "Welcome to OneCode OneScript!"
                            + "\r\n<a href=\"https://gallery.technet.microsoft.com\">Click me</a>");
                        HttpContext.Current.Response.Write(responseContent);
                    }
                    else
                    {
                        HttpContext.Current.Response.Write("Input something...");
                    }
                }
                catch (Exception ex)
                {
                   Console.Error.WriteLine(ex.StackTrace);
                }
            }
        }

        private static bool CheckSignature(String signature, String timestamp, String nonce)
        {
            String[] arr = new String[] { ConfigurationManager.AppSettings["TOKEN"].ToString(), 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());
            return tmpStr != null ? tmpStr.Equals(signature) : false;
        }

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

        private 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;
        }

        private static string Message_Text
        {
            get { return @"<xml>
                            <ToUserName><![CDATA[{0}]]></ToUserName>
                            <FromUserName><![CDATA[{1}]]></FromUserName>
                            <CreateTime>{2}</CreateTime>
                            <MsgType><![CDATA[text]]></MsgType>
                            <Content><![CDATA[{3}]]></Content>
                           </xml>"; }
        }
 

更多信息

• 微信公众平台开发者文档

• What is Azure App Service?

 

官方站点: