码迷,mamicode.com
首页 > 微信 > 详细

.net微信公众号开发——快速入门

时间:2015-02-25 11:31:13      阅读:343      评论:0      收藏:0      [点我收藏+]

标签:

作者:王先荣

    最近在学习微信公众号开发,将学习的成果做成了一个类库,方便重复使用。

    使用该类库的流程及寥寥数行代码得到的结果如下。

 技术分享 技术分享

1 引用微信公众号类库

    引用xrwang.weixin.PublicAccount。

 

2 添加公众号信息

    添加提供服务的公众号的信息,包括:原始id、AppId、AppSecret、EncodingAESKey。代码如下:

AccountInfoCollection.SetAccountInfo(new AccountInfo("YourOriginalId", "AppId", "AppSecret", "Token", "EncodingAESKey"));

    如果需要同时给多个公众号提供服务,重复上面这行代码就可以了。

    (注:多个公众号的Token必须一致,这是微信服务器的原因)

    我喜欢将添加公众号信息的工作放到Gobal.asax的Application_Start方法中。

 

3 与微信服务器通信

    我添加了名为“WeixinInterface.ashx”的一般处理页,并在其中与微信服务器进行通信,包括:校验请求、处理请求、回复适当的响应。代码如下:

技术分享
    public void ProcessRequest(HttpContext context)

    {

        string result = string.Empty;

        if (Validate(context))

        {

            if (context.Request.HttpMethod == WebRequestMethods.Http.Get)

                result = HandleGet(context);

            else if (context.Request.HttpMethod == WebRequestMethods.Http.Post)

                result = HandlePost(context);

        }

        else

            Message.Insert(new Message(MessageType.Exception, "校验消息失败。\r\n地址:" + context.Request.RawUrl));

        context.Response.Write(result);

    }
与微信服务器通信

3.1 校验请求

    首先,我们需要校验接收到的请求是否来自微信服务器,方法如下:

技术分享
    /// <summary>

    /// 验证消息的有效性

    /// </summary>

    /// <param name="context"></param>

    /// <returns>如果消息有效,返回true;否则返回false。</returns>

    private bool Validate(HttpContext context)

    {

        string token = AccountInfoCollection.First.Token;   //由于在校验微信签名时,微信未传入公众号,因此这里用第一个公众号的TOKEN

        string signature = RequestEx.TryGetQueryString("signature");

        string timestamp = RequestEx.TryGetQueryString("timestamp");

        string nonce = RequestEx.TryGetQueryString("nonce");

        if (string.IsNullOrWhiteSpace(signature) || string.IsNullOrWhiteSpace(timestamp) || string.IsNullOrWhiteSpace(nonce))

            return false;

        return xrwang.weixin.PublicAccount.Utility.CheckSignature(signature, token, timestamp, nonce);

    }
校验请求

    当然,如果你对世界充满爱,相信没有欺骗;如果你厉行节约,急需提高性能;不校验也是可以的。

3.2 处理请求

    校验完请求之后,我们分两种情况处理请求:

(1)微信服务器的GET请求,用来验证我们的服务器是否正在工作,我们直接返回echostr就可以了;

技术分享
    /// <summary>

    /// 处理微信的GET请求,校验签名

    /// </summary>

    /// <param name="context"></param>

    /// <returns>返回echostr</returns>

    private string HandleGet(HttpContext context)

    {

        return RequestEx.TryGetQueryString("echostr");

    }
处理GET请求

(2)微信服务器的POST请求,这是服务器分发给我们的消息,我们需要解析消息。

RequestMessageHelper helper = new RequestMessageHelper(context.Request);

3.3 回复响应

    解析完微信服务器分发给我们的消息之后,我们要做出回应。我这里把收到的消息直接发回去,偷懒~\(≧▽≦)/~啦啦啦

技术分享
    /// <summary>

    /// 处理微信的POST请求

    /// </summary>

    /// <param name="context"></param>

    /// <returns>返回xml响应</returns>

    private string HandlePost(HttpContext context)

    {

        RequestMessageHelper helper = new RequestMessageHelper(context.Request);

        if (helper.Message != null)

        {

            ResponseBaseMessage responseMessage = HandleRequestMessage(helper.Message);

            return responseMessage.ToXml(helper.EncryptType);

        }

        else

            return string.Empty;

    }

 

    /// <summary>

    /// 处理请求消息,返回响应消息

    /// </summary>

    /// <returns>返回响应消息</returns>

    private ResponseBaseMessage HandleRequestMessage(RequestBaseMessage requestMessage)

    {

        ResponseTextMessage response = new ResponseTextMessage(requestMessage.FromUserName, requestMessage.ToUserName,

            DateTime.Now, string.Format("自动回复,请求内容如下:\r\n{0}", requestMessage));

        response.Content += "\r\n<a href=\"http://www.cnblogs.com\">博客园</a>";

        return response;

    }
回复响应

    当然了,正常情况下,我们需要兵来将挡水来土掩,根据不同的请求,回复对应的响应。如果需要对请求排队,再一一回复客服消息,可以先直接回复空字符串。回复客服消息的方法请看后面的文章。

 

4 微信公众号类库简介

    xrwang.weixin.PublicAccount是一套简化微信公众号开发的类库,由王先荣开发,并且正在添砖加瓦中。采用MIT开源协议,大家可以随便用,别删掉我的名字就可以啦。

    源代码的地址是:http://git.oschina.net/xrwang2/xrwang.weixin.PublicAccount

    如果发现BUG,请在博客中留言,或者给我发电子邮件:xrwang(a)126.com。

    千万不要用QQ或者阿里旺旺聊天,打扰我玩游戏,我会骂人的  >.<

 

5 体验测试号

    下面分别是我的测试号和公众号,您可以对照文章来体验哦。

测试号

 技术分享

测试号权限多,几乎可以测试公众平台的所有功能。

我的公众号

xrwang

 技术分享

个人订阅号,功能较少,不过我会特别优化。

 

好了,感谢您看完本文,希望对您有所帮助。本文来自xrwang的博客http://xrwang/cnblogs.com,欢迎在不篡改作者的前提下转载以传播知识。

.net微信公众号开发——快速入门

标签:

原文地址:http://www.cnblogs.com/xrwang/p/PublicAccount-QuickStart.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!