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

注:本文提到的代码示例下载地址>如何用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?

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值