加入收藏 | 设为首页 | 会员中心 | 我要投稿 北几岛 (https://www.beijidao.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

[开源]微信在线信息模拟测试工具(基于Senparc.Weixin.MP开发)

发布时间:2021-08-28 05:09:15 所属栏目:大数据 来源: https://www.cnblogs.com/szw
导读:目前为止似乎还没有看到过Web版的普通消息测试工具(除了官方针对高级接口的),现有的一些桌面版的几个测试工具也都是使用XML直接请求,非常不友好,我们来尝试做一个“面向对象”操作的测试工具。 测试工具在线DEMO:http://weixin.senparc.com/SimulateTo

  目前为止似乎还没有看到过Web版的普通消息测试工具(除了官方针对高级接口的),现有的一些桌面版的几个测试工具也都是使用XML直接请求,非常不友好,我们来尝试做一个“面向对象”操作的测试工具。

  测试工具在线DEMO:http://weixin.senparc.com/SimulateTool

  Senparc.Weixin.MP是一个开源的微信SDK项目,地址:https://github.com/JeffreySu/WeiXinMPSDK (其中https://github.com/JeffreySu/WeiXinMPSDK/tree/master/Senparc.Weixin.MP.Sample 包含了本文所讲的所有源代码)

  也可以通过Nuget直接安装到项目中:https://www.nuget.org/packages/Senparc.Weixin.MP

  Senparc.Weixin.MP教程索引:http://www.cnblogs.com/szw/archive/2013/05/14/weixin-course-index.html

?

  下面大致解释一下源代码及工作原理:

一、界面

  

  界面分为4大区域:接口设置、发送参数、发送内容和接收内容

  其中接口设置用于提供类似微信公众账号后台的Url和Token的对接参数设置,指定目标服务器。

  在发送参数中,根据选择不同的消息类型,下面的参数选项会对应变化。

  发送内容显示的是提交参数之后,模拟发送到目标服务器的XML,这里摆脱了之前一些需要手动输入XML的麻烦。

  根据发送内容,在接收内容框中,显示目标服务器返回的实际内容。

二、服务器端代码

  由于使用了Senparc.Weixin.MP SDK,所有的XML生成、代理操作、XML流等操作都变得非常简单,一共只用了100多行代码就实现了XML生成及模拟发送、接收等2大块功能,这里为了让大家看得更明白,将所有代码都尽量平铺直叙,实际还可以有很多缩减或重用的地方(文件位于源代码/Senparc.Weixin.MP.Sample/Senparc.Weixin.MP.Sample/Controllers/SimulateToolController.cs):

using System;
using System.IO;
using System.Web.Mvc;
using System.Xml.Linq;
using Senparc.Weixin.MP.Agent;
using Senparc.Weixin.MP.Entities;
using Senparc.Weixin.MP.Helpers;

namespace Senparc.Weixin.MP.Sample.Controllers
{
    public class SimulateToolController : BaseController
    {
        /// <summary>
        /// 获取请求XML
        /// </summary>
        /// <returns></returns>
        private XDocument GetrequestMessaageDoc(string url,string token,RequestMsgType requestType,Event? eventType)
        {
            RequestMessageBase requestMessaage = null;
            switch (requestType)
            {
                case RequestMsgType.Text:
                    requestMessaage = new RequestMessageText()
                    {
                        Content = Request.Form["Content"],};
                    break;
                case RequestMsgType.Location:
                    requestMessaage = new RequestMessageLocation()
                    {
                        Label = Request.Form["Label"],Location_X = double.Parse(Request.Form["Location_X"]),Location_Y = double.Parse(Request.Form["Location_Y"]),Scale = int.Parse(Request.Form["Scale"])
                    };
                    break;
                case RequestMsgType.Image:
                    requestMessaage = new RequestMessageImage()
                    {
                        PicUrl = Request.Form["PicUrl"],};
                    break;
                case RequestMsgType.Voice:
                    requestMessaage = new RequestMessageVoice()
                    {
                        Format = Request.Form["Format"],Recognition = Request.Form["Recognition"],};
                    break;
                case RequestMsgType.Video:
                    requestMessaage = new RequestMessageVideo()
                    {
                        MsgId = long.Parse(Request.Form["MsgId"]),ThumbMediaId = Request.Form["ThumbMediaId"],};
                    break;
                //case RequestMsgType.Link:
                //    break;
                case RequestMsgType.Event:
                    if (eventType.HasValue)
                    {
                        RequestMessageEventBase requestMessageEvent = null;
                        switch (eventType.Value)
                        {
                            //case Event.ENTER:
                            //    break;
                            case Event.LOCATION:
                                requestMessageEvent = new RequestMessageEvent_Location()
                                {
                                    Latitude = long.Parse(Request.Form["Event.Latitude"]),Longitude = long.Parse(Request.Form["Event.Longitude"]),Precision = double.Parse(Request.Form["Event.Precision"])
                                };
                                break;
                            case Event.subscribe:
                                requestMessageEvent = new RequestMessageEvent_Subscribe()
                                {
                                    EventKey = Request.Form["Event.EventKey"]
                                };
                                break;
                            case Event.unsubscribe:
                                requestMessageEvent = new RequestMessageEvent_Unsubscribe();
                                  break;
                            case Event.CLICK:
                                requestMessageEvent = new RequestMessageEvent_Click()
                                   {
                                       EventKey = Request.Form["Event.EventKey"]
                                   };
                                break;
                            case Event.scan:
                                requestMessageEvent = new RequestMessageEvent_Scan()
                                 {
                                     EventKey = Request.Form["Event.EventKey"],Ticket = Request.Form["Event.Ticket"]
                                 }; break;
                            case Event.VIEW:
                                requestMessageEvent = new RequestMessageEvent_View()
                                 {
                                     EventKey = Request.Form["Event.EventKey"]
                                 }; break;
                            case Event.MASSSENDJOBFINISH:
                                requestMessageEvent = new RequestMessageEvent_MassSendJobFinish()
                                {
                                    FromUserName = "mphelper",//系统指定
                                    ErrorCount = int.Parse(Request.Form["Event.ErrorCount"]),FilterCount = int.Parse(Request.Form["Event.FilterCount"]),SendCount = int.Parse(Request.Form["Event.SendCount"]),Status = Request.Form["Event.Status"],TotalCount = int.Parse(Request.Form["Event.TotalCount"])
                                }; break;
                            default:
                                throw new ArgumentOutOfRangeException("eventType");
                        }
                        requestMessaage = requestMessageEvent;
                    }
                    else
                    {
                        throw new ArgumentOutOfRangeException("eventType");
                    }
                    break;
                default:
                    throw new ArgumentOutOfRangeException("requestType");
            }

            requestMessaage.CreateTime = DateTime.Now;
            requestMessaage.FromUserName = requestMessaage.FromUserName ?? "FromUserName(OpenId)";//用于区别不同的请求用户
            requestMessaage.ToUserName = "ToUserName";

            return requestMessaage.ConvertEntityToXml();
        }

        /// <summary>
        /// 默认页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            ViewData["Token"] = WeixinController.Token;
            return View();
        }

        /// <summary>
        /// 模拟发送并返回结果
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Index(string url,Event? eventType)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                var requestMessaageDoc = GetrequestMessaageDoc(url,token,requestType,eventType);
                requestMessaageDoc.Save(ms);
                ms.Seek(0,SeekOrigin.Begin);

                var responseMessageXml = MessageAgent.RequestXml(null,url,requestMessaageDoc.ToString());

                return Content(responseMessageXml);
            }
        }

        /// <summary>
        /// 返回模拟发送的XML
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetRequestMessageXml(string url,Event? eventType)
        {
            var requestMessaageDoc = GetrequestMessaageDoc(url,eventType);
            return Content(requestMessaageDoc.ToString());
        }
    }
}

  

三、View代码

  下面是MVC中View(razor)的代码(200行左右,文件位于源代码/Senparc.Weixin.MP.Sample/Senparc.Weixin.MP.Sample/Views/SimulateTool/Index.cshtml):

  1 @{
  2     ViewBag.Title = "微信消息模拟测试工具";
  3     Layout = "~/Views/Shared/_Layout.cshtml";
  4 
  5     var nonce = "JeffreySu";
  6     var timestamp = DateTime.Now.Ticks.ToString();
  7     var echostr = DateTime.Now.Ticks.ToString();
  8     var token = ViewData["Token"] as string;
  9 }
 10 @section HeaderContent
 11 {
 12     <style>
 13         .param {
 14             display: none;
 15         }
 16 
 17         .messageXmlArea  18             width 100% 19          20 
 21             .messageXmlArea textarea  22                 width 23                 height 200px 24              25 
 26         .paramAreaLeft  27             float left 28  45% 29             margin-right 6% 30          31 
 32         .paramArearight  33  34  35          36 
 37         #requestType,#eventType  38             padding 5px 39          40     </ 41     script 42         $(function () {
 43             $('#requestType).change(checkRequestType);
 44 #eventType).change(checkEventType);
 45             checkRequestType();
 46             checkEventType();
 47         });
 48 
 49          checkRequestType() {
 50             var requestType = $().val();
 51              paramId = param' + requestType;
 52 div[id^=param]).hide();
 53 # paramId).show();
 54         }
 55 
 56          checkEventType() {
 57              58              eventId event 59 div[id^=event] 60  eventId).show();
 61  62 
 63          sendMessage() {
 64              url #Url 65              token #Token 66              67              eventType  68              param  { url: url,token: token,requestType: requestType };
 69              70              eventType;
 71             //设置参数
 72             if (requestType != Event) {
 73                 $.each($( paramId).find(input), (i,item) {
 74                     param[$(item).attr(name)]  $(item).val();
 75                 });
 76             } else {
 77                 param.eventType  78  eventId).find( 79  80  81             }
 82 
 83              txtResponseMessageXML #responseMessageXML);
 84              txtRequestMessageXML #requestMessageXML 85 
 86             txtResponseMessageXML.html(载入中... 87             txtRequestMessageXML.html( 88 
 89             $.post(@Url.Action("Index"),param,1)"> (result) {
 90                 txtResponseMessageXML.html(result);
 91             });
 92 
 93 @Url.Action("GetRequestMessageXml") 94                 txtRequestMessageXML.html(result);
 95  96  97      98  99 @section Featured
100 101 
102 103 section class="content-wrapper main-content clear-fix"104     h1>消息模拟工具105     div ="clear-fix"></div106     id="simulateTool"107         ="paramAreaLeft"108             h3>接口设置109             110                 URL:@Html.TextBox("Url",Url.Action("Index","Weixin",null,"http",Request.Url.Host))br />
111                 Token:@Html.TextBox("Token",token)
112             113             >发送参数114             115                 类型:select ="requestType"116                     option value="Text">文本option117                     ="Location">地理位置118                     ="Image">图片119                     ="Voice">语音120                     ="Video">视频121                     @*="Link">连接信息>*@
122                     ="Event">事件推送123                 select124             125             126                 参数:
127                 ="paramText" class="param"128                     Content:input name="Content" 129                 130                 ="paramLocation"131                     Label:="Label" /><132                     Location_X:="Location_X" type="number" value="0" 133                     Location_Y:="Location_Y"134                     Scale:="Scale"="0" step="1" 135                 136                 ="paramImage"137                     PicUrl:="PicUrl" 138                 139                 ="paramVoice"140                     Format:="Format"="arm" 141                     Recognition:="Recognition" 142                 143                 ="paramVideo"144                     MsgId:="MsgId"="@DateTime.Now.Ticks"145                     ThumbMediaId:="ThumbMediaId" 146                 147                 @*="paramLink"148                 ="paramEvent"149                     事件类型:="eventType"150                         @*="ENTER">进入会话151                         ="LOCATION"152                         ="subscribe">订阅153                         ="unsubscribe">取消订阅154                         ="CLICK">自定义菜单点击事件155                         ="scan">二维码扫描156                         ="VIEW">URL跳转157                         ="MASSSENDJOBFINISH">事件推送群发结果158                     159                     @*="eventENTER"160                     ="eventLOCATION"161                         Latitude:="Event.Latitude"="0"162                         Longitude:="Event.Longitude"163                         Precision:="Event.Precision"164                     165                     ="eventsubscribe"166                         EventKey:="Event.EventKey" 167                     168                     ="eventunsubscribe"169                     ="eventCLICK"170                         EventKey:171                     172                     ="eventscan"173                         EventKey:174                         Ticket:="Event.Ticket" 175                     176                     ="eventVIEW"177                         EventKey:="Event.EventKey"="http://" 178                     179                     ="eventMASSSENDJOBFINISH"180                         ErrorCount:="Event.ErrorCount"181                         FilterCount:="Event.FilterCount"182                         SendCount:="Event.SendCount"183                         Status:="Event.Status"184                         TotalCount:="Event.TotalCount"185                     186                 187                 188                     type="button"="提交" onclick="sendMessage()" 189                 190             191         192         ="paramArearight"193 
194             ="messageXmlArea"195                 >发送内容(根据参数自动生成)196                 textarea ="requestMessageXML" readonly="readonly"textarea197             198             199                 >接收内容200                 ="responseMessageXML"201             202         203     204 section>

?

  因为代码已经足够简单,所以不再一一详解,如果有任何问题可以在评论里面讨论,欢迎提各种建议!

(编辑:北几岛)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读