微信消息的處理和應答


1.微信消息應答流程
微信服務器是客戶手機和開發服務器信息流通的橋梁。消息流程圖如下:

2.微信服務器向開發服務器請求消息
1)文本消息處理
2)事件消息處理
3)開發者認證處理


微信消息處理入口操作,代碼示例如下:

public void ProcessRequest(HttpContext context)
{
    //WHC.Framework.Commons.LogTextHelper.Info("測試記錄");

    string postString = string.Empty;
    if (HttpContext.Current.Request.HttpMethod.ToUpper() == "POST")
    {
        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);
        }

        if (!string.IsNullOrEmpty(postString))
        {
            Execute(postString);
        }
    }
    else
    {
        Auth();
    }
}

WeixinApiDispatch消息分發管理類,它提取請求消息的內容,並構建不同類型的消息參數,傳遞給不同的響應函數進行處理,然后返回封裝好的XML內容,作為響應。

/// <summary>
/// 處理各種請求信息並應答(通過POST的請求)
/// </summary>
/// <param name="postStr">POST方式提交的數據</param>
private void Execute(string postStr)
{
    WeixinApiDispatch dispatch = new WeixinApiDispatch();
    string responseContent = dispatch.Execute(postStr);

    HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;
    HttpContext.Current.Response.Write(responseContent);
}

代碼處理邏輯如下圖所示:

具體的消息處理類:

/// <summary>
/// 客戶端請求的數據接口
/// </summary>
public interface IWeixinAction
{
    /// <summary>
    /// 對文本請求信息進行處理
    /// </summary>
    /// <param name="info">文本信息實體</param>
    /// <returns></returns>
    string HandleText(RequestText info);

    /// <summary>
    /// 對圖片請求信息進行處理
    /// </summary>
    /// <param name="info">圖片信息實體</param>
    /// <returns></returns>
    string HandleImage(RequestImage info);

...........................


    /// <summary>
    /// 對訂閱請求事件進行處理
    /// </summary>
    /// <param name="info">訂閱請求事件信息實體</param>
    /// <returns></returns>
    string HandleEventSubscribe(RequestEventSubscribe info);

    /// <summary>
    /// 對菜單單擊請求事件進行處理
    /// </summary>
    /// <param name="info">菜單單擊請求事件信息實體</param>
    /// <returns></returns>
    string HandleEventClick(RequestEventClick info);

..............................
}

其中,實體類參數是我們根據程序開發自己定義的,繼承關系如下所示:

3.開發者服務器向微信服務器進行的消息請求消息
我們可以通過微信,進行相關的消息回復或者數據管理操作。
如下如所示:

 

微信的回復消息處理,處理邏輯如下圖所示:

 

參考資料:http://www.cnblogs.com/wuhuacong/p/3614175.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM