public ActionResult MiniPost(PostModel postModel)
        {
            var ent = "";

            if (!BasicAPI.CheckSignature(postModel.Signature, postModel.Timestamp, postModel.Nonce, WeixinConfig.Token, out ent))
            {
                //return Content("参数错误!");//v0.7-
                return(new WeixinResult("参数错误!"));//v0.8+
            }

            var           encryptMsg = string.Empty;
            WeixinMessage message    = null;

            using (var streamReader = new StreamReader(Request.InputStream))
            {
                var decryptMsg = streamReader.ReadToEnd();
                message = AcceptMessageAPI.Parse(decryptMsg);
            }
            encryptMsg = new WeixinExecutor().Execute(message);

            return(new WeixinResult(encryptMsg)
            {
                ContentType = "text/xml",
                ContentEncoding = System.Text.UTF8Encoding.UTF8
            });
        }
예제 #2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="message"></param>
        /// <returns>已经打包成xml的用于回复用户的消息包</returns>
        public string Execute(WeixinMessage message)
        {
            string result     = string.Empty;
            string openId     = message.Body.FromUserName.Value;
            string myUserName = message.Body.ToUserName.Value;
            string unionId    = AdminAPI.GetUnionId(GlobalContext.AccessToken, openId);

            switch (message.Type)
            {
            //文字消息
            case WeixinMessageType.Text:
                string userMessage = message.Body.Content.Value;
                result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("欢迎使用,[openid:{0};\nunionid:{1}]\n输入了:" + userMessage, openId, unionId));
                break;

            //事件处理
            case WeixinMessageType.Event:
                DealWithEvent(message, openId, unionId, myUserName, out result);
                break;

            default:
                result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("未处理消息类型:{0}", message.Type));
                break;
            }
            return(result);
        }
예제 #3
0
        public ActionResult Post(string signature, string timestamp, string nonce, string echostr)
        {
            try
            {
                var appid     = "";
                var appsecret = "";
                if (CheckSignature(out appid, out appsecret))
                {
                    WeixinMessage message = null;
                    string        msgBody = "";
                    Stream        s       = System.Web.HttpContext.Current.Request.InputStream;
                    byte[]        b       = new byte[s.Length];
                    s.Read(b, 0, (int)s.Length);
                    msgBody = Encoding.UTF8.GetString(b);
                    if (string.IsNullOrWhiteSpace(msgBody))
                    {
                        _log.AddLog(new Log()
                        {
                            Msg = "lkpost过来的数据包:空" + msgBody.Length + DateTime.Now.ToString(), CreateTime = DateTime.Now, Ret = 0
                        });

                        return(null);
                    }
                    _log.AddLog(new Log()
                    {
                        Msg = "msgBody:" + msgBody.Length, CreateTime = DateTime.Now, Ret = 0
                    });

                    message = AcceptMessageAPI.Parse(msgBody);
                    WeiXinSdkTask _sdk     = new WeiXinSdkTask(appid, appsecret);
                    var           response = _sdk.Execute(message);//处理接收到的信息
                    _log.AddLog(new Log()
                    {
                        Msg = "response:" + response, CreateTime = DateTime.Now, Ret = 0
                    });
                    return(new ContentResult
                    {
                        Content = response,
                        ContentType = "text/xml",
                        ContentEncoding = System.Text.UTF8Encoding.UTF8
                    });
                }
                else
                {
                    _log.AddLog(new Log()
                    {
                        Msg = "lk消息真实性效验,不通过", CreateTime = DateTime.Now, Ret = 0
                    });
                }
            }
            catch (Exception ex)
            {
                _log.AddLog(new Log()
                {
                    Msg = "lk出错:" + ex.Message + DateTime.Now.ToString(), CreateTime = DateTime.Now, Ret = 0
                });
            }

            return(Content("")); //返回空串表示有响应
        }
예제 #4
0
        public ActionResult Post(string signature, string timestamp, string nonce, string echostr)
        {
            WeixinMessage message  = null;
            var           safeMode = Request.QueryString.Get("encrypt_type") == "aes";

            using (var streamReader = new StreamReader(Request.InputStream))
            {
                var decryptMsg = string.Empty;
                var msg        = streamReader.ReadToEnd();

                #region 解密
                if (safeMode)
                {
                    var msg_signature = Request.QueryString.Get("msg_signature");
                    var wxBizMsgCrypt = new WXBizMsgCrypt(WeixinConfig.Token, WeixinConfig.EncodingAESKey, WeixinConfig.AppID);
                    var ret           = wxBizMsgCrypt.DecryptMsg(msg_signature, timestamp, nonce, msg, ref decryptMsg);
                    if (ret != 0)//解密失败
                    {
                        //TODO:开发者解密失败的业务处理逻辑
                        //注意:本demo用log4net记录此信息,你可以用其他方法
                        LogWriter.Default.WriteError(string.Format("decrypt message return {0}, request body {1}", ret, msg));
                    }
                }
                else
                {
                    decryptMsg = msg;
                }
                #endregion

                message = AcceptMessageAPI.Parse(decryptMsg);
            }
            var response   = new WeixinExecutor().Execute(message);
            var encryptMsg = string.Empty;

            #region 加密
            if (safeMode)
            {
                var msg_signature = Request.QueryString.Get("msg_signature");
                var wxBizMsgCrypt = new WXBizMsgCrypt(WeixinConfig.Token, WeixinConfig.EncodingAESKey, WeixinConfig.AppID);
                var ret           = wxBizMsgCrypt.EncryptMsg(response, timestamp, nonce, ref encryptMsg);
                if (ret != 0)//加密失败
                {
                    //TODO:开发者加密失败的业务处理逻辑
                    LogWriter.Default.WriteError(string.Format("encrypt message return {0}, response body {1}", ret, response));
                }
            }
            else
            {
                encryptMsg = response;
            }
            #endregion

            return(new ContentResult
            {
                Content = encryptMsg,
                ContentType = "text/xml",
                ContentEncoding = System.Text.UTF8Encoding.UTF8
            });
        }
예제 #5
0
        public ActionResult Post(string signature, string timestamp, string nonce, string echostr)
        {
            try
            {
                if (CheckSignature(XiaoWeiXinSdkTask.Token))
                {
                    WeixinMessage message = null;
                    string        msgBody = "";
                    Stream        s       = System.Web.HttpContext.Current.Request.InputStream;
                    byte[]        b       = new byte[s.Length];
                    s.Read(b, 0, (int)s.Length);
                    msgBody = Encoding.UTF8.GetString(b);
                    if (string.IsNullOrWhiteSpace(msgBody))
                    {
                        SysLogTask.AddLog(new SysLogDto()
                        {
                            Message = "lkpost过来的数据包:空" + msgBody.Length + DateTime.Now.ToString(), Module = LogModuleEnum.WeiXin, Operator = "zl", Result = "加密失败", Type = LogTypeEnum.WeiXinREceive
                        });

                        return(null);
                    }
                    SysLogTask.AddLog(new SysLogDto()
                    {
                        Message = "msgBody:" + msgBody.Length, Module = LogModuleEnum.WeiXin, Operator = "zl", Result = "加密失败", Type = LogTypeEnum.WeiXinREceive
                    });

                    message = AcceptMessageAPI.Parse(msgBody);
                    var response = _sdk.Execute(message);//处理接收到的信息
                    SysLogTask.AddLog(new SysLogDto()
                    {
                        Message = "response:" + response, Module = LogModuleEnum.WeiXin, Operator = "zl", Result = "加密失败", Type = LogTypeEnum.WeiXinREceive
                    });
                }
                else
                {
                    SysLogTask.AddLog(new SysLogDto()
                    {
                        Message = "lk消息真实性效验,不通过", Module = LogModuleEnum.WeiXin, Operator = "zl", Result = "加密失败", Type = LogTypeEnum.WeiXinREceive
                    });
                }
            }
            catch (Exception ex)
            {
                SysLogTask.AddLog(new SysLogDto()
                {
                    Message = "lk出错:" + ex.Message + DateTime.Now.ToString(), Module = LogModuleEnum.WeiXin, Operator = "zl", Result = "加密失败", Type = LogTypeEnum.WeiXinREceive
                });
            }

            return(Content("")); //返回空串表示有响应
        }
예제 #6
0
        public ActionResult Post(string signature, string timestamp, string nonce, string echostr)
        {
            WeixinMessage message = null;

            using (var streamReader = new StreamReader(Request.InputStream))
            {
                message = AcceptMessageAPI.Parse(streamReader.ReadToEnd());
            }
            var response = new WeixinExecutor().Execute(message);

            return(new ContentResult
            {
                Content = response,
                ContentType = "text/xml",
                ContentEncoding = System.Text.UTF8Encoding.UTF8
            });
        }
예제 #7
0
        /// <summary>
        /// 解析微信服务器推送的消息
        /// http://mp.weixin.qq.com/wiki/index.php?title=%E6%8E%A5%E6%94%B6%E6%99%AE%E9%80%9A%E6%B6%88%E6%81%AF
        /// http://mp.weixin.qq.com/wiki/index.php?title=%E6%8E%A5%E6%94%B6%E4%BA%8B%E4%BB%B6%E6%8E%A8%E9%80%81
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public static WeixinMessage Parse(string message)
        {
            var msg = new WeixinMessage();

            msg.Body = new DynamicXml(message);
            string msgType = msg.Body.MsgType.Value;

            switch (msgType)
            {
            case "text":
                msg.Type = WeixinMessageType.Text;
                break;

            case "image":
                msg.Type = WeixinMessageType.Image;
                break;

            case "voice":
                msg.Type = WeixinMessageType.Voice;
                break;

            case "video":
                msg.Type = WeixinMessageType.Video;
                break;

            case "location":
                msg.Type = WeixinMessageType.Location;
                break;

            case "link":
                msg.Type = WeixinMessageType.Link;
                break;

            case "event":
                msg.Type = WeixinMessageType.Event;
                break;

            default: throw new Exception("does not support this message type:" + msgType);
            }
            return(msg);
        }
예제 #8
0
        /// <summary>
        /// 说明:带TODO字眼的代码段,需要开发者自行按照自己的业务逻辑实现
        /// </summary>
        /// <param name="message"></param>
        /// <returns>已经打包成xml的用于回复用户的消息包</returns>
        public string Execute(WeixinMessage message)
        {
            var result     = "";
            var domain     = System.Configuration.ConfigurationManager.AppSettings["Domain"];//请更改成你的域名
            var openId     = message.Body.FromUserName.Value;
            var myUserName = message.Body.ToUserName.Value;

            //这里需要调用TokenHelper获取Token的,省略了。
            switch (message.Type)
            {
            case WeixinMessageType.Text:    //文字消息
                string userMessage = message.Body.Content.Value;
                result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, "欢迎使用,您输入了:" + userMessage);
                break;

            case WeixinMessageType.Image:                     //图片消息
                string imageUrl = message.Body.PicUrl.Value;  //图片地址
                string mediaId  = message.Body.MediaId.Value; //mediaId
                result = ReplayPassiveMessageAPI.ReplayImage(openId, myUserName, mediaId);
                break;

            case WeixinMessageType.Video:    //视频消息
                #region 视频消息
            {
                var media_id       = message.Body.MediaId.Value.ToString();
                var thumb_media_id = message.Body.ThumbMediaId.Value.ToString();
                var msgId          = message.Body.MsgId.Value.ToString();
                //TODO
                result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("视频消息:openid:{0},media_id:{1},thumb_media_id:{2},msgId:{3}", openId, media_id, thumb_media_id, msgId));
            }
                #endregion
                break;

            case WeixinMessageType.Voice:    //语音消息
                #region 语音消息
            {
                var media_id = message.Body.MediaId.Value.ToString();
                var format   = message.Body.Format.Value.ToString();
                var msgId    = message.Body.MsgId.Value.ToString();
                //TODO
                result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("语音消息:openid:{0},media_id:{1},format:{2},msgId:{3}", openId, media_id, format, msgId));
            }
                #endregion
                break;

            case WeixinMessageType.Location:    //地理位置消息
                #region 地理位置消息
            {
                var location_X = message.Body.Location_X.Value.ToString();
                var location_Y = message.Body.Location_Y.Value.ToString();
                var scale      = message.Body.Scale.Value.ToString();
                var Label      = message.Body.Label.Value.ToString();
                //TODO
                result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("地理位置消息: openid:{0},Location_X:{1},Location_Y:{2},Scale:{3},label:{4}", openId, location_X, location_Y, scale, Label));
            }
                #endregion
                break;

            case WeixinMessageType.Link:    //链接消息
                #region 链接消息
            {
                var title       = message.Body.Title.Value.ToString();
                var description = message.Body.Description.Value.ToString();
                var url         = message.Body.Url.Value.ToString();
                var msgId       = message.Body.MsgId.Value.ToString();
                //TODO
                result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("openid:{0},title:{1},description:{2},url:{3},msgId:{4}", openId, title, description, url, msgId));
            }
                #endregion
                break;

            case WeixinMessageType.Event:
                string eventType = message.Body.Event.Value.ToLower();
                string eventKey  = string.Empty;
                try
                {
                    eventKey = message.Body.EventKey.Value;
                }
                catch { }
                switch (eventType)
                {
                case "subscribe":        //用户未关注时,进行关注后的事件推送
                    #region 首次关注
                    if (!string.IsNullOrEmpty(eventKey))
                    {
                        var qrscene = eventKey.Replace("qrscene_", "");        //此为场景二维码的场景值
                        result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, "欢迎订阅,场景值:" + qrscene);
                    }
                    else
                    {
                        result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, "欢迎订阅");
                    }

                    #endregion
                    break;

                case "unsubscribe":        //取消关注
                    #region 取消关注
                    result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, "欢迎再来");
                    #endregion
                    break;

                case "scan":        // 用户已关注时的事件推送
                    #region 已关注扫码事件
                    if (!string.IsNullOrEmpty(eventKey))
                    {
                        var qrscene = eventKey.Replace("qrscene_", "");        //此为场景二维码的场景值
                        result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, "欢迎使用,场景值:" + qrscene);
                    }
                    else
                    {
                        result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, "欢迎使用");
                    }
                    #endregion
                    break;

                case "masssendjobfinish":        //事件推送群发结果,
                    #region 事件推送群发结果
                {
                    var msgId     = message.Body.MsgID;
                    var msgStatus = message.Body.Status;            //“send success”或“send fail”或“err(num)”
                    //send success时,也有可能因用户拒收公众号的消息、系统错误等原因造成少量用户接收失败。
                    //err(num)是审核失败的具体原因,可能的情况如下:err(10001)涉嫌广告, err(20001)涉嫌政治, err(20004)涉嫌社会, err(20002)涉嫌色情, err(20006)涉嫌违法犯罪,
                    //err(20008)涉嫌欺诈, err(20013)涉嫌版权, err(22000)涉嫌互推(互相宣传), err(21000)涉嫌其他
                    var totalCount  = message.Body.TotalCount;         //group_id下粉丝数;或者openid_list中的粉丝数
                    var filterCount = message.Body.FilterCount;        //过滤(过滤是指特定地区、性别的过滤、用户设置拒收的过滤,用户接收已超4条的过滤)后,准备发送的粉丝数,原则上,FilterCount = SentCount + ErrorCount
                    var sentCount   = message.Body.SentCount;          //发送成功的粉丝数
                    var errorCount  = message.Body.FilterCount;        //发送失败的粉丝数
                    //TODO:开发者自己的处理逻辑,这里用log4net记录日志
                    LogWriter.Default.WriteInfo(string.Format("mass send job finishe,msgId:{0},msgStatus:{1},totalCount:{2},filterCount:{3},sentCount:{4},errorCount:{5}", msgId, msgStatus, totalCount, filterCount, sentCount, errorCount));
                }
                    #endregion
                    break;

                case "templatesendjobfinish":        //模版消息结果,
                    #region 模版消息结果
                {
                    var msgId     = message.Body.MsgID;
                    var msgStatus = message.Body.Status;            //发送状态为成功: success; 用户拒绝接收:failed:user block; 发送状态为发送失败(非用户拒绝):failed: system failed
                    //TODO:开发者自己的处理逻辑,这里用log4net记录日志
                    LogWriter.Default.WriteInfo(string.Format("template send job finish,msgId:{0},msgStatus:{1}", msgId, msgStatus));
                }
                    #endregion
                    break;

                case "location":        //上报地理位置事件
                    #region  报地理位置事件
                    var lat = message.Body.Latitude.Value.ToString();
                    var lng = message.Body.Longitude.Value.ToString();
                    var pcn = message.Body.Precision.Value.ToString();
                    //TODO:在此处将经纬度记录在数据库,这里用log4net记录日志
                    LogWriter.Default.WriteInfo(string.Format("openid:{0} ,location,lat:{1},lng:{21},pcn:{3}", openId, lat, lng, pcn));
                    #endregion
                    break;

                case "voice":        //语音消息
                    #region 语音消息
                    //A:已开通语音识别权限的公众号
                    var userVoice = message.Body.Recognition.Value;        //用户语音消息文字
                    result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, "您说:" + userVoice);

                    //B:未开通语音识别权限的公众号
                    var userVoiceMediaId = message.Body.MediaId.Value;        //media_id
                    //TODO:调用自定义的语音识别程序识别用户语义

                    #endregion
                    break;

                case "image":                                  //图片消息
                    #region 图片消息
                    var userImage = message.Body.PicUrl.Value; //用户语音消息文字
                    result = ReplayPassiveMessageAPI.RepayNews(openId, myUserName, new WeixinNews
                    {
                        title       = "您刚才发送了图片消息",
                        picurl      = string.Format("{0}/Images/ad.jpg", domain),
                        description = "点击查看图片",
                        url         = userImage
                    });
                    #endregion
                    break;

                case "click":        //自定义菜单事件
                    #region 自定义菜单事件
                {
                    switch (eventKey)
                    {
                    case "myaccount":                //CLICK类型事件举例
                        #region 我的账户
                        result = ReplayPassiveMessageAPI.RepayNews(openId, myUserName, new List <WeixinNews>()
                            {
                                new WeixinNews {
                                    title       = "我的帐户",
                                    url         = string.Format("{0}/user?openId={1}", domain, openId),
                                    description = "点击查看帐户详情",
                                    picurl      = string.Format("{0}/Images/ad.jpg", domain)
                                },
                            });
                        #endregion
                        break;

                    case "www.weixinsdk.net":                //VIEW类型事件举例,注意:点击菜单弹出子菜单,不会产生上报。
                        //TODO:后台处理逻辑
                        break;

                    default:
                        result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, "没有响应菜单事件");
                        break;
                    }
                }
                    #endregion
                    break;

                case "view":        //点击菜单跳转链接时的事件推送
                    #region 点击菜单跳转链接时的事件推送
                    result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("您将跳转至:{0}", eventKey));
                    #endregion
                    break;

                case "scancode_push":                                      //扫码推事件的事件推送
                {
                    var scanType   = message.Body.ScanCodeInfo.ScanType;   //扫描类型,一般是qrcode
                    var scanResult = message.Body.ScanCodeInfo.ScanResult; //扫描结果,即二维码对应的字符串信息
                    result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("您扫描了二维码,scanType:{0},scanResult:{1},EventKey:{2}", scanType, scanResult, eventKey));
                }
                break;

                case "scancode_waitmsg":                                   //扫码推事件且弹出“消息接收中”提示框的事件推送
                {
                    var scanType   = message.Body.ScanCodeInfo.ScanType;   //扫描类型,一般是qrcode
                    var scanResult = message.Body.ScanCodeInfo.ScanResult; //扫描结果,即二维码对应的字符串信息
                    result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("您扫描了二维码,scanType:{0},scanResult:{1},EventKey:{2}", scanType, scanResult, eventKey));
                }
                break;

                case "pic_sysphoto":                               //弹出系统拍照发图的事件推送
                {
                    var count   = message.Body.SendPicsInfo.Count; //发送的图片数量
                    var picList = message.Body.PicList;            //发送的图片信息
                    result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("弹出系统拍照发图,count:{0},EventKey:{1}", count, eventKey));
                }
                break;

                case "pic_photo_or_album":                         //弹出拍照或者相册发图的事件推送
                {
                    var count   = message.Body.SendPicsInfo.Count; //发送的图片数量
                    var picList = message.Body.PicList;            //发送的图片信息
                    result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("弹出拍照或者相册发图,count:{0},EventKey:{1}", count, eventKey));
                }
                break;

                case "pic_weixin":                                 //弹出微信相册发图器的事件推送
                {
                    var count   = message.Body.SendPicsInfo.Count; //发送的图片数量
                    var picList = message.Body.PicList;            //发送的图片信息
                    result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("弹出微信相册发图器,count:{0},EventKey:{1}", count, eventKey));
                }
                break;

                case "location_select":                                        //弹出地理位置选择器的事件推送
                {
                    var location_X = message.Body.SendLocationInfo.Location_X; //X坐标信息
                    var location_Y = message.Body.SendLocationInfo.Location_Y; //Y坐标信息
                    var scale      = message.Body.SendLocationInfo.Scale;      //精度,可理解为精度或者比例尺、越精细的话 scale越高
                    var label      = message.Body.SendLocationInfo.Label;      //地理位置的字符串信息
                    var poiname    = message.Body.SendLocationInfo.Poiname;    //朋友圈POI的名字,可能为空
                    result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("弹出地理位置选择器,location_X:{0},location_Y:{1},scale:{2},label:{3},poiname:{4},eventKey:{5}", location_X, location_Y, scale, label, poiname, eventKey));
                }
                break;
                }
                break;

            default:
                result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("未处理消息类型:{0}", message.Type));
                break;
            }
            return(result);
        }
        public ActionResult Post(PostModel postModel)
        {
            postModel.Token = WeixinConfig.Token;
            //postModel.EncodingAESKey = WeixinConfig.EncodingAESKey;
            postModel.AppId = WeixinConfig.AppID;

            var ent = "";

            if (!BasicAPI.CheckSignature(postModel.Signature, postModel.Timestamp, postModel.Nonce, WeixinConfig.Token, out ent))
            {
                return(Content("参数错误!"));
            }

            var           encryptMsg = string.Empty;
            WeixinMessage message    = null;
            var           safeMode   = Request.QueryString.Get("encrypt_type") == "aes";

            using (var streamReader = new StreamReader(Request.InputStream))
            {
                var decryptMsg = string.Empty;
                var msg        = streamReader.ReadToEnd();

                #region 解密
                if (safeMode)
                {
                    var msg_signature = Request.QueryString.Get("msg_signature");
                    var wxBizMsgCrypt = new WXBizMsgCrypt(WeixinConfig.Token, WeixinConfig.EncodingAESKey, WeixinConfig.AppID);
                    var ret           = wxBizMsgCrypt.DecryptMsg(msg_signature, postModel.Timestamp, postModel.Nonce, msg, ref decryptMsg);
                    if (ret != 0)//解密失败
                    {
                        //TODO:开发者解密失败的业务处理逻辑
                        Log.Instence.LogWriteLine(string.Format("decrypt message return {0}, request body {1}", ret, msg));
                    }
                }
                else
                {
                    decryptMsg = msg;
                }
                #endregion

                message = AcceptMessageAPI.Parse(decryptMsg);
            }

            var response = new WeixinExecutor().Execute(message);

            #region 加密
            if (safeMode)
            {
                var msg_signature = Request.QueryString.Get("msg_signature");
                var wxBizMsgCrypt = new WXBizMsgCrypt(WeixinConfig.Token, WeixinConfig.EncodingAESKey, WeixinConfig.AppID);
                var ret           = wxBizMsgCrypt.EncryptMsg(response, postModel.Timestamp, postModel.Nonce, ref encryptMsg);
                if (ret != 0)//加密失败
                {
                    //TODO:开发者加密失败的业务处理逻辑
                    Log.Instence.LogWriteLine(string.Format("encrypt message return {0}, response body {1}", ret, response));
                }
            }
            else
            {
                encryptMsg = response;
            }
            #endregion
            return(new ContentResult
            {
                Content = encryptMsg,
                ContentType = "text/xml",
                ContentEncoding = System.Text.UTF8Encoding.UTF8
            });
        }
예제 #10
0
        /// <summary>
        /// 说明:带TODO字眼的代码段,需要开发者自行按照自己的业务逻辑实现
        /// </summary>
        /// <param name="message"></param>
        /// <returns>已经打包成xml的用于回复用户的消息包</returns>
        public string Execute(WeixinMessage message)
        {
            var result     = "";
            var openId     = message.Body.FromUserName.Value;
            var myUserName = message.Body.ToUserName.Value;

            //这里需要调用TokenHelper获取Token的,省略了。

            #region 记录接收信息
            var receiveMessage = new WeiXinReceiveMessage()
            {
                ToUserName   = myUserName,
                FromUserName = openId,
                CreateDate   = DateTime.Now,
                CreateTime   = message.Body.CreateTime.Value,
                MsgType      = message.Body.MsgType.Value,
                MsgId        = message.Type == WeixinMessageType.Event ? "" : message.Body.MsgId.Value //事件没有这个参数
            };
            #endregion
            switch (message.Type)
            {
            case WeixinMessageType.Text:    //文字消息
                #region 文字消息
                string userMessage = message.Body.Content.Value;
                receiveMessage.Content = userMessage;                          //用于记录接收信息
                var reply = _replyMessage.GetMessage(userMessage, myUserName); //查找回复信息表
                result = Repay(reply, openId, myUserName);
                #endregion
                break;

            case WeixinMessageType.Image:                     //图片消息
                #region 图片消息
                string imageUrl = message.Body.PicUrl.Value;  //图片地址
                string mediaId  = message.Body.MediaId.Value; //mediaId
                receiveMessage.PicUrl  = imageUrl;
                receiveMessage.MediaId = mediaId;
                #endregion
                break;

            case WeixinMessageType.Video:    //视频消息
                #region 视频消息
            {
                var media_id       = message.Body.MediaId.Value.ToString();
                var thumb_media_id = message.Body.ThumbMediaId.Value.ToString();
                receiveMessage.MediaId      = media_id;
                receiveMessage.ThumbMediaId = thumb_media_id;
            }
                #endregion
                break;

            case WeixinMessageType.Voice:    //语音消息
                #region 语音消息
            {
                var media_id = message.Body.MediaId.Value.ToString();
                var format   = message.Body.Format.Value.ToString();
                receiveMessage.MediaId = media_id;
                receiveMessage.Format  = format;
            }
                #endregion
                break;

            case WeixinMessageType.Location:    //地理位置消息
                #region 地理位置消息
            {
                var location_X = message.Body.Location_X.Value.ToString();
                var location_Y = message.Body.Location_Y.Value.ToString();
                var scale      = message.Body.Scale.Value.ToString();
                var Label      = message.Body.Label.Value.ToString();
                receiveMessage.Location_X = location_X;
                receiveMessage.Location_Y = location_Y;
                receiveMessage.Scale      = scale;
                receiveMessage.Label      = Label;
            }
                #endregion
                break;

            case WeixinMessageType.Link:    //链接消息
                #region 链接消息
            {
                var title       = message.Body.Title.Value.ToString();
                var description = message.Body.Description.Value.ToString();
                var url         = message.Body.Url.Value.ToString();
                receiveMessage.Title       = title;
                receiveMessage.Description = description;
                receiveMessage.Url         = url;
            }
                #endregion
                break;

            case WeixinMessageType.Event:
                #region 事件
                string eventType = message.Body.Event.Value.ToLower();
                string eventKey  = string.Empty;
                try
                {
                    eventKey = message.Body.EventKey.Value;
                }
                catch { }
                receiveMessage.EventType = eventType;
                receiveMessage.EventKey  = eventKey;
                switch (eventType)
                {
                case "subscribe":        //用户未关注时,进行关注后的事件推送
                    #region 首次关注

                    //TODO: 获取用户基本信息后,将用户信息存储在本地。
                    var weixinInfo  = UserAdminAPI.GetInfo(AccountToken(), openId);           //注意:订阅号没有此权限
                    var userinfoDto = JsonConvert.DeserializeObject <WeiXinUserDto>(JsonConvert.SerializeObject(weixinInfo));
                    var userinfo    = EntityMapper.Map <WeiXinUserDto, WeiXinUser>(userinfoDto);
                    userinfo.createtime = DateTime.Now;
                    if (_userTask.GetByOpenId(openId) == null)
                    {
                        _userTask.AddUser(userinfo);                                                //保存用户关注数据
                    }
                    reply  = _replyMessage.GetMessageByReplayType(eventType, eventKey, myUserName); //查找回复信息表
                    result = Repay(reply, openId, myUserName);
                    #endregion
                    break;

                case "unsubscribe":        //取消关注
                    #region 取消关注
                    result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, "欢迎再来");
                    #endregion
                    break;

                case "scan":        // 用户已关注时的事件推送
                    #region 已关注扫码事件
                    if (!string.IsNullOrEmpty(eventKey))
                    {
                        var qrscene = eventKey.Replace("qrscene_", "");        //此为场景二维码的场景值
                        result = ReplayPassiveMessageAPI.RepayNews(openId, myUserName,
                                                                   new WeixinNews
                        {
                            title       = "欢迎使用,场景值:" + qrscene,
                            description = "欢迎使用,场景值:" + qrscene,
                            picurl      = string.Format("{0}/ad.jpg", domain),
                            url         = domain
                        });
                    }
                    else
                    {
                        result = ReplayPassiveMessageAPI.RepayNews(openId, myUserName,
                                                                   new WeixinNews
                        {
                            title       = "欢迎使用",
                            description = "欢迎订阅,点击此消息查看在线demo",
                            picurl      = string.Format("{0}/ad.jpg", domain),
                            url         = domain
                        });
                    }
                    #endregion
                    break;

                case "masssendjobfinish":        //事件推送群发结果,
                    #region 事件推送群发结果
                {
                    var msgId     = message.Body.MsgID.Value;
                    var msgStatus = message.Body.Status.Value;            //“send success”或“send fail”或“err(num)”
                    //send success时,也有可能因用户拒收公众号的消息、系统错误等原因造成少量用户接收失败。
                    //err(num)是审核失败的具体原因,可能的情况如下:err(10001)涉嫌广告, err(20001)涉嫌政治, err(20004)涉嫌社会, err(20002)涉嫌色情, err(20006)涉嫌违法犯罪,
                    //err(20008)涉嫌欺诈, err(20013)涉嫌版权, err(22000)涉嫌互推(互相宣传), err(21000)涉嫌其他
                    var totalCount  = message.Body.TotalCount.Value;         //group_id下粉丝数;或者openid_list中的粉丝数
                    var filterCount = message.Body.FilterCount.Value;        //过滤(过滤是指特定地区、性别的过滤、用户设置拒收的过滤,用户接收已超4条的过滤)后,准备发送的粉丝数,原则上,FilterCount = SentCount + ErrorCount
                    var sentCount   = message.Body.SentCount.Value;          //发送成功的粉丝数
                    var errorCount  = message.Body.FilterCount.Value;        //发送失败的粉丝数
                    //TODO:开发者自己的处理逻辑,这里用log4net记录日志
                    // LogWriter.Default.WriteInfo(string.Format("mass send job finishe,msgId:{0},msgStatus:{1},totalCount:{2},filterCount:{3},sentCount:{4},errorCount:{5}", msgId, msgStatus, totalCount, filterCount, sentCount, errorCount));
                }
                    #endregion
                    break;

                case "templatesendjobfinish":        //模版消息结果,
                    #region 模版消息结果
                {
                    var msgId     = message.Body.MsgID.Value;
                    var msgStatus = message.Body.Status.Value;            //发送状态为成功: success; 用户拒绝接收:failed:user block; 发送状态为发送失败(非用户拒绝):failed: system failed
                    //TODO:开发者自己的处理逻辑,这里用log4net记录日志
                    //LogWriter.Default.WriteInfo(string.Format("template send job finish,msgId:{0},msgStatus:{1}", msgId, msgStatus));
                }
                    #endregion
                    break;

                case "location":        //上报地理位置事件
                    #region  报地理位置事件
                    var lat = message.Body.Latitude.Value.ToString();
                    var lng = message.Body.Longitude.Value.ToString();
                    var pcn = message.Body.Precision.Value.ToString();
                    //TODO:在此处将经纬度记录在数据库,这里用log4net记录日志
                    // LogWriter.Default.WriteInfo(string.Format("openid:{0} ,location,lat:{1},lng:{2},pcn:{3}", openId, lat, lng, pcn));
                    #endregion
                    break;

                case "voice":        //语音消息
                    #region 语音消息
                    //A:已开通语音识别权限的公众号
                    var userVoice = message.Body.Recognition.Value;        //用户语音消息文字
                    result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, "您说:" + userVoice);

                    //B:未开通语音识别权限的公众号
                    var userVoiceMediaId = message.Body.MediaId.Value;        //media_id
                    //TODO:调用自定义的语音识别程序识别用户语义

                    #endregion
                    break;

                case "image":                                  //图片消息
                    #region 图片消息
                    var userImage = message.Body.PicUrl.Value; //用户语音消息文字
                    result = ReplayPassiveMessageAPI.RepayNews(openId, myUserName, new WeixinNews
                    {
                        title       = "您刚才发送了图片消息",
                        picurl      = string.Format("{0}/Images/ad.jpg", domain),
                        description = "点击查看图片",
                        url         = userImage
                    });
                    #endregion
                    break;

                case "click":        //自定义菜单事件
                    #region 自定义菜单事件
                {
                    reply  = _replyMessage.GetMessageByReplayType(eventType, eventKey, myUserName);            //查找回复信息表
                    result = Repay(reply, openId, myUserName);
                }
                    #endregion
                    break;

                case "view":        //点击菜单跳转链接时的事件推送
                    #region 点击菜单跳转链接时的事件推送
                    result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("您将跳转至:{0}", eventKey));
                    #endregion
                    break;

                    #region 仅支持微信iPhone5.4.1以上版本,和Android5.4以上版本的微信用户,旧版本微信用户点击后将没有回应,开发者也不能正常接收到事件推送
                case "scancode_push":                                            //扫码推事件的事件推送
                {
                    var scanType   = message.Body.ScanCodeInfo.ScanType.Value;   //扫描类型,一般是qrcode
                    var scanResult = message.Body.ScanCodeInfo.ScanResult.Value; //扫描结果,即二维码对应的字符串信息
                    result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("您扫描了二维码,scanType:{0},scanResult:{1},EventKey:{2}", scanType, scanResult, eventKey));
                }
                break;

                case "scancode_waitmsg":                                         //扫码推事件且弹出“消息接收中”提示框的事件推送
                {
                    var scanType   = message.Body.ScanCodeInfo.ScanType.Value;   //扫描类型,一般是qrcode
                    var scanResult = message.Body.ScanCodeInfo.ScanResult.Value; //扫描结果,即二维码对应的字符串信息
                    result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("您扫描了二维码,scanType:{0},scanResult:{1},EventKey:{2}", scanType, scanResult, eventKey));
                }
                break;

                case "pic_sysphoto":                               //弹出系统拍照发图的事件推送
                {
                    var count   = message.Body.SendPicsInfo.Count; //发送的图片数量
                    var picList = message.Body.PicList;            //发送的图片信息
                    result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("弹出系统拍照发图,count:{0},EventKey:{1}", count, eventKey));
                }
                break;

                case "pic_photo_or_album":                               //弹出拍照或者相册发图的事件推送
                {
                    var count   = message.Body.SendPicsInfo.Count.Value; //发送的图片数量
                    var picList = message.Body.PicList.Value;            //发送的图片信息
                    result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("弹出拍照或者相册发图,count:{0},EventKey:{1}", count, eventKey));
                }
                break;

                case "pic_weixin":                                       //弹出微信相册发图器的事件推送
                {
                    var count   = message.Body.SendPicsInfo.Count.Value; //发送的图片数量
                    var picList = message.Body.PicList.Value;            //发送的图片信息
                    result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("弹出微信相册发图器,count:{0},EventKey:{1}", count, eventKey));
                }
                break;

                case "location_select":                                              //弹出地理位置选择器的事件推送
                {
                    var location_X = message.Body.SendLocationInfo.Location_X.Value; //X坐标信息
                    var location_Y = message.Body.SendLocationInfo.Location_Y.Value; //Y坐标信息
                    var scale      = message.Body.SendLocationInfo.Scale.Value;      //精度,可理解为精度或者比例尺、越精细的话 scale越高
                    var label      = message.Body.SendLocationInfo.Label.Value;      //地理位置的字符串信息
                    var poiname    = message.Body.SendLocationInfo.Poiname.Value;    //朋友圈POI的名字,可能为空
                    result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("弹出地理位置选择器,location_X:{0},location_Y:{1},scale:{2},label:{3},poiname:{4},eventKey:{5}", location_X, location_Y, scale, label, poiname, eventKey));
                }
                break;

                case "card_pass_check":                     //生成的卡券通过审核时,微信会把这个事件推送到开发者填写的URL。
                {
                    var cardid = message.Body.CardId.Value; //CardId
                    result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("您的卡券已经通过审核"));
                }
                break;

                case "card_not_pass_check":                 //生成的卡券未通过审核时,微信会把这个事件推送到开发者填写的URL。
                {
                    var cardid = message.Body.CardId.Value; //CardId
                }
                break;

                case "user_get_card":                                       //用户在领取卡券时,微信会把这个事件推送到开发者填写的URL。
                {
                    var cardid         = message.Body.CardId.Value;         //CardId
                    var isGiveByFriend = message.Body.IsGiveByFriend.Value; //是否为转赠,1代表是,0代表否。
                    var fromUserName   = message.Body.FromUserName.Value;   //领券方帐号(一个OpenID)
                    var friendUserName = message.Body.FriendUserName.Value; //赠送方账号(一个OpenID),"IsGiveByFriend”为1时填写该参数。
                    var userCardCode   = message.Body.UserCardCode.Value;   //code序列号。自定义code及非自定义code的卡券被领取后都支持事件推送。
                    var outerId        = message.Body.OuterId.Value;        //领取场景值,用于领取渠道数据统计。可在生成二维码接口及添加JSAPI接口中自定义该字段的整型值。
                }
                break;

                case "user_del_card":                                   //用户在删除卡券时,微信会把这个事件推送到开发者填写的URL
                {
                    var cardid       = message.Body.CardId.Value;       //CardId
                    var userCardCode = message.Body.UserCardCode.Value; //商户自定义code值。非自定code推送为空
                }
                break;

                case "merchant_order":                                //微信小店:订单付款通知:在用户在微信中付款成功后,微信服务器会将订单付款通知推送到开发者在公众平台网站中设置的回调URL(在开发模式中设置)中,如未设置回调URL,则获取不到该事件推送。
                {
                    var orderId     = message.Body.OrderId.Value;     //CardId
                    var orderStatus = message.Body.OrderStatus.Value; //OrderStatus
                    var productId   = message.Body.ProductId.Value;   //ProductId
                    var skuInfo     = message.Body.SkuInfo.Value;     //SkuInfo
                }
                break;
                    #endregion
                }
                #endregion
                break;

            default:
                result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("未处理消息类型:{0}", message.Type));
                break;
            }
            _receiveMessage.AddMessage(receiveMessage);
            return(result);
        }
예제 #11
0
        public ActionResult Post(string signature, string timestamp, string nonce, string echostr)
        {
            WeixinMessage message  = null;
            var           safeMode = Request.QueryString.Get("encrypt_type") == "aes";

            using (var streamReader = new StreamReader(Request.InputStream))
            {
                var decryptMsg = string.Empty;
                var msg        = streamReader.ReadToEnd();

                #region 解密
                if (safeMode)
                {
                    var msg_signature = Request.QueryString.Get("msg_signature");
                    var wxBizMsgCrypt = new WXBizMsgCrypt(WeiXinSdkTask.Token, WeiXinSdkTask.appsecret, WeiXinSdkTask.appID);
                    var ret           = wxBizMsgCrypt.DecryptMsg(msg_signature, timestamp, nonce, msg, ref decryptMsg);
                    if (ret != 0)//解密失败
                    {
                        SysLogTask.AddLog(new SysLogDto()
                        {
                            Message = "message:" + ret + "request:" + msg, Module = LogModuleEnum.WeiXin, Operator = "zl", Result = "解密失败", Type = LogTypeEnum.WeiXinREceive
                        });
                    }
                }
                else
                {
                    decryptMsg = msg;
                }
                #endregion

                message = AcceptMessageAPI.Parse(decryptMsg);
            }
            var response   = _sdk.Execute(message);//处理接收到的信息
            var encryptMsg = string.Empty;
            #region 加密
            if (safeMode)
            {
                var msg_signature = Request.QueryString.Get("msg_signature");
                var wxBizMsgCrypt = new WXBizMsgCrypt(WeiXinSdkTask.Token, WeiXinSdkTask.appsecret, WeiXinSdkTask.appID);
                var ret           = wxBizMsgCrypt.EncryptMsg(response, timestamp, nonce, ref encryptMsg);
                if (ret != 0)//加密失败
                {
                    SysLogTask.AddLog(new SysLogDto()
                    {
                        Message = "message:" + ret + "response:" + response, Module = LogModuleEnum.WeiXin, Operator = "zl", Result = "加密失败", Type = LogTypeEnum.WeiXinREceive
                    });
                }
            }
            else
            {
                encryptMsg = response;
            }
            #endregion

            return(new ContentResult
            {
                Content = encryptMsg,
                ContentType = "text/xml",
                ContentEncoding = System.Text.UTF8Encoding.UTF8
            });
        }
예제 #12
0
        private void DealWithEvent(WeixinMessage message, string openId, string unionId, string myUserName, out string result)
        {
            string eventType = message.Body.Event.Value.ToLower();
            string eventKey  = string.Empty;

            try
            {
                eventKey = message.Body.EventKey.Value;
            }
            catch { }
            switch (eventType)
            {
            case "subscribe":    //用户未关注时,进行关注后的事件推送
                #region 首次关注

                //TODO: 获取用户基本信息后,将用户信息存储在本地。
                //var token = WeixinConfig.TokenHelper.GetToken();
                //var weixinInfo = UserAdminAPI.GetInfo(token, openId);//注意:订阅号没有此权限

                if (!string.IsNullOrEmpty(eventKey))
                {
                    var qrscene = eventKey.Replace("qrscene_", "");    //此为场景二维码的场景值
                    result = ReplayPassiveMessageAPI.RepayNews(openId, myUserName,
                                                               new WeixinNews
                    {
                        title       = "欢迎订阅01World,场景值:" + qrscene,
                        description = "欢迎订阅01World,场景值:" + qrscene,
                        picurl      = string.Format("{0}/resource/Content/images/usericof.png", GlobalContext.Domain),
                        url         = string.Format("{0}?unionId={1}", GlobalContext.Domain, unionId)
                    });
                }
                else
                {
                    result = ReplayPassiveMessageAPI.RepayNews(openId, myUserName,
                                                               new WeixinNews
                    {
                        title       = "欢迎订阅01World",
                        description = "欢迎订阅01World",
                        picurl      = string.Format("{0}/resource/Content/images/usericof.png", GlobalContext.Domain),
                        url         = string.Format("{0}?unionId={1}", GlobalContext.Domain, unionId)
                    });
                }
                #endregion
                break;

            case "unsubscribe":    //取消关注
                #region 取消关注
                result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, "欢迎再来");
                #endregion
                break;

            case "click":    //自定义菜单事件
                #region 自定义菜单事件
            {
                switch (eventKey)
                {
                case "V1001_Hello":
                    #region Hello
                    result = ReplayPassiveMessageAPI.RepayNews(openId, myUserName, new List <WeixinNews>()
                        {
                            new WeixinNews {
                                title       = "欢迎关注本公众号",
                                url         = string.Format("{0}?unionId={1}", GlobalContext.Domain, unionId),
                                description = "点击进入01world",
                                picurl      = string.Format("{0}/resource/Content/images/usericof.png", GlobalContext.Domain)
                            },
                        });
                    #endregion
                    break;

                case "V1001_My01":
                    #region 我的01
                    result = ReplayPassiveMessageAPI.RepayNews(openId, myUserName, new List <WeixinNews>()
                        {
                            new WeixinNews {
                                title       = "我的01",
                                url         = string.Format("{0}/My01/My01?unionId={1}", GlobalContext.Domain, unionId),
                                description = "我的余额:" + GetYE() + ";\n点击查看帐户详情",
                                picurl      = string.Format("{0}/resource/Content/images/usericof.png", GlobalContext.Domain)
                            },
                        });
                    #endregion
                    break;

                case "V1001_Binding":
                    #region 绑定账号
                    result = ReplayPassiveMessageAPI.RepayNews(openId, myUserName, new List <WeixinNews>()
                        {
                            new WeixinNews {
                                title       = "绑定01world账号",
                                url         = string.Format("{0}/User/WeixinBind?unionId={1}", GlobalContext.Domain, unionId),
                                description = "点击绑定01world账号",
                                picurl      = string.Format("{0}/resource/Content/images/usericof.png", GlobalContext.Domain)
                            },
                        });
                    #endregion
                    break;

                default:
                    result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, "没有响应菜单事件");
                    break;
                }
            }
                #endregion
                break;

            case "view":    //点击菜单跳转链接时的事件推送
                #region 点击菜单跳转链接时的事件推送
                result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("您将跳转至:{0}", eventKey));
                #endregion
                break;

            default:
                result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, "没有响应菜单事件");
                break;
            }
        }
예제 #13
0
        public string Execute(WeixinMessage message)
        {
            var    result     = "";
            string openId     = message.Body.FromUserName.Value;
            var    myUserName = message.Body.ToUserName.Value;

            //这里需要调用TokenHelper获取Token的,省略了。
            switch (message.Type)
            {
            case WeixinMessageType.Text:
                string userMessage = message.Body.Content.Value;
                result = RepayText(openId, myUserName, "欢迎使用");
                break;

            case WeixinMessageType.Event:
                string eventType = message.Body.Event.Value.ToLower();
                string eventKey  = message.Body.EventKey.Value;
                switch (eventType)
                {
                case "subscribe":
                    result = RepayText(openId, myUserName, "欢迎订阅");
                    break;

                case "unsubscribe":
                    result = RepayText(openId, myUserName, "欢迎再来");
                    break;

                case "scan":
                    result = RepayText(openId, myUserName, "欢迎使用");
                    break;

                case "location":        //用户进入应用时记录用户地理位置
                    #region location
                    var lat = message.Body.Latitude.Value.ToString();
                    var lng = message.Body.Longitude.Value.ToString();
                    var pcn = message.Body.Precision.Value.ToString();
                    //在此处将经纬度记录在数据库
                    #endregion
                    break;

                case "click":
                    switch (eventKey)        //refer to: Recources/menu.json
                    {
                    case "myaccount":
                        #region 我的账户
                        result = RepayText(openId, myUserName, "我的账户.");
                        #endregion
                        break;

                    default:
                        result = string.Format("<xml><ToUserName><![CDATA[{0}]]></ToUserName>" +
                                               "<FromUserName><![CDATA[{1}]]></FromUserName>" +
                                               "<CreateTime>{2}</CreateTime>" +
                                               "<MsgType><![CDATA[text]]></MsgType>" +
                                               "<Content><![CDATA[{3}]]></Content>" + "</xml>",
                                               openId, myUserName, DateTime.Now.ToBinary(), "没有响应菜单事件");
                        break;
                    }
                    break;
                }
                break;

            default:
                result = string.Format("<xml><ToUserName><![CDATA[{0}]]></ToUserName>" +
                                       "<FromUserName><![CDATA[{1}]]></FromUserName>" +
                                       "<CreateTime>{2}</CreateTime>" +
                                       "<MsgType><![CDATA[text]]></MsgType>" +
                                       "<Content><![CDATA[{3}]]></Content>" + "</xml>",
                                       openId, myUserName, DateTime.Now.ToBinary(), string.Format("未处理消息类型:{0}", message.Type));
                break;
            }
            return(result);
        }
        public string HandleMessage(WeixinMessage message)
        {
            var result     = "";
            var openId     = message.Body.FromUserName.Value;
            var myUserName = message.Body.ToUserName.Value;
            var domain     = "";

            //这里需要调用TokenHelper获取Token的,省略了。
            switch (message.Type)
            {
            case WeixinMessageType.Text:    //文字消息
                string userMessage = message.Body.Content.Value;
                result = ReplayMessageApi.RepayText(openId, myUserName, " 晚安家纺欢迎您 ");
                break;

            case WeixinMessageType.Image:                     //图片消息
                string imageUrl = message.Body.PicUrl.Value;  //图片地址
                string mediaId  = message.Body.MediaId.Value; //mediaId
                result = ReplayMessageApi.ReplayImage(openId, myUserName, mediaId);
                break;

            case WeixinMessageType.Video:    //视频消息
                #region 视频消息
            {
                var media_id       = message.Body.MediaId.Value.ToString();
                var thumb_media_id = message.Body.ThumbMediaId.Value.ToString();
                var msgId          = message.Body.MsgId.Value.ToString();
                //TODO
                result = ReplayMessageApi.RepayText(openId, myUserName, string.Format("视频消息:openid:{0},media_id:{1},thumb_media_id:{2},msgId:{3}", openId, media_id, thumb_media_id, msgId));
            }
                #endregion
                break;

            case WeixinMessageType.Voice:    //语音消息
                #region 语音消息
            {
                var media_id = message.Body.MediaId.Value.ToString();
                var format   = message.Body.Format.Value.ToString();
                var msgId    = message.Body.MsgId.Value.ToString();
                //TODO
                result = ReplayMessageApi.RepayText(openId, myUserName, string.Format("语音消息:openid:{0},media_id:{1},format:{2},msgId:{3}", openId, media_id, format, msgId));
            }
                #endregion
                break;

            case WeixinMessageType.Link:    //链接消息
                #region 链接消息
            {
                var title       = message.Body.Title.Value.ToString();
                var description = message.Body.Description.Value.ToString();
                var url         = message.Body.Url.Value.ToString();
                var msgId       = message.Body.MsgId.Value.ToString();
                //TODO
                result = ReplayMessageApi.RepayText(openId, myUserName, string.Format("openid:{0},title:{1},description:{2},url:{3},msgId:{4}", openId, title, description, url, msgId));
            }
                #endregion
                break;

            case WeixinMessageType.Event:
                string eventType = message.Body.Event.Value.ToLower();
                string eventKey  = string.Empty;
                try
                {
                    eventKey = message.Body.EventKey.Value;
                }
                catch { }
                switch (eventType)
                {
                case "subscribe":        //用户未关注时,进行关注后的事件推送

                    result = ReplayMessageApi.RepayText(openId, myUserName,
                                                        "欢迎订阅 晚安家纺公众号");

                    break;

                case "unsubscribe":        //取消关注
                    #region 取消关注
                    result = ReplayMessageApi.RepayText(openId, myUserName, "欢迎再来");
                    #endregion
                    break;

                case "scan":        // 用户已关注时的事件推送
                    #region 已关注扫码事件
                    if (!string.IsNullOrEmpty(eventKey))
                    {
                        var qrscene = eventKey.Replace("qrscene_", "");        //此为场景二维码的场景值
                        result = ReplayMessageApi.RepayNews(openId, myUserName,
                                                            new WeixinNews
                        {
                            title       = "欢迎使用,场景值:" + qrscene,
                            description = "欢迎使用,场景值:" + qrscene,
                            picurl      = string.Format("{0}/ad.jpg", domain),
                            url         = domain
                        });
                    }
                    else
                    {
                        result = ReplayMessageApi.RepayNews(openId, myUserName,
                                                            new WeixinNews
                        {
                            title       = "欢迎使用",
                            description = "欢迎订阅,点击此消息查看在线demo",
                            picurl      = string.Format("{0}/ad.jpg", domain),
                            url         = domain
                        });
                    }
                    #endregion
                    break;

                case "masssendjobfinish":        //事件推送群发结果,
                    #region 事件推送群发结果
                {
                    var msgId     = message.Body.MsgID.Value;
                    var msgStatus = message.Body.Status.Value;            //“send success”或“send fail”或“err(num)”
                    //send success时,也有可能因用户拒收公众号的消息、系统错误等原因造成少量用户接收失败。
                    //err(num)是审核失败的具体原因,可能的情况如下:err(10001)涉嫌广告, err(20001)涉嫌政治, err(20004)涉嫌社会, err(20002)涉嫌色情, err(20006)涉嫌违法犯罪,
                    //err(20008)涉嫌欺诈, err(20013)涉嫌版权, err(22000)涉嫌互推(互相宣传), err(21000)涉嫌其他
                    var totalCount  = message.Body.TotalCount.Value;         //group_id下粉丝数;或者openid_list中的粉丝数
                    var filterCount = message.Body.FilterCount.Value;        //过滤(过滤是指特定地区、性别的过滤、用户设置拒收的过滤,用户接收已超4条的过滤)后,准备发送的粉丝数,原则上,FilterCount = SentCount + ErrorCount
                    var sentCount   = message.Body.SentCount.Value;          //发送成功的粉丝数
                    var errorCount  = message.Body.FilterCount.Value;        //发送失败的粉丝数
                                                                             //TODO:开发者自己的处理逻辑,这里用log4net记录日志
                    _log.Info(string.Format("mass send job finishe,msgId:{0},msgStatus:{1},totalCount:{2},filterCount:{3},sentCount:{4},errorCount:{5}", msgId, msgStatus, totalCount, filterCount, sentCount, errorCount));
                }
                    #endregion
                    break;

                case "templatesendjobfinish":        //模版消息结果,
                    #region 模版消息结果
                {
                    var msgId     = message.Body.MsgID.Value;
                    var msgStatus = message.Body.Status.Value;            //发送状态为成功: success; 用户拒绝接收:failed:user block; 发送状态为发送失败(非用户拒绝):failed: system failed
                                                                          //TODO:开发者自己的处理逻辑,这里用log4net记录日志
                    _log.Info(string.Format("template send job finish,msgId:{0},msgStatus:{1}", msgId, msgStatus));
                }
                    #endregion
                    break;

                case "location":        //上报地理位置事件
                    #region  报地理位置事件
                    var lat = message.Body.Latitude.Value.ToString();
                    var lng = message.Body.Longitude.Value.ToString();
                    var pcn = message.Body.Precision.Value.ToString();
                    //TODO:在此处将经纬度记录在数据库,这里用log4net记录日志
                    _log.Info(string.Format("openid:{0} ,location,lat:{1},lng:{2},pcn:{3}", openId, lat, lng, pcn));
                    #endregion
                    break;

                case "image":                                  //图片消息
                    #region 图片消息
                    var userImage = message.Body.PicUrl.Value; //用户语音消息文字
                    result = ReplayMessageApi.RepayNews(openId, myUserName, new WeixinNews
                    {
                        title       = "您刚才发送了图片消息",
                        picurl      = string.Format("{0}/Images/ad.jpg", domain),
                        description = "点击查看图片",
                        url         = userImage
                    });
                    #endregion
                    break;

                case "click":        //自定义菜单事件
                    #region 自定义菜单事件
                {
                    switch (eventKey)
                    {
                    case "myaccount":                //CLICK类型事件举例
                        #region 我的账户
                        result = ReplayMessageApi.RepayNews(openId, myUserName, new List <WeixinNews>()
                            {
                                new WeixinNews {
                                    title       = "我的帐户",
                                    url         = string.Format("{0}/user?openId={1}", domain, openId),
                                    description = "点击查看帐户详情",
                                    picurl      = string.Format("{0}/Images/ad.jpg", domain)
                                },
                            });
                        #endregion
                        break;

                    case "www.weixinsdk.net":                //VIEW类型事件举例,注意:点击菜单弹出子菜单,不会产生上报。
                        //TODO:后台处理逻辑
                        break;

                    default:
                        result = ReplayMessageApi.RepayText(openId, myUserName, "没有响应菜单事件");
                        break;
                    }
                }
                    #endregion
                    break;

                case "view":        //点击菜单跳转链接时的事件推送
                    #region 点击菜单跳转链接时的事件推送
                    result = ReplayMessageApi.RepayText(openId, myUserName, string.Format("您将跳转至:{0}", eventKey));
                    #endregion
                    break;

                case "scancode_push":                                            //扫码推事件的事件推送
                {
                    var scanType   = message.Body.ScanCodeInfo.ScanType.Value;   //扫描类型,一般是qrcode
                    var scanResult = message.Body.ScanCodeInfo.ScanResult.Value; //扫描结果,即二维码对应的字符串信息
                    result = ReplayMessageApi.RepayText(openId, myUserName, string.Format("您扫描了二维码,scanType:{0},scanResult:{1},EventKey:{2}", scanType, scanResult, eventKey));
                }
                break;

                case "scancode_waitmsg":        //扫码推事件且弹出“消息接收中”提示框的事件推送
                {
                    if (!string.IsNullOrEmpty(eventKey) && eventKey == "rselfmenu_0_1")
                    {
                        try
                        {
                            var ms = _dbProcess.Process(message.Body.ScanCodeInfo.ScanResult.Value);
                            result = ReplayMessageApi.RepayText(openId, myUserName, ms);
                        }
                        catch (Exception ex)
                        {
                            result = ReplayMessageApi.RepayText(openId, myUserName, ex.Message);
                        }
                    }
                    //else
                    //{
                    //    var scanType = message.Body.ScanCodeInfo.ScanType.Value;//扫描类型,一般是qrcode
                    //    var scanResult = message.Body.ScanCodeInfo.ScanResult.Value;//扫描结果,即二维码对应的字符串信息
                    //    result = ReplayMessageApi.RepayText(openId, myUserName, string.Format("您扫描了二维码,scanType:{0},scanResult:{1},EventKey:{2}", scanType, scanResult, eventKey));
                    //}
                }
                break;

                case "pic_sysphoto":                               //弹出系统拍照发图的事件推送
                {
                    var count   = message.Body.SendPicsInfo.Count; //发送的图片数量
                    var picList = message.Body.PicList;            //发送的图片信息
                    result = ReplayMessageApi.RepayText(openId, myUserName, string.Format("弹出系统拍照发图,count:{0},EventKey:{1}", count, eventKey));
                }
                break;

                case "pic_photo_or_album":                               //弹出拍照或者相册发图的事件推送
                {
                    var count   = message.Body.SendPicsInfo.Count.Value; //发送的图片数量
                    var picList = message.Body.PicList.Value;            //发送的图片信息
                    result = ReplayMessageApi.RepayText(openId, myUserName, string.Format("弹出拍照或者相册发图,count:{0},EventKey:{1}", count, eventKey));
                }
                break;
                }
                break;

            default:
                result = ReplayMessageApi.RepayText(openId, myUserName, string.Format("未处理消息类型:{0}", message.Type));
                break;
            }
            return(result);
        }
예제 #15
0
        /// <summary>
        /// 说明:带TODO字眼的代码段,需要开发者自行按照自己的业务逻辑实现
        /// </summary>
        /// <param name="message"></param>
        /// <returns>已经打包成xml的用于回复用户的消息包</returns>
        public string Execute(WeixinMessage message)
        {
            var result     = "";
            var domain     = System.Configuration.ConfigurationManager.AppSettings["Domain"];//请更改成你的域名
            var openId     = message.Body.FromUserName.Value;
            var myUserName = message.Body.ToUserName.Value;

            //这里需要调用TokenHelper获取Token的,省略了。
            switch (message.Type)
            {
            case WeixinMessageType.Text:
                string userMessage = message.Body.Content.Value;
                result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, "欢迎使用,您输入了:" + userMessage);
                break;

            case WeixinMessageType.Event:
                string eventType = message.Body.Event.Value.ToLower();
                string eventKey  = message.Body.EventKey.Value;
                switch (eventType)
                {
                case "subscribe":        //用户未关注时,进行关注后的事件推送
                    #region 首次关注
                    if (!string.IsNullOrEmpty(eventKey))
                    {
                        var qrscene = eventKey.Replace("qrscene_", "");        //此为场景二维码的场景值
                        result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, "欢迎订阅,场景值:" + qrscene);
                    }
                    else
                    {
                        result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, "欢迎订阅");
                    }
                    #endregion
                    break;

                case "unsubscribe":        //取消关注
                    #region 取消关注
                    result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, "欢迎再来");
                    #endregion
                    break;

                case "scan":        // 用户已关注时的事件推送
                    #region 已关注扫码事件
                    if (!string.IsNullOrEmpty(eventKey))
                    {
                        var qrscene = eventKey.Replace("qrscene_", "");        //此为场景二维码的场景值
                        result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, "欢迎使用,场景值:" + qrscene);
                    }
                    else
                    {
                        result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, "欢迎使用");
                    }
                    #endregion
                    break;

                case "MASSSENDJOBFINISH":        //事件推送群发结果,
                {
                    var msgId     = message.Body.MsgID;
                    var msgStatus = message.Body.Status;            //“send success”或“send fail”或“err(num)”
                    //send success时,也有可能因用户拒收公众号的消息、系统错误等原因造成少量用户接收失败。
                    //err(num)是审核失败的具体原因,可能的情况如下:err(10001)涉嫌广告, err(20001)涉嫌政治, err(20004)涉嫌社会, err(20002)涉嫌色情, err(20006)涉嫌违法犯罪,
                    //err(20008)涉嫌欺诈, err(20013)涉嫌版权, err(22000)涉嫌互推(互相宣传), err(21000)涉嫌其他
                    var totalCount  = message.Body.TotalCount;         //group_id下粉丝数;或者openid_list中的粉丝数
                    var filterCount = message.Body.FilterCount;        //过滤(过滤是指特定地区、性别的过滤、用户设置拒收的过滤,用户接收已超4条的过滤)后,准备发送的粉丝数,原则上,FilterCount = SentCount + ErrorCount
                    var sentCount   = message.Body.SentCount;          //发送成功的粉丝数
                    var errorCount  = message.Body.FilterCount;        //发送失败的粉丝数
                    //TODO:开发者自己的处理逻辑
                }
                break;

                case "TEMPLATESENDJOBFINISH":        //模版消息结果,
                {
                    var msgId     = message.Body.MsgID;
                    var msgStatus = message.Body.Status;            //发送状态为成功: success; 用户拒绝接收:failed:user block; 发送状态为发送失败(非用户拒绝):failed: system failed
                }
                break;

                case "location":        //上报地理位置事件
                    #region  报地理位置事件
                    var lat = message.Body.Latitude.Value.ToString();
                    var lng = message.Body.Longitude.Value.ToString();
                    var pcn = message.Body.Precision.Value.ToString();
                    //TODO:在此处将经纬度记录在数据库
                    #endregion
                    break;

                case "voice":        //语音消息
                    #region 语音消息
                    //A:已开通语音识别权限的公众号
                    var userVoice = message.Body.Recognition.Value;        //用户语音消息文字
                    result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, "您说:" + userVoice);

                    //B:未开通语音识别权限的公众号
                    var userVoiceMediaId = message.Body.MediaId.Value;        //media_id
                    //TODO:调用自定义的语音识别程序识别用户语义

                    #endregion
                    break;

                case "image":                                  //图片消息
                    #region 图片消息
                    var userImage = message.Body.PicUrl.Value; //用户语音消息文字
                    result = ReplayPassiveMessageAPI.RepayNews(openId, myUserName, new WeixinNews
                    {
                        title       = "您刚才发送了图片消息",
                        picurl      = string.Format("{0}/Images/ad.jpg", domain),
                        description = "点击查看图片",
                        url         = userImage
                    });
                    #endregion
                    break;

                case "click":        //自定义菜单事件
                    #region 自定义菜单事件
                    switch (eventKey)
                    {
                    case "myaccount":            //CLICK类型事件举例
                        #region 我的账户
                        result = ReplayPassiveMessageAPI.RepayNews(openId, myUserName, new List <WeixinNews>()
                        {
                            new WeixinNews {
                                title       = "我的帐户",
                                url         = string.Format("{0}/user?openId={1}", domain, openId),
                                description = "点击查看帐户详情",
                                picurl      = string.Format("{0}/Images/ad.jpg", domain)
                            },
                        });
                        #endregion
                        break;

                    case "www.weixinsdk.net":            //VIEW类型事件举例,注意:点击菜单弹出子菜单,不会产生上报。
                        //TODO:后台处理逻辑
                        break;

                    default:
                        result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, "没有响应菜单事件");
                        break;
                    }
                    #endregion
                    break;
                }
                break;

            default:
                result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("未处理消息类型:{0}", message.Type));
                break;
            }
            return(result);
        }
예제 #16
0
        /// <summary>
        /// 说明:带TODO字眼的代码段,需要开发者自行按照自己的业务逻辑实现
        /// </summary>
        /// <param name="message"></param>
        /// <returns>已经打包成xml的用于回复用户的消息包</returns>
        public string Execute(WeixinMessage message)
        {
            var result     = "";
            var domain     = System.Configuration.ConfigurationManager.AppSettings["Domain"];//请更改成你的域名
            var openId     = message.Body.FromUserName.Value;
            var myUserName = message.Body.ToUserName.Value;

            //这里需要调用TokenHelper获取Token的,省略了。
            switch (message.Type)
            {
            case WeixinMessageType.Text:    //文字消息
                string userMessage = message.Body.Content.Value;
                result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, "欢迎使用,您输入了:" + userMessage);
                break;

            case WeixinMessageType.Image:                     //图片消息
                string imageUrl = message.Body.PicUrl.Value;  //图片地址
                string mediaId  = message.Body.MediaId.Value; //mediaId
                result = ReplayPassiveMessageAPI.ReplayImage(openId, myUserName, mediaId);
                break;

            case WeixinMessageType.Video:    //视频消息
                #region 视频消息
            {
                var media_id       = message.Body.MediaId.Value.ToString();
                var thumb_media_id = message.Body.ThumbMediaId.Value.ToString();
                var msgId          = message.Body.MsgId.Value.ToString();
                //TODO
                result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("视频消息:openid:{0},media_id:{1},thumb_media_id:{2},msgId:{3}", openId, media_id, thumb_media_id, msgId));
            }
                #endregion
                break;

            case WeixinMessageType.Voice:    //语音消息
                #region 语音消息
            {
                var media_id = message.Body.MediaId.Value.ToString();
                var format   = message.Body.Format.Value.ToString();
                var msgId    = message.Body.MsgId.Value.ToString();
                //TODO
                result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("语音消息:openid:{0},media_id:{1},format:{2},msgId:{3}", openId, media_id, format, msgId));
            }
                #endregion
                break;

            case WeixinMessageType.Location:    //地理位置消息
                #region 地理位置消息
            {
                var location_X = message.Body.Location_X.Value.ToString();
                var location_Y = message.Body.Location_Y.Value.ToString();
                var scale      = message.Body.Scale.Value.ToString();
                var Label      = message.Body.Label.Value.ToString();
                //TODO
                result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("地理位置消息: openid:{0},Location_X:{1},Location_Y:{2},Scale:{3},label:{4}", openId, location_X, location_Y, scale, Label));
            }
                #endregion
                break;

            case WeixinMessageType.Link:    //链接消息
                #region 链接消息
            {
                var title       = message.Body.Title.Value.ToString();
                var description = message.Body.Description.Value.ToString();
                var url         = message.Body.Url.Value.ToString();
                var msgId       = message.Body.MsgId.Value.ToString();
                //TODO
                result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("openid:{0},title:{1},description:{2},url:{3},msgId:{4}", openId, title, description, url, msgId));
            }
                #endregion
                break;

            case WeixinMessageType.Event:
                string eventType = message.Body.Event.Value.ToLower();
                string eventKey  = string.Empty;
                try
                {
                    eventKey = message.Body.EventKey.Value;
                }
                catch { }
                switch (eventType)
                {
                case "subscribe":        //用户未关注时,进行关注后的事件推送
                    #region 首次关注

                    //TODO: 获取用户基本信息后,将用户信息存储在本地。
                    //var weixinInfo = UserAdminAPI.GetInfo(token, openId);//注意:订阅号没有此权限

                    if (!string.IsNullOrEmpty(eventKey))
                    {
                        var qrscene = eventKey.Replace("qrscene_", "");        //此为场景二维码的场景值
                        result = ReplayPassiveMessageAPI.RepayNews(openId, myUserName,
                                                                   new WeixinNews
                        {
                            title       = "欢迎订阅,场景值:" + qrscene,
                            description = "欢迎订阅,场景值:" + qrscene,
                            picurl      = string.Format("{0}/ad.jpg", domain),
                            url         = domain
                        });
                    }
                    else
                    {
                        result = ReplayPassiveMessageAPI.RepayNews(openId, myUserName,
                                                                   new WeixinNews
                        {
                            title       = "欢迎订阅",
                            description = "欢迎订阅,点击此消息查看在线demo",
                            picurl      = string.Format("{0}/ad.jpg", domain),
                            url         = domain
                        });
                    }
                    #endregion
                    break;

                case "unsubscribe":        //取消关注
                    #region 取消关注
                    result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, "欢迎再来");
                    #endregion
                    break;

                case "scan":        // 用户已关注时的事件推送
                    #region 已关注扫码事件
                    if (!string.IsNullOrEmpty(eventKey))
                    {
                        var qrscene = eventKey.Replace("qrscene_", "");        //此为场景二维码的场景值
                        result = ReplayPassiveMessageAPI.RepayNews(openId, myUserName,
                                                                   new WeixinNews
                        {
                            title       = "欢迎使用,场景值:" + qrscene,
                            description = "欢迎使用,场景值:" + qrscene,
                            picurl      = string.Format("{0}/ad.jpg", domain),
                            url         = domain
                        });
                    }
                    else
                    {
                        result = ReplayPassiveMessageAPI.RepayNews(openId, myUserName,
                                                                   new WeixinNews
                        {
                            title       = "欢迎使用",
                            description = "欢迎订阅,点击此消息查看在线demo",
                            picurl      = string.Format("{0}/ad.jpg", domain),
                            url         = domain
                        });
                    }
                    #endregion
                    break;

                case "masssendjobfinish":        //事件推送群发结果,
                    #region 事件推送群发结果
                {
                    var msgId     = message.Body.MsgID.Value;
                    var msgStatus = message.Body.Status.Value;            //“send success”或“send fail”或“err(num)”
                    //send success时,也有可能因用户拒收公众号的消息、系统错误等原因造成少量用户接收失败。
                    //err(num)是审核失败的具体原因,可能的情况如下:err(10001)涉嫌广告, err(20001)涉嫌政治, err(20004)涉嫌社会, err(20002)涉嫌色情, err(20006)涉嫌违法犯罪,
                    //err(20008)涉嫌欺诈, err(20013)涉嫌版权, err(22000)涉嫌互推(互相宣传), err(21000)涉嫌其他
                    var totalCount  = message.Body.TotalCount.Value;         //group_id下粉丝数;或者openid_list中的粉丝数
                    var filterCount = message.Body.FilterCount.Value;        //过滤(过滤是指特定地区、性别的过滤、用户设置拒收的过滤,用户接收已超4条的过滤)后,准备发送的粉丝数,原则上,FilterCount = SentCount + ErrorCount
                    var sentCount   = message.Body.SentCount.Value;          //发送成功的粉丝数
                    var errorCount  = message.Body.FilterCount.Value;        //发送失败的粉丝数
                    //TODO:开发者自己的处理逻辑,这里用log4net记录日志
                    LogWriter.Default.WriteInfo(string.Format("mass send job finishe,msgId:{0},msgStatus:{1},totalCount:{2},filterCount:{3},sentCount:{4},errorCount:{5}", msgId, msgStatus, totalCount, filterCount, sentCount, errorCount));
                }
                    #endregion
                    break;

                case "templatesendjobfinish":        //模版消息结果,
                    #region 模版消息结果
                {
                    var msgId     = message.Body.MsgID.Value;
                    var msgStatus = message.Body.Status.Value;            //发送状态为成功: success; 用户拒绝接收:failed:user block; 发送状态为发送失败(非用户拒绝):failed: system failed
                    //TODO:开发者自己的处理逻辑,这里用log4net记录日志
                    LogWriter.Default.WriteInfo(string.Format("template send job finish,msgId:{0},msgStatus:{1}", msgId, msgStatus));
                }
                    #endregion
                    break;

                case "location":        //上报地理位置事件
                    #region  报地理位置事件
                    var lat = message.Body.Latitude.Value.ToString();
                    var lng = message.Body.Longitude.Value.ToString();
                    var pcn = message.Body.Precision.Value.ToString();
                    //TODO:在此处将经纬度记录在数据库,这里用log4net记录日志
                    LogWriter.Default.WriteInfo(string.Format("openid:{0} ,location,lat:{1},lng:{2},pcn:{3}", openId, lat, lng, pcn));
                    #endregion
                    break;

                case "voice":        //语音消息
                    #region 语音消息
                    //A:已开通语音识别权限的公众号
                    var userVoice = message.Body.Recognition.Value;        //用户语音消息文字
                    result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, "您说:" + userVoice);

                    //B:未开通语音识别权限的公众号
                    var userVoiceMediaId = message.Body.MediaId.Value;        //media_id
                    //TODO:调用自定义的语音识别程序识别用户语义

                    #endregion
                    break;

                case "image":                                  //图片消息
                    #region 图片消息
                    var userImage = message.Body.PicUrl.Value; //用户语音消息文字
                    result = ReplayPassiveMessageAPI.RepayNews(openId, myUserName, new WeixinNews
                    {
                        title       = "您刚才发送了图片消息",
                        picurl      = string.Format("{0}/Images/ad.jpg", domain),
                        description = "点击查看图片",
                        url         = userImage
                    });
                    #endregion
                    break;

                case "click":        //自定义菜单事件
                    #region 自定义菜单事件
                {
                    switch (eventKey)
                    {
                    case "myaccount":                //CLICK类型事件举例
                        #region 我的账户
                        result = ReplayPassiveMessageAPI.RepayNews(openId, myUserName, new List <WeixinNews>()
                            {
                                new WeixinNews {
                                    title       = "我的帐户",
                                    url         = string.Format("{0}/user?openId={1}", domain, openId),
                                    description = "点击查看帐户详情",
                                    picurl      = string.Format("{0}/Images/ad.jpg", domain)
                                },
                            });
                        #endregion
                        break;

                    case "www.weixinsdk.net":                //VIEW类型事件举例,注意:点击菜单弹出子菜单,不会产生上报。
                        //TODO:后台处理逻辑
                        break;

                    default:
                        result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, "没有响应菜单事件");
                        break;
                    }
                }
                    #endregion
                    break;

                case "view":        //点击菜单跳转链接时的事件推送
                    #region 点击菜单跳转链接时的事件推送
                    result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("您将跳转至:{0}", eventKey));
                    #endregion
                    break;

                case "scancode_push":                                            //扫码推事件的事件推送
                {
                    var scanType   = message.Body.ScanCodeInfo.ScanType.Value;   //扫描类型,一般是qrcode
                    var scanResult = message.Body.ScanCodeInfo.ScanResult.Value; //扫描结果,即二维码对应的字符串信息
                    result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("您扫描了二维码,scanType:{0},scanResult:{1},EventKey:{2}", scanType, scanResult, eventKey));
                }
                break;

                case "scancode_waitmsg":                                         //扫码推事件且弹出“消息接收中”提示框的事件推送
                {
                    var scanType   = message.Body.ScanCodeInfo.ScanType.Value;   //扫描类型,一般是qrcode
                    var scanResult = message.Body.ScanCodeInfo.ScanResult.Value; //扫描结果,即二维码对应的字符串信息
                    result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("您扫描了二维码,scanType:{0},scanResult:{1},EventKey:{2}", scanType, scanResult, eventKey));
                }
                break;

                case "pic_sysphoto":                               //弹出系统拍照发图的事件推送
                {
                    var count   = message.Body.SendPicsInfo.Count; //发送的图片数量
                    var picList = message.Body.PicList;            //发送的图片信息
                    result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("弹出系统拍照发图,count:{0},EventKey:{1}", count, eventKey));
                }
                break;

                case "pic_photo_or_album":                               //弹出拍照或者相册发图的事件推送
                {
                    var count   = message.Body.SendPicsInfo.Count.Value; //发送的图片数量
                    var picList = message.Body.PicList.Value;            //发送的图片信息
                    result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("弹出拍照或者相册发图,count:{0},EventKey:{1}", count, eventKey));
                }
                break;

                case "pic_weixin":                                       //弹出微信相册发图器的事件推送
                {
                    var count   = message.Body.SendPicsInfo.Count.Value; //发送的图片数量
                    var picList = message.Body.PicList.Value;            //发送的图片信息
                    result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("弹出微信相册发图器,count:{0},EventKey:{1}", count, eventKey));
                }
                break;

                case "location_select":                                              //弹出地理位置选择器的事件推送
                {
                    var location_X = message.Body.SendLocationInfo.Location_X.Value; //X坐标信息
                    var location_Y = message.Body.SendLocationInfo.Location_Y.Value; //Y坐标信息
                    var scale      = message.Body.SendLocationInfo.Scale.Value;      //精度,可理解为精度或者比例尺、越精细的话 scale越高
                    var label      = message.Body.SendLocationInfo.Label.Value;      //地理位置的字符串信息
                    var poiname    = message.Body.SendLocationInfo.Poiname.Value;    //朋友圈POI的名字,可能为空
                    result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("弹出地理位置选择器,location_X:{0},location_Y:{1},scale:{2},label:{3},poiname:{4},eventKey:{5}", location_X, location_Y, scale, label, poiname, eventKey));
                }
                break;

                case "card_pass_check":                     //生成的卡券通过审核时,微信会把这个事件推送到开发者填写的URL。
                {
                    var cardid = message.Body.CardId.Value; //CardId
                    result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("您的卡券已经通过审核"));
                }
                break;

                case "card_not_pass_check":                 //生成的卡券未通过审核时,微信会把这个事件推送到开发者填写的URL。
                {
                    var cardid = message.Body.CardId.Value; //CardId
                }
                break;

                case "user_get_card":                                       //用户在领取卡券时,微信会把这个事件推送到开发者填写的URL。
                {
                    var cardid         = message.Body.CardId.Value;         //CardId
                    var isGiveByFriend = message.Body.IsGiveByFriend.Value; //是否为转赠,1代表是,0代表否。
                    var fromUserName   = message.Body.FromUserName.Value;   //领券方帐号(一个OpenID)
                    var friendUserName = message.Body.FriendUserName.Value; //赠送方账号(一个OpenID),"IsGiveByFriend”为1时填写该参数。
                    var userCardCode   = message.Body.UserCardCode.Value;   //code序列号。自定义code及非自定义code的卡券被领取后都支持事件推送。
                    var outerId        = message.Body.OuterId.Value;        //领取场景值,用于领取渠道数据统计。可在生成二维码接口及添加JSAPI接口中自定义该字段的整型值。
                }
                break;

                case "user_del_card":                                   //用户在删除卡券时,微信会把这个事件推送到开发者填写的URL
                {
                    var cardid       = message.Body.CardId.Value;       //CardId
                    var userCardCode = message.Body.UserCardCode.Value; //商户自定义code值。非自定code推送为空
                }
                break;

                case "merchant_order":                                //微信小店:订单付款通知:在用户在微信中付款成功后,微信服务器会将订单付款通知推送到开发者在公众平台网站中设置的回调URL(在开发模式中设置)中,如未设置回调URL,则获取不到该事件推送。
                {
                    var orderId     = message.Body.OrderId.Value;     //CardId
                    var orderStatus = message.Body.OrderStatus.Value; //OrderStatus
                    var productId   = message.Body.ProductId.Value;   //ProductId
                    var skuInfo     = message.Body.SkuInfo.Value;     //SkuInfo
                }
                break;
                }
                break;

            default:
                result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("未处理消息类型:{0}", message.Type));
                break;
            }
            return(result);
        }
        private void DealWithEvent(WeixinMessage message, string openId, string unionId, string myUserName, out string result)
        {
            string eventType = message.Body.Event.Value.ToLower();
            string eventKey  = string.Empty;

            try
            {
                eventKey = message.Body.EventKey.Value;
            }
            catch { }
            switch (eventType)
            {
            case "scan":    // 用户已关注时的事件推送
                #region 已关注扫码事件
                if (!string.IsNullOrEmpty(eventKey))
                {
                    var qrscene = eventKey.Replace("qrscene_", "");    //此为场景二维码的场景值
                    result = ReplayPassiveMessageAPI.RepayNews(openId, myUserName,
                                                               new WeixinNews
                    {
                        title       = "欢迎使用,场景值:" + qrscene,
                        description = "欢迎使用,场景值:" + qrscene,
                        picurl      = string.Format("{0}/resource/Content/images/[email protected]", GlobalContext.Domain),
                        url         = string.Format("{0}?unionId={1}", GlobalContext.Domain, unionId)
                    });
                }
                else
                {
                    result = ReplayPassiveMessageAPI.RepayNews(openId, myUserName,
                                                               new WeixinNews
                    {
                        title       = "欢迎使用",
                        description = "欢迎订阅,点击此消息查看在线demo",
                        picurl      = string.Format("{0}/resource/Content/images/[email protected]", GlobalContext.Domain),
                        url         = string.Format("{0}?unionId={1}", GlobalContext.Domain, unionId)
                    });
                }
                #endregion
                break;

            case "subscribe":    //用户未关注时,进行关注后的事件推送
                #region 首次关注

                //TODO: 获取用户基本信息后,将用户信息存储在本地。
                //var token = WeixinConfig.TokenHelper.GetToken();
                //var weixinInfo = UserAdminAPI.GetInfo(token, openId);//注意:订阅号没有此权限

                if (!string.IsNullOrEmpty(eventKey))
                {
                    var qrscene = eventKey.Replace("qrscene_", "");    //此为场景二维码的场景值
                    result = ReplayPassiveMessageAPI.RepayNews(openId, myUserName,
                                                               new WeixinNews
                    {
                        title       = "欢迎订阅,场景值:" + qrscene,
                        description = "欢迎订阅01World,场景值:" + qrscene,
                        picurl      = string.Format("{0}/resource/Content/images/[email protected]", GlobalContext.Domain),
                        url         = string.Format("{0}?unionId={1}", GlobalContext.Domain, unionId)
                    });
                }
                else
                {
                    result = ReplayPassiveMessageAPI.RepayNews(openId, myUserName,
                                                               new WeixinNews
                    {
                        title       = "欢迎订阅",
                        description = "欢迎订阅",
                        picurl      = string.Format("{0}/resource/Content/images/[email protected]", GlobalContext.Domain),
                        url         = string.Format("{0}?unionId={1}", GlobalContext.Domain, unionId)
                    });
                }
                #endregion
                break;

            case "unsubscribe":    //取消关注
                #region 取消关注
                result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, "欢迎再来");
                #endregion
                break;

            case "click":    //自定义菜单事件
                #region 自定义菜单事件
            {
                switch (eventKey)
                {
                case "V1001_My01":
                    #region 我的01
                    result = ReplayPassiveMessageAPI.RepayNews(openId, myUserName, new List <WeixinNews>()
                        {
                            new WeixinNews {
                                title       = "我的01",
                                url         = string.Format("{0}/My01/My01?unionId={1}", GlobalContext.Domain, unionId),
                                description = "我的余额:" + GetYE() + ";\n点击查看帐户详情",
                                picurl      = string.Format("{0}/resource/Content/images/mytopbg.jpg", GlobalContext.Domain)
                            },
                        });
                    #endregion
                    break;

                case "V1001_Binding":
                    #region 绑定账号
                    result = ReplayPassiveMessageAPI.RepayNews(openId, myUserName, new List <WeixinNews>()
                        {
                            new WeixinNews {
                                title       = "绑定账号",
                                url         = string.Format("{0}/User/WeixinBind?unionId={1}", GlobalContext.Domain, unionId),
                                description = "点击绑定账号",
                                picurl      = string.Format("{0}/resource/Content/images/[email protected]", GlobalContext.Domain)
                            },
                        });
                    #endregion
                    break;

                case "V1001_JSAPIPay":
                    #region JSAPI支付测试 web
                    result = ReplayPassiveMessageAPI.RepayNews(openId, myUserName, new List <WeixinNews>()
                        {
                            new WeixinNews {
                                title       = "公众号支付测试",
                                url         = string.Format("{0}/WeixinPay2/JsApiPay?openid={1}&total_fee={2}", GlobalContext.APIDomain, openId, "39.9"),
                                description = "点击支付",
                                picurl      = string.Format("{0}/resource/Content/images/apple.png", GlobalContext.Domain)
                            },
                        });
                    #endregion
                    break;

                case "V1001_NativePay":
                    #region 公众号支付测试
                    result = ReplayPassiveMessageAPI.RepayNews(openId, myUserName, new List <WeixinNews>()
                        {
                            new WeixinNews {
                                title       = "扫码支付测试",
                                url         = string.Format("{0}/WeixinPay2/NativePay?productId={1}", GlobalContext.APIDomain, "apple01"),
                                description = "进入扫码",
                                picurl      = string.Format("{0}/resource/Content/images/apple.png", GlobalContext.Domain)
                            },
                        });
                    #endregion
                    break;

                default:
                    result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, "没有响应菜单事件");
                    break;
                }
            }
                #endregion
                break;

            case "view":    //点击菜单跳转链接时的事件推送
                #region 点击菜单跳转链接时的事件推送
                result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, string.Format("您将跳转至:{0}", eventKey));
                #endregion
                break;

            default:
                result = ReplayPassiveMessageAPI.RepayText(openId, myUserName, "没有响应菜单事件");
                break;
            }
        }