用c#開發微信 (8) 微渠道 - 推廣渠道管理系統 3 UI設計及後臺處理

咱們能夠使用微信的「生成帶參數二維碼接口」和 「用戶管理接口」,來實現生成能標識不一樣推廣渠道的二維碼,記錄分配給不一樣推廣渠道二維碼被掃描的信息。這樣就能夠統計和分析不一樣推廣渠道的推廣效果。javascript

前面二篇《用c#開發微信 (6) 微渠道 - 推廣渠道管理系統 1 基礎架構搭建》, 《用c#開發微信 (7) 微渠道 - 推廣渠道管理系統 2 業務邏輯實現》分別介紹了數據訪問層和業務邏輯層。 本文是微渠道的第三篇,主要介紹以下內容:css

1. 接收二維碼掃描事件html

2. 推廣渠道類型管理前端

3. 推廣渠道管理java

4. 推廣渠道二維碼掃描記錄列表jquery

5. 下載渠道二維碼ajax

6. 微信用戶列表數據庫

 

下面是詳細的實現方法:bootstrap

 

1. 接收二維碼掃描事件

可參考前面的 《用c#開發微信 (4) 基於Senparc.Weixin框架的接收事件推送處理 (源碼下載)》,這裏就不過多講解了:c#

/// <summary>
/// 自定義MessageHandler
/// 把MessageHandler做爲基類,重寫對應請求的處理方法
/// </summary>
public partial class CustomMessageHandler : MessageHandler<MessageContext<IRequestMessageBase, IResponseMessageBase>>
{
   /// <summary>
   /// 構造函數
   /// </summary>
   /// <param name="inputStream"></param>
   /// <param name="maxRecordCount"></param>
   public CustomMessageHandler(Stream inputStream, int maxRecordCount = 0)
       : base(inputStream, null, maxRecordCount)
   {
       //這裏設置僅用於測試,實際開發能夠在外部更全局的地方設置,
       //好比MessageHandler<MessageContext>.GlobalWeixinContext.ExpireMinutes = 3。
       WeixinContext.ExpireMinutes = 3;
   }
   public override void OnExecuting()
   {
       //測試MessageContext.StorageData
       if (CurrentMessageContext.StorageData == null)
       {
           CurrentMessageContext.StorageData = 0;
       }
       base.OnExecuting();
   }
   public override void OnExecuted()
   {
       base.OnExecuted();
       CurrentMessageContext.StorageData = ((int)CurrentMessageContext.StorageData) + 1;
   }
   /// <summary>
   /// 處理掃描請求
   /// 用戶掃描帶場景值二維碼時,若是用戶已經關注公衆號,則微信會將帶場景值掃描事件推送給開發者。
   /// </summary>
   /// <returns></returns>
   public override IResponseMessageBase OnEvent_ScanRequest(RequestMessageEvent_Scan requestMessage)
   {
       int sceneId = 0;
       int.TryParse(requestMessage.EventKey, out sceneId);
       if (sceneId > 0)
       {
           new ChannelScanBll().SaveScan(requestMessage.FromUserName, sceneId, ScanType.Scan);
       }
       var responseMessage = CreateResponseMessage<ResponseMessageText>();
       responseMessage.Content = "掃描已記錄";
       return responseMessage;
   }
   /// <summary>
   /// 處理關注請求
   /// 用戶掃描帶場景值二維碼時,若是用戶還未關注公衆號,則用戶能夠關注公衆號,關注後微信會將帶場景值關注事件推送給開發者。
   /// </summary>
   /// <returns></returns>
   public override IResponseMessageBase OnEvent_SubscribeRequest(RequestMessageEvent_Subscribe requestMessage)
   {
       if (!string.IsNullOrWhiteSpace(requestMessage.EventKey))
       {
           string sceneIdstr = requestMessage.EventKey.Substring(8);
           int sceneId = 0;
           int.TryParse(sceneIdstr, out sceneId);
           if (sceneId > 0)
           {
               new ChannelScanBll().SaveScan(requestMessage.FromUserName, sceneId, ScanType.Subscribe);
           }
       }
       var responseMessage = CreateResponseMessage<ResponseMessageText>();
       responseMessage.Content = "掃描已記錄";
       return responseMessage;
   }
 
   public override IResponseMessageBase DefaultResponseMessage(IRequestMessageBase requestMessage)
   {
       //全部沒有被處理的消息會默認返回這裏的結果
       var responseMessage = this.CreateResponseMessage<ResponseMessageText>();
       responseMessage.Content = "這條消息來自DefaultResponseMessage。";
       return responseMessage;
   }
}

 

前端開發框架使用Bootstrap,沒有註明前臺的頁面表示前臺不用顯示任何內容

2. 推廣渠道類型管理

主要是對推廣渠道類型的新增、修改、刪除及列表顯示等

1) 渠道新增、修改頁面

前臺:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>修改渠道類型</title>
</head>
<body>
    <form id="Form1" class="form-horizontal" type="post" runat="server">
        <%if (ViewState["channelType"] != null)
          {%>
        <%-- 修改表單 --%>
        <input type="hidden" name="ID" value="<%=(ViewState["channelType"] as ChannelSystem.ViewEntity.ChannelTypeEntity).ID%>" />
        <div class="control-group">
            <label class="control-label" for="Name"><strong>渠道類型名稱</strong></label>
            <div class="controls">
                <input type="text" name="Name" value="<%=(ViewState["channelType"] as ChannelSystem.ViewEntity.ChannelTypeEntity).Name%>" />
            </div>
        </div>
        <%}
          else
          {%>
        <%-- 新增表單 --%>
        <div class="control-group">
            <label class="control-label" for="Name"><strong>渠道類型名稱</strong></label>
            <div class="controls">
                <input type="text" name="Name" />
            </div>
        </div>
        <%}%>
        <%-- 提交按鈕 --%>
        <button class="btn btn-large btn-primary" type="submit">保存</button>
    </form>
</body>
</html>

 

後臺:

/// <summary>
/// 新增或修改渠道類型
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        //修改渠道類型,首先獲取渠道類型數據
        int id;
        if (int.TryParse(Request.QueryString["id"], out id))
        {
            ViewState["channelType"] = new ChannelTypeBll().GetEntityById(id);
        }
    }
    else
    {
        //將渠道類型新增或修改的數據保存到數據庫
        var entity = new ChannelTypeEntity()
        {
            ID = Request.Form["ID"] == null ? 0 : int.Parse(Request.Form["ID"]),
            Name = Request.Form["Name"]
        };
        new ChannelTypeBll().UpdateOrInsertEntity(entity);
        //回到渠道類型列表頁面
        Response.Redirect("ChannelTypeList.aspx");
        Response.End();
    }
}

 

2) 渠道類型列表頁面

前臺:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>渠道類型列表</title>
</head>
<!-- #Bootstrap -->
<link href="Css/bootstrap.min.css" rel="stylesheet" />
<script src="Scripts/bootstrap.min.js"></script>
<!-- #Jquery -->
<script src="Scripts/jquery-1.9.1.min.js"></script>
<body>
    <div class="container">
        <form id="Form1" class="form-horizontal" type="post" runat="server">
            <h2 class="form-signin-heading">渠道類型列表</h2>
            <a class="btnGrayS vm doaddit" href="ChannelTypeEdit.aspx">添加</a> <a class="btnGrayS vm doaddit" href="ChannelList.aspx">渠道列表</a>
            <table id="listTable" class="table table-bordered table-hover dataTable" style="width: auto">
                <thead>
                    <tr>
                        <th style="border-color: #ddd; color: Black">ID
                        </th>
                        <th style="border-color: #ddd; color: Black">渠道類型名稱
                        </th>
                        <th style="border-color: #ddd; color: Black">操做
                        </th>
                    </tr>
                </thead>
                <tbody>
                    <% foreach (ChannelSystem.ViewEntity.ChannelTypeEntity channelType in (ViewState["ChannelTypeList"] as List<ChannelSystem.ViewEntity.ChannelTypeEntity>))
                       { %>
                    <tr>
                        <td><%= channelType.ID%>
                                </td>
                        <td><%= channelType.Name%>
                                </td>
                        <td>
                            <p>
                                <a class="btnGrayS vm doaddit" href="ChannelTypeEdit.aspx?id=<%= channelType.ID%>">編輯</a>
                                <a href="javascript:void(0)" data="<%= channelType.ID%>" class="dodelit deleteChannelType">刪除</a>
                            </p>
                        </td>
                    </tr>
                    <% } %>
                </tbody>
            </table>
        </form>
    </div>
    <script>
        $(function () {
            $(".deleteChannelType").click(function () {
                if (confirm("肯定刪除嗎?")) {
                    var id = $(this).attr("data");
                    $.ajax({
                        url: "ChannelTypeDelete.aspx?id=" + id,
                        type: "get",
                        success: function (repText) {
                            if (repText && repText == "True") {
                                window.location.reload();
                            } else {
                                alert(repText.ErrorMsg);
                            }
                        },
                        complete: function (xhr, ts) {
                            xhr = null;
                        }
                    });
                }
            });
        });
    </script>
</body>
</html>

 

後臺:

/// <summary>
/// 渠道類型列表
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Load(object sender, EventArgs e)
{
    //獲取渠道類型列表數據
    ViewState["ChannelTypeList"] = new ChannelTypeBll().GetEntities();
}

 

3) 渠道類型刪除頁面

後臺:

/// <summary>
/// 刪除渠道類型
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Load(object sender, EventArgs e)
{
    //獲取渠道類型ID
    int id;
    if (int.TryParse(Request.QueryString["id"], out id))
    {
        //刪除渠道類型並返回刪除結果
        bool result = new ChannelTypeBll().DeleteEntityById(id);
        Response.Write(result.ToString());
        Response.End();
    }
}

 

3. 推廣渠道管理

主要是對推廣渠道的新增、修改、刪除及列表顯示等

1) 渠道新增、修改頁面

前臺:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>修改渠道</title>
</head>
<body>
    <form id="Form1" class="form-horizontal" type="post" runat="server">
        <%if (ViewState["channel"] != null)
          {%>
        <%-- 修改表單 --%>
        <input type="hidden" name="ID" value="<%=(ViewState["channel"] as ChannelSystem.ViewEntity.ChannelEntity).ID%>" />
        <div class="control-group">
            <label class="control-label" for="Name"><strong>渠道名稱</strong></label>
            <div class="controls">
                <input type="text" name="Name" value="<%=(ViewState["channel"] as ChannelSystem.ViewEntity.ChannelEntity).Name%>" />
            </div>
        </div>
        <div class="control-group">
            <label class="control-label" for="ChannelTypeId"><strong>所屬渠道類型</strong></label>
            <div class="controls">
                <%-- 構造渠道類型下拉框 --%>
                <select name="ChannelTypeId">
                    <% foreach (ChannelSystem.ViewEntity.ChannelTypeEntity channelType in (ViewState["ChannelTypeList"] as List<ChannelSystem.ViewEntity.ChannelTypeEntity>))
                       { %>
                    <%if (channelType.ID == (ViewState["channel"] as ChannelSystem.ViewEntity.ChannelEntity).ChannelTypeId)
                      {%>
                    <%-- 設置渠道類型下拉框初始選中項目 --%>
                    <option value="<%=channelType.ID %>" selected="selected"><%=channelType.Name %></option>
                    <%}
                      else
                      {%>
                    <option value="<%=channelType.ID %>"><%=channelType.Name %></option>
                    <%}%>
                    <% } %>
                </select>
            </div>
        </div>
        <%}
          else
          {%>
        <%-- 新增表單 --%>
        <div class="control-group">
            <label class="control-label" for="Name"><strong>渠道名稱</strong></label>
            <div class="controls">
                <input type="text" name="Name" />
            </div>
        </div>
        <div class="control-group">
            <label class="control-label" for="ChannelTypeId"><strong>所屬渠道類型</strong></label>
            <div class="controls">
                <%-- 構造渠道類型下拉框 --%>
                <select name="ChannelTypeId">
                    <% foreach (ChannelSystem.ViewEntity.ChannelTypeEntity channelType in (ViewState["ChannelTypeList"] as List<ChannelSystem.ViewEntity.ChannelTypeEntity>))
                       { %>
                    <option value="<%=channelType.ID %>"><%=channelType.Name %></option>
                    <% } %>
                </select>
            </div>
        </div>
        <%}%>
        <%-- 提交按鈕 --%>
        <button class="btn btn-large btn-primary" type="submit">保存</button>
    </form>
</body>
</html>

 

後臺:

/// <summary>
/// 新增或修改渠道
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        //獲取渠道類型列表數據
        ViewState["ChannelTypeList"] = new ChannelTypeBll().GetEntities();
        //修改渠道,首先獲取渠道數據
        int id;
        if (int.TryParse(Request.QueryString["id"], out id))
        {
            ViewState["Channel"] = new ChannelBll().GetEntityById(id);
        }
    }
    else
    {
        //將渠道新增或修改的數據保存到數據庫
        var entity = new ChannelEntity()
        {
            ID = Request.Form["ID"] == null ? 0 : int.Parse(Request.Form["ID"]),
            Name = Request.Form["Name"],
            ChannelTypeId = int.Parse(Request.Form["ChannelTypeId"])
        };
        new ChannelBll().UpdateOrInsertEntity(entity);
        //回到渠道列表頁面
        Response.Redirect("ChannelList.aspx");
        Response.End();
    }
}

 

2) 渠道列表頁面

前臺:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>渠道類型列表</title>
</head>
<!-- #Bootstrap -->
<link href="Css/bootstrap.min.css" rel="stylesheet" />
<script src="Scripts/bootstrap.min.js"></script>
<!-- #Jquery -->
<script src="Scripts/jquery-1.9.1.min.js"></script>
<body>
    <div class="container">
        <form id="Form1" class="form-horizontal" type="post" runat="server">
            <h2 class="form-signin-heading">渠道類型列表</h2>
            <a class="btnGrayS vm doaddit" href="ChannelTypeEdit.aspx">添加</a> <a class="btnGrayS vm doaddit" href="ChannelList.aspx">渠道列表</a>
            <table id="listTable" class="table table-bordered table-hover dataTable" style="width: auto">
                <thead>
                    <tr>
                        <th style="border-color: #ddd; color: Black">ID
                        </th>
                        <th style="border-color: #ddd; color: Black">渠道類型名稱
                        </th>
                        <th style="border-color: #ddd; color: Black">操做
                        </th>
                    </tr>
                </thead>
                <tbody>
                    <% foreach (ChannelSystem.ViewEntity.ChannelTypeEntity channelType in (ViewState["ChannelTypeList"] as List<ChannelSystem.ViewEntity.ChannelTypeEntity>))
                       { %>
                    <tr>
                        <td><%= channelType.ID%>
                                </td>
                        <td><%= channelType.Name%>
                                </td>
                        <td>
                            <p>
                                <a class="btnGrayS vm doaddit" href="ChannelTypeEdit.aspx?id=<%= channelType.ID%>">編輯</a>
                                <a href="javascript:void(0)" data="<%= channelType.ID%>" class="dodelit deleteChannelType">刪除</a>
                            </p>
                        </td>
                    </tr>
                    <% } %>
                </tbody>
            </table>
        </form>
    </div>
    <script>
        $(function () {
            $(".deleteChannelType").click(function () {
                if (confirm("肯定刪除嗎?")) {
                    var id = $(this).attr("data");
                    $.ajax({
                        url: "ChannelTypeDelete.aspx?id=" + id,
                        type: "get",
                        success: function (repText) {
                            if (repText && repText == "True") {
                                window.location.reload();
                            } else {
                                alert(repText.ErrorMsg);
                            }
                        },
                        complete: function (xhr, ts) {
                            xhr = null;
                        }
                    });
                }
            });
        });
    </script>
</body>
</html>

 

後臺:

/// <summary>
/// 渠道列表
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Load(object sender, EventArgs e)
{
    //獲取渠道列表數據
    ViewState["ChannelList"] = new ChannelBll().GetEntities();
}

 

3) 渠道刪除頁面

後臺:

/// <summary>
/// 刪除渠道
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Load(object sender, EventArgs e)
{
    //獲取渠道ID
    int id;
    if (int.TryParse(Request.QueryString["id"], out id))
    {
        //刪除渠道並返回刪除結果
        bool result = new ChannelBll().DeleteEntityById(id);
        Response.Write(result.ToString());
        Response.End();
    }
}

 

 

4. 推廣渠道二維碼掃描記錄列表

前臺:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>掃描記錄列表</title>
</head>
<!-- #Bootstrap -->
<link href="Css/bootstrap.min.css" rel="stylesheet" />
<script src="Scripts/bootstrap.min.js"></script>
<!-- #Jquery -->
<script src="Scripts/jquery-1.9.1.min.js"></script>
<body>
    <div class="container">
        <form id="Form1" class="form-horizontal" type="post" runat="server">
            <h2 class="form-signin-heading">掃描記錄列表</h2>
            <table id="listTable" class="table table-bordered table-hover dataTable" style="width: auto">
                <thead>
                    <tr>
                        <th style="border-color: #ddd; color: Black">ID
                        </th>
                        <th style="border-color: #ddd; color: Black">掃描類型
                        </th>
                        <th style="border-color: #ddd; color: Black">掃描時間
                        </th>
                        <th style="border-color: #ddd; color: Black">所屬渠道ID
                        </th>
                        <th style="border-color: #ddd; color: Black">微信用戶OpenId
                        </th>
                        <th style="border-color: #ddd; color: Black">頭像
                        </th>
                        <th style="border-color: #ddd; color: Black">暱稱
                        </th>
                        <th style="border-color: #ddd; color: Black">性別
                        </th>
                        <th style="border-color: #ddd; color: Black">國家
                        </th>
                        <th style="border-color: #ddd; color: Black">省
                        </th>
                        <th style="border-color: #ddd; color: Black">市
                        </th>
                        <th style="border-color: #ddd; color: Black">關注時間
                        </th>
                    </tr>
                </thead>
                <tbody>
                    <% foreach (ChannelSystem.ViewEntity.ChannelScanDisplayEntity channelScanDisplay in (ViewState["ChannelScanDisplayList"] as List<ChannelSystem.ViewEntity.ChannelScanDisplayEntity>))
                       { %>
                    <tr>
                        <td><%= channelScanDisplay.ScanEntity.ID%>
                                </td>
                        <td><%= channelScanDisplay.ScanEntity.ScanType.ToString()%>
                                </td>
                        <td><%= channelScanDisplay.ScanEntity.ScanTime.ToString()%>
                                </td>
                        <td><%= channelScanDisplay.ScanEntity.ChannelId.ToString()%>
                                </td>
                        <td><%= channelScanDisplay.ScanEntity.OpenId%>
                                </td>
                        <td>
                            <img width="50px" src="<%= channelScanDisplay.UserInfoEntity.HeadImgUrl%>" />
                        </td>
                        <td><%= channelScanDisplay.UserInfoEntity.NickName%>
                                </td>
                        <td><%= channelScanDisplay.UserInfoEntity.Sex.ToString()%>
                                </td>
                        <td><%= channelScanDisplay.UserInfoEntity.Country%>
                                </td>
                        <td><%= channelScanDisplay.UserInfoEntity.Province%>
                                </td>
                        <td><%= channelScanDisplay.UserInfoEntity.City%>
                                </td>
                        <td><%= channelScanDisplay.UserInfoEntity.SubscribeTime.ToShortDateString()%>
                                </td>
                    </tr>
                    <% } %>
                </tbody>
            </table>
        </form>
    </div>
</body>
</html>

 

後臺:

/// <summary>
/// 渠道掃描記錄列表
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Load(object sender, EventArgs e)
{
    //獲取渠道ID
    int id;
    if (int.TryParse(Request.QueryString["id"], out id))
    {
        //獲取渠道掃描記錄列表數據
        ViewState["ChannelScanDisplayList"] = new ChannelScanBll().GetChannelScanList(id);
    }
}

 

5. 下載渠道二維碼

後臺:

/// <summary>
/// 下載渠道二維碼
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Load(object sender, EventArgs e)
{
    //獲取渠道ID
    int id;
    if (int.TryParse(Request.QueryString["id"], out id))
    {
        var entity = new ChannelBll().GetEntityById(id);
        //將數據庫中Base64String格式圖片轉換爲Image格式,返回給瀏覽器
        string base64Image = File.ReadAllText(System.Web.HttpContext.Current.Server.MapPath("~/App_Data/") + entity.Qrcode);
        byte[] arr = Convert.FromBase64String(base64Image);
        MemoryStream ms = new MemoryStream(arr);
        Response.ContentType = "image/jpeg";
        ms.WriteTo(Response.OutputStream);
        Response.End();
    }
}

 

6. 微信用戶列表

前臺:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>微信用戶列表</title>
</head>
<!-- #Bootstrap -->
<link href="Css/bootstrap.min.css" rel="stylesheet" />
<script src="Scripts/bootstrap.min.js"></script>
<!-- #Jquery -->
<script src="Scripts/jquery-1.9.1.min.js"></script>
<body>
    <div class="container">
        <form id="Form1" class="form-horizontal" type="post" runat="server">
            <h2 class="form-signin-heading">微信用戶列表</h2>
            <table id="listTable" class="table table-bordered table-hover dataTable" style="width: auto">
                <thead>
                    <tr>
                        <th style="border-color: #ddd; color: Black">OpenId
                        </th>
                        <th style="border-color: #ddd; color: Black">頭像
                        </th>
                        <th style="border-color: #ddd; color: Black">暱稱
                        </th>
                        <th style="border-color: #ddd; color: Black">性別
                        </th>
                        <th style="border-color: #ddd; color: Black">國家
                        </th>
                        <th style="border-color: #ddd; color: Black">省
                        </th>
                        <th style="border-color: #ddd; color: Black">市
                        </th>
                        <th style="border-color: #ddd; color: Black">註冊時間
                        </th>
                    </tr>
                </thead>
                <tbody>
                    <% foreach (ChannelSystem.ViewEntity.WeixinUserInfoEntity weixinUserInfo in (ViewState["WeixinUserInfoList"] as List<ChannelSystem.ViewEntity.WeixinUserInfoEntity>))
                       { %>
                    <tr>
                        <td><%= weixinUserInfo.OpenId%>
                                </td>
                        <td>
                            <img width="50px" src="<%= weixinUserInfo.HeadImgUrl%>" />
                        </td>
                        <td><%= weixinUserInfo.NickName%>
                                </td>
                        <td><%= weixinUserInfo.Sex.ToString()%>
                                </td>
                        <td><%= weixinUserInfo.Country%>
                                </td>
                        <td><%= weixinUserInfo.Province%>
                                </td>
                        <td><%= weixinUserInfo.City%>
                                </td>
                        <td><%= weixinUserInfo.SubscribeTime.ToShortDateString()%>
                                </td>
                    </tr>
                    <% } %>
                </tbody>
            </table>
        </form>
    </div>
</body>
</html>

 

後臺:

protected void Page_Load(object sender, EventArgs e)
{
    //獲取微信用戶列表數據
    ViewState["WeixinUserInfoList"] = new WeixinUserInfoBll().GetEntities();
}

上一篇,講過同步微信用戶的線程只會在這個頁面第一次打開時被調用。

 

一樣地,咱們也要建一個Index頁面做爲入口:

private readonly string Token = ConfigurationManager.AppSettings["token"];//與微信公衆帳號後臺的Token設置保持一致,區分大小寫。
protected void Page_Load(object sender, EventArgs e)
{
    string signature = Request["signature"];
    string timestamp = Request["timestamp"];
    string nonce = Request["nonce"];
    string echostr = Request["echostr"];
    if (Request.HttpMethod == "GET")
    {
        //get method - 僅在微信後臺填寫URL驗證時觸發
        if (CheckSignature.Check(signature, timestamp, nonce, Token))
        {
            WriteContent(echostr); //返回隨機字符串則表示驗證經過
        }
        else
        {
            WriteContent("failed:" + signature + "," + CheckSignature.GetSignature(timestamp, nonce, Token) + "。" +
                        "若是你在瀏覽器中看到這句話,說明此地址能夠被做爲微信公衆帳號後臺的Url,請注意保持Token一致。");
        }
        Response.End();
    }
    else
    {
        //post method - 當有用戶想公衆帳號發送消息時觸發
        if (!CheckSignature.Check(signature, timestamp, nonce, Token))
        {
            WriteContent("參數錯誤!");
            return;
        }
        //設置每一個人上下文消息儲存的最大數量,防止內存佔用過多,若是該參數小於等於0,則不限制
        var maxRecordCount = 10;
        //自定義MessageHandler,對微信請求的詳細判斷操做都在這裏面。
        var messageHandler = new CustomMessageHandler(Request.InputStream, maxRecordCount);
        try
        {
            //測試時可開啓此記錄,幫助跟蹤數據,使用前請確保App_Data文件夾存在,且有讀寫權限。
            messageHandler.RequestDocument.Save(
                Server.MapPath("~/App_Data/" + DateTime.Now.Ticks + "_Request_" +
                               messageHandler.RequestMessage.FromUserName + ".txt"));
            //執行微信處理過程
            messageHandler.Execute();
            //測試時可開啓,幫助跟蹤數據
            messageHandler.ResponseDocument.Save(
                Server.MapPath("~/App_Data/" + DateTime.Now.Ticks + "_Response_" +
                               messageHandler.ResponseMessage.ToUserName + ".txt"));
            WriteContent(messageHandler.ResponseDocument.ToString());
            return;
        }
        catch (Exception ex)
        {
            //將程序運行中發生的錯誤記錄到App_Data文件夾
            using (TextWriter tw = new StreamWriter(Server.MapPath("~/App_Data/Error_" + DateTime.Now.Ticks + ".txt")))
            {
                tw.WriteLine(ex.Message);
                tw.WriteLine(ex.InnerException.Message);
                if (messageHandler.ResponseDocument != null)
                {
                    tw.WriteLine(messageHandler.ResponseDocument.ToString());
                }
                tw.Flush();
                tw.Close();
            }
            WriteContent("");
        }
        finally
        {
            Response.End();
        }
    }
}
private void WriteContent(string str)
{
    Response.Output.Write(str);
}

 

最後整個View就以下圖:

image

 

未完待續!!!

 

 

用c#開發微信 系列彙總

相關文章
相關標籤/搜索