コード例 #1
0
        /// <summary>
        /// 文本信息处理
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnTextRequest(RequestMessageText requestMessage)
        {
            var responseMessage = base.CreateResponseMessage <ResponseMessageText>();

            try
            {
                var keyword    = requestMessage.Content;
                var dataAccess = new WeiXinMessageDataAccess();
                var service    = new WeiXinService(dataAccess);
                var message    = service.AutoReplyMessageGetByKeyword(keyword);

                if (message != null && message.Id > 0)
                {
                    responseMessage.Content = message.ReplyContent;
                    return(responseMessage);
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                return(null);
            }
        }
コード例 #2
0
        public ActionResult WeixinMessage()
        {
            var accesstoken          = AccessTokenContainer.TryGetToken(AppId, AppSecret);
            var autoReplyMessagelist = WeiXinService.AutoReplyMessageGetAll();

            ViewBag.MessageList = autoReplyMessagelist;
            return(View());
        }
コード例 #3
0
        /// <summary>
        /// 微信登录
        /// </summary>
        public void WXLogin()
        {
            string returnUrl = Request.QueryString["ReturnUrl"];

            #region  是否开发环境
            string devClinetSysNo = ConfigurationManager.AppSettings["DevClinetUserSysNo"];
            int    clientSysNo    = 0;
            int.TryParse(devClinetSysNo, out clientSysNo);
            if (clientSysNo > 0)
            {
                Client cusomerInfo = ClientService.LoadClient(clientSysNo);
                if (cusomerInfo != null && cusomerInfo.SysNo > 0)
                {
                    var appuser = new AppUserInfo()
                    {
                        AppCustomerID   = cusomerInfo.AppCustomerID,
                        UserSysNo       = cusomerInfo.SysNo,
                        UserID          = HttpUtility.UrlEncode(cusomerInfo.Name),
                        HeadImage       = cusomerInfo.HeaderImage,
                        UserDisplayName = HttpUtility.UrlEncode(cusomerInfo.Name),

                        ManagerSysNo      = cusomerInfo.ManagerSysNo,
                        UserType          = UserType.Common,
                        LastLoginDateText = DateTimeHelper.GetTimeZoneNow().ToString("yyyy-MM-dd HH:mm:ss"),
                        ManagerLoginName  = cusomerInfo.ManagerLoginName,
                        ManagerName       = HttpUtility.UrlEncode(cusomerInfo.ManagerName)
                    };

                    if (cusomerInfo.ManagerSysNo.HasValue && cusomerInfo.ManagerSysNo.Value > 0)
                    {
                        appuser.UserType = UserType.Manager;
                        var company = CompanyService.GetCompanyUser(cusomerInfo.ManagerSysNo.Value);
                        if (company != null)
                        {
                            appuser.UserType = UserType.Installer;
                        }
                    }

                    UserMgr.Logout();
                    UserMgr.WriteUserInfo(appuser);
                    if (!string.IsNullOrEmpty(returnUrl))
                    {
                        Response.Redirect(returnUrl);
                        return;
                    }
                    Response.Redirect("/smoke/userInfo");
                    return;
                }
            }
            #endregion


            NameValueCollection collection = new NameValueCollection();
            collection.Add("ReturnUrl", HttpUtility.UrlDecode(returnUrl));
            Response.Redirect(WeiXinService.WeiXinLogin(collection));
        }
コード例 #4
0
ファイル: index.ashx.cs プロジェクト: flyxlee/FlyWXSolution
        public void ProcessRequest(HttpContext context)
        {
            WeiXinService wxs         = new WeiXinService(context.Request);
            string        responseMsg = wxs.Execute();

            context.Response.Clear();
            context.Response.Charset = "UTF-8";
            context.Response.Write(responseMsg);
            context.Response.End();
        }
コード例 #5
0
ファイル: WeiXin.ashx.cs プロジェクト: chenz2008/WeiXin
        static WeiXin()
        {
            _Service = new ProcessMessage();
            // 步骤2
            WeiXinService.Register(_Service);

            Log.Logger = new Logger();
            // 设置日记级别
            Log.Level = LogLevel.Debug;
        }
コード例 #6
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var code  = Request.QueryString["code"];
            var state = Request.QueryString["state"];

            if (!string.IsNullOrEmpty(state) && !string.IsNullOrEmpty(code))
            {
                var token = WeiXinService.GetOAuthAccessToken(code, WeiXinConfig.AppId, WeiXinConfig.AppSecret);
                this.openId.Text = token.OpenId;
            }
        }
コード例 #7
0
ファイル: Show_Test.ashx.cs プロジェクト: fr830/-Demo
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            //context.Response.Write("Hello World");

            //由微信服务接收请求,具体处理请求
            WeiXinService wxService   = new WeiXinService(context.Request);
            string        responseMsg = wxService.Response();

            context.Response.Clear();
            context.Response.Charset = "UTF-8";
            context.Response.Write(responseMsg);
            context.Response.End();
        }
コード例 #8
0
        public ActionResult GetWXjsSdkConfig(string curl)
        {
            string ticket = string.Empty;

            //try
            //{
            ticket = WeiXinService.GetWeixinJsApiTicket();
            //}
            //catch (BusinessException e )
            //{
            //    return Json(new AjaxResult { Success = false,Message="获取微信接口信息失败,请重新进入后再试" }, JsonRequestBehavior.AllowGet);
            //}

            if (string.IsNullOrEmpty(ticket))
            {
                throw new BusinessException("调用微信接口失败,请重新进入页面后重试!");
            }
            Random            random      = new Random(unchecked ((int)DateTime.Now.Ticks));
            var               srandom     = random.Next(11111, 999999);
            WeixinJsApiConfig jsApiConfig = new WeixinJsApiConfig
            {
                Noncestr  = srandom.ToString(),
                Timestamp = WebPortalHelper.GetTimeStamp().ToString(),
            };
            string url = string.Empty;

            if (!string.IsNullOrEmpty(curl))
            {
                url = curl;
            }
            StringBuilder sb = new StringBuilder();

            sb.Append(string.Format("jsapi_ticket={0}&", ticket));
            sb.Append(string.Format("noncestr={0}&", jsApiConfig.Noncestr));
            sb.Append(string.Format("timestamp={0}&", jsApiConfig.Timestamp));
            sb.Append(string.Format("url={0}", url));
            jsApiConfig.Signature = SecurityHelper.GetSHA1Value(sb.ToString());
            jsApiConfig.AppId     = WechatSenderService.WXConfig.AppID;
            jsApiConfig.Debug     = false;
            jsApiConfig.JsApiList = WechatSenderService.WXConfig.JsApis;
            var jsapiconfig = JsonConvert.SerializeObject(jsApiConfig);

            return(Json(new AjaxResult {
                Success = true, Data = jsapiconfig
            }, JsonRequestBehavior.AllowGet));
        }
コード例 #9
0
        public ActionResult WeixinMessage(WeixinAutoReplyMessageModel model)
        {
            model.CreateTime = DateTime.Now;
            model.CreatorId  = this.Admin.Id;
            if (model.Id == 0)
            {
                WeiXinService.AutoReplyMessageInsert(model);
            }
            else
            {
                WeiXinService.AutoReplyMessageUpdate(model);
            }
            var autoReplyMessagelist = WeiXinService.AutoReplyMessageGetAll();

            ViewBag.MessageList = autoReplyMessagelist;
            return(View());
        }
コード例 #10
0
        /// <summary>
        /// 确认结算AJAX
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public JsonResult ConfirmOrderRefund(int id, int userId)
        {
            var success = true;
            var msg     = "";
            var paylog  = WeiXinService.GetPayLogById(id);

            if (paylog.Id > 0)
            {
                //企业支付
                var payCode      = paylog.OrderId.ToString() + paylog.Id.ToString();
                var payResultMsg = "";
                var payResult    = WeixinPayApi.QYPay(paylog.WxOpenId, payCode, paylog.Amount, paylog.Description, out payResultMsg);
                if (payResult == "SUCCESS")
                {
                    success = true;
                    //更新paylog状态
                    WeiXinService.WeixinPayLogUpdateStatus(id, 1);
                    //确认是否都处于结算完成状态
                    var hasUnRefund = WeiXinService.WeixinPayLogCheckStatus(paylog.OrderId, 0);//返回是否还有状态为0的数据
                    //如果没有状态为0的数据,修改订单状态为已完成
                    if (!hasUnRefund)
                    {
                        var orderStatus = OrderStatus.Complete.GetHashCode();
                        OrderService.UpdateOrderStatus(userId, paylog.OrderId, orderStatus);
                    }
                }
                else
                {
                    success = false;
                    msg     = "企业支付接口调取失败,请稍后重试。原因:" + payResultMsg;
                }
            }
            else
            {
                success = false;
                msg     = "结算记录不存在";
            }
            var result = new
            {
                IsSuccess = success,
                Message   = msg
            };

            return(Json(result));
        }
コード例 #11
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var code  = Request.QueryString["code"];
            var state = Request.QueryString["state"];

            if (!string.IsNullOrEmpty(state) && !string.IsNullOrEmpty(code))
            {
                var token    = WeiXinService.GetOAuthAccessToken(code, WeiXinConfig.AppId, WeiXinConfig.AppSecret);
                var userInfo = WeiXinService.GetOAuthUserInfo(token.OpenId, token.AccessToken);
                this.openId.Text         = token.OpenId;
                this.nickname.Text       = userInfo.NickName;
                this.sex.Text            = userInfo.Sex.ToString();
                this.city.Text           = userInfo.City;
                this.province.Text       = userInfo.Province;
                this.country.Text        = userInfo.Country;
                this.headimgurl.ImageUrl = userInfo.HeadImgUrl;
            }
        }
コード例 #12
0
        /// <summary>
        /// 结算详情页
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public ActionResult PayRefund(long orderId, int userId)
        {
            var weixinPayLogList = WeiXinService.GetPayLogListByOrderId(orderId);

            ViewBag.Msg = "";
            if (weixinPayLogList == null || weixinPayLogList.Count == 0)
            {
                var msg = "";
                weixinPayLogList = createWeixinPayLog(orderId, userId, out msg);
                if (weixinPayLogList == null)
                {
                    ViewBag.Msg      = msg;
                    weixinPayLogList = new List <WeixinPayLog>();
                }
            }
            ViewBag.PayLogList = JsonHelper.ToJson(weixinPayLogList);
            ViewBag.UserId     = userId;
            return(View());
        }
コード例 #13
0
ファイル: WeiXin.ashx.cs プロジェクト: chenz2008/WeiXin
        public void ProcessRequest(HttpContext context)
        {
            string echoStr   = HttpContext.Current.Request.QueryString["echoStr"];
            string signature = HttpContext.Current.Request.QueryString["signature"];
            string timestamp = HttpContext.Current.Request.QueryString["timestamp"];
            string nonce     = HttpContext.Current.Request.QueryString["nonce"];

            // 验证签名
            if (WeiXinService.CheckSignature(WeiXinConfig.Token, signature, timestamp, nonce))
            {
                var writeMsg = string.Empty;
                if ("post".Equals(context.Request.HttpMethod.ToLower()))
                {
                    string xml = null;
                    using (var reader = new StreamReader(context.Request.InputStream))
                    {
                        xml = reader.ReadToEnd();
                    }
                    if (!string.IsNullOrEmpty(xml))
                    {
                        // 步骤3
                        try
                        {
                            writeMsg = WeiXinService.ProcessMessage(xml);
                        }
                        catch (System.Exception e)
                        {
                            Log.Error("异常信息:{1}\r\n源:{2}\r\n堆栈:{3}\r\n引发异常的方法:{4}\r\n\r\n", e.Message, e.Source, e.StackTrace, e.TargetSite.Name);
                        }
                    }
                }
                else
                {
                    // get 请求是微信服务器验证,原样返回 echoStr 才能通过验证
                    writeMsg = echoStr;
                }
                HttpContext.Current.Response.Write(writeMsg);
                HttpContext.Current.Response.End();
            }
        }
コード例 #14
0
ファイル: weixin.ashx.cs プロジェクト: ben889/myb2b
 public void ProcessRequest(HttpContext context)
 {
     try
     {
         //if (context.Request["s"] != null)
         //{
         //    companyid = DESEncrypt.Decrypt(context.Request["s"]);
         //}
         //由微信服务接收请求,具体处理请求
         WeiXinService wxService   = new WeiXinService(context.Request);
         string        responseMsg = wxService.Response();
         context.Response.Clear();
         context.Response.Charset = "UTF-8";
         context.Response.Write(responseMsg);
         //Common.Library.WriteTxt(responseMsg, HttpContext.Current.Server.MapPath("/log/"), "微信接口调试" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt");
     }
     catch (Exception exc)
     {
         Common.Library.WriteTxt(exc.Message, HttpContext.Current.Server.MapPath("/log/"), "微信接口调试" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt");
     }
     finally {
         context.Response.End();
     }
 }
コード例 #15
0
        /// <summary>
        /// </summary>
        /// 微信登录回调
        public void WXLoginBack()
        {
            Client     customer    = new Client();
            WeiXinUser weiXinUser  = WeiXinService.GetWeiXinUser(string.Empty, Request.Params["code"].ToString());
            string     callbackUrl = Request.QueryString["state"].ToString();

            if (weiXinUser != null && !string.IsNullOrEmpty(weiXinUser.Openid))
            {
                Client cusomerInfo = ClientService.LoadClientByAppCustomerID(weiXinUser.Openid);
                if (cusomerInfo != null && cusomerInfo.SysNo > 0)
                {
                    //更新用户头像以及昵称
                    cusomerInfo.Name        = weiXinUser.NickName;
                    cusomerInfo.HeaderImage = weiXinUser.HeadImgUrl;
                    cusomerInfo.EditTime    = DateTimeHelper.GetTimeZoneNow();

                    ClientService.UpdateClient(cusomerInfo);

                    var appuser = new AppUserInfo()
                    {
                        AppCustomerID   = weiXinUser.Openid,
                        UserSysNo       = cusomerInfo.SysNo,
                        UserID          = HttpUtility.UrlEncode(cusomerInfo.Name),
                        HeadImage       = cusomerInfo.HeaderImage,
                        UserDisplayName = HttpUtility.UrlEncode(cusomerInfo.Name),

                        ManagerSysNo      = cusomerInfo.ManagerSysNo,
                        UserType          = UserType.Common,
                        LastLoginDateText = DateTimeHelper.GetTimeZoneNow().ToString("yyyy-MM-dd HH:mm:ss"),
                        ManagerLoginName  = cusomerInfo.ManagerLoginName,
                        ManagerName       = HttpUtility.UrlEncode(cusomerInfo.ManagerName)
                    };

                    if (cusomerInfo.ManagerSysNo.HasValue && cusomerInfo.ManagerSysNo.Value > 0)
                    {
                        appuser.UserType = UserType.Manager;
                        var company = CompanyService.GetCompanyUser(cusomerInfo.ManagerSysNo.Value);
                        if (company != null)
                        {
                            appuser.UserType = UserType.Installer;
                        }
                    }

                    UserMgr.Logout();
                    UserMgr.WriteUserInfo(appuser);
                    if (!string.IsNullOrEmpty(callbackUrl))
                    {
                        Response.Redirect(callbackUrl);
                        return;
                    }
                    Response.Redirect("/smoke/userInfo");
                    return;
                }
                else//新建client
                {
                    customer.AppCustomerID = weiXinUser.Openid;
                    customer.Name          = weiXinUser.NickName;
                    customer.HeaderImage   = weiXinUser.HeadImgUrl;
                    customer.EditTime      = DateTimeHelper.GetTimeZoneNow();
                    customer.RegisterTime  = DateTimeHelper.GetTimeZoneNow();
                    //创建用户
                    customer.SysNo = ClientService.InsertClient(customer);
                    var appuser = new AppUserInfo()
                    {
                        AppCustomerID     = weiXinUser.Openid,
                        UserSysNo         = customer.SysNo,
                        UserID            = HttpUtility.UrlEncode(customer.Name),
                        UserDisplayName   = HttpUtility.UrlEncode(customer.Name),
                        HeadImage         = customer.HeaderImage,
                        UserType          = UserType.Common,
                        LastLoginDateText = DateTimeHelper.GetTimeZoneNow().ToString("yyyy-MM-dd HH:mm:ss")
                    };
                    UserMgr.Logout();
                    UserMgr.WriteUserInfo(appuser);
                    if (!string.IsNullOrEmpty(callbackUrl))
                    {
                        Response.Redirect(callbackUrl);
                        return;
                    }
                    Response.Redirect("/smoke/userInfo");
                    return;
                }
            }
        }
コード例 #16
0
        private static void Main()
        {
            var service = new WeiXinService();

            //登录微信号。
            service.Login("chunsun_cc", "123456");

            //获取用户信息。
            var user = service.GetUserInfo();

            Console.WriteLine("名称:" + user.Name);
            Console.WriteLine("登录邮箱:" + user.LoginEmail);
            Console.WriteLine("原始ID:" + user.OriginalId);
            Console.WriteLine("微信号:" + user.UserName);
            Console.WriteLine("类型:" + user.Type);
            Console.WriteLine("认证情况:" + user.AuthenticateStatus);
            Console.WriteLine("主体信息:" + user.Body);
            Console.WriteLine("地区:" + user.Area);
            Console.WriteLine("功能介绍:" + user.Description);
            Console.WriteLine("是否有头像:" + ((user.Picture.Value == null || user.Picture.Value.Length <= 0) ? "否" : "是"));
            Console.WriteLine("二维码:" + ((user.QrCode.Value == null || user.QrCode.Value.Length <= 0) ? "获取二维码失败!" : "获取成功。"));

            Console.WriteLine();
            Console.WriteLine();

            /*//开启开发者模式。
             * service.SetDevelopMode(true);
             * //关闭开发者模式。
             * service.SetDevelopMode(false);
             * //开启编辑模式。
             * service.SetEditMode(true);
             * //关闭编辑模式。
             * service.SetEditMode(false);
             * //设置开发接口信息。
             * service.SetDevelopInterface("{Url}", "{token}");*/

            //获取开发者凭据。
            var developCredential = service.GetDevelopCredential();

            if (developCredential != null)
            {
                Console.WriteLine("AppId:" + developCredential.AppId);
                Console.WriteLine("AppSecret:" + developCredential.AppSecret);
            }
            else
            {
                Console.WriteLine("用户不是服务号不具有开发者凭据。");
            }

            Console.WriteLine();

            //得到当天的关注信息。
            var attention = service.GetAttentions(DateTime.Now);

            Action <AttentionInfo> writerAttention = model =>
            {
                Console.WriteLine("时间:{0}", model.Date.ToString("yyyy-MM-dd"));
                Console.WriteLine("新关注人数:{0}", model.NewUser);
                Console.WriteLine("取消关注人数:{0}", model.CancelUser);
                Console.WriteLine("净增关注人数:{0}", model.NetUser);
                Console.WriteLine("累积关注人数:{0}", model.CumulateUser);
            };
            var defaultColor = Console.ForegroundColor;

            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("当天关注信息:\r\n");
            Console.ForegroundColor = defaultColor;
            writerAttention(attention);

            Console.WriteLine("\r\n==============================");
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("7天之内的关注信息:\r\n");
            Console.ForegroundColor = defaultColor;

            //得到7天之内的关注量
            var attentions = service.GetAttentions(DateTime.Now.Subtract(TimeSpan.FromDays(7)), DateTime.Now);

            foreach (var item in attentions)
            {
                writerAttention(item);
                Console.WriteLine("==============================");
            }
        }
コード例 #17
0
        /// <summary>
        /// 根据订单创建paylog
        /// </summary>
        /// <returns></returns>
        private IList <WeixinPayLog> createWeixinPayLog(long orderId, int userId, out string message)
        {
            var order   = OrderService.GetOrder(userId, orderId);
            var user    = UserService.GetUserByUserId(order.UserId);
            var product = ProductService.GetProductById(order.ProductId);

            if (order.Status == OrderStatus.WaitingConfirm.GetHashCode() && product.EndTime.AddDays(product.EarningDay) < DateTime.Now)
            {
                if (order.PayType == 0)
                {
                    var refundPrincipal = order.Price * order.ProductCount; //购买本金
                    var descPrincipal   = string.Format("羊客【{0}】结算本金", product.Name);
                    var count           = 1;
                    var amount          = refundPrincipal;
                    while (amount > 0M)
                    {
                        var desc = "";
                        if (amount <= payUpperLimit)
                        {
                            if (count > 1)
                            {
                                desc = string.Format("{0}第{1}笔", descPrincipal, count);
                            }
                            else
                            {
                                desc = descPrincipal;
                            }
                            WeiXinService.InsertWeixinPayLog(new WeixinPayLog()
                            {
                                Amount      = amount,
                                Description = desc,
                                OrderId     = order.OrderId,
                                WxOpenId    = user.WxOpenId,
                                Status      = 0,
                                CreateTime  = DateTime.Now
                            });
                            amount = 0M;
                        }
                        else
                        {
                            desc = string.Format("{0}第{1}笔", descPrincipal, count);
                            WeiXinService.InsertWeixinPayLog(new WeixinPayLog()
                            {
                                Amount      = payUpperLimit,
                                Description = desc,
                                OrderId     = order.OrderId,
                                WxOpenId    = user.WxOpenId,
                                Status      = 0,
                                CreateTime  = DateTime.Now
                            });
                            amount = amount - payUpperLimit;
                        }
                        count++;
                    }


                    var refundBonus = product.Earning * order.ProductCount;
                    var descBonus   = string.Format("羊客【{0}】结算收益", product.Name);
                    WeiXinService.InsertWeixinPayLog(new WeixinPayLog()
                    {
                        Amount      = refundBonus,
                        Description = descBonus,
                        OrderId     = order.OrderId,
                        WxOpenId    = user.WxOpenId,
                        Status      = 0,
                        CreateTime  = DateTime.Now
                    });
                    message = "插入成功";
                    return(WeiXinService.GetPayLogListByOrderId(orderId));
                }
                else
                {
                    message = "订单为线下支付订单,请直接在订单列表处操作";
                    return(null);
                }
            }
            else
            {
                message = "订单状态不是【待确认结算】或订单尚未达到结算期";
                return(null);
            }
        }
コード例 #18
0
 /// <summary>
 /// AJAX获取微信支付日志
 /// </summary>
 /// <param name="orderId"></param>
 /// <returns></returns>
 public JsonResult GetWeixinPayLogByOrderId(long orderId)
 {
     return(Json(WeiXinService.GetPayLogListByOrderId(orderId)));
 }
コード例 #19
0
ファイル: MenuService.cs プロジェクト: fleetscythe/YuChang
 internal MenuService(WeiXinService weixin)
 {
     this.weixin = weixin;
 }
コード例 #20
0
 public WeiXinController(WeiXinService service)
 {
     _service = service;
 }
コード例 #21
0
 public JsonResult DelKeyword(int id)
 {
     WeiXinService.AutoReplyMessageUpdateStatus(id, 0);
     return(Json(1));
 }
コード例 #22
0
        public JsonResult CheckKeyword(string keyword)
        {
            var result = WeiXinService.AutoReplyMessageCheckKeyword(keyword);

            return(Json(result));
        }
コード例 #23
0
 public TemplateService(WeiXinService weixin)
 {
     this.weixin = weixin;
 }
コード例 #24
0
 public WeiXinReplayController(WeiXinService weiXinService)
 {
     _weiXinService = weiXinService;
 }
コード例 #25
0
ファイル: HomeController.cs プロジェクト: zzb-private/WeiXin
 public HomeController(WeiXinService weiXinService)
 {
     _weiXinService = weiXinService;
 }
コード例 #26
0
        string EventClickAction(ReceiveXmlMessage receiveMsg)
        {
            var result   = string.Empty;
            var eventMsg = receiveMsg as ReceiveXmlEventMessage;

            if (eventMsg.EventKey.Equals("1"))
            {
                var sendMsg = new SendXmlTextMessage();
                sendMsg.ToUserName   = receiveMsg.FromUserName;
                sendMsg.FromUserName = receiveMsg.ToUserName;
                sendMsg.Content      = "被动文本消息";
                result = sendMsg.ToXml();
            }
            else if (eventMsg.EventKey.Equals("2"))
            {
                var sendMsg = new SendXmlNewsMessage();
                sendMsg.ToUserName   = receiveMsg.FromUserName;
                sendMsg.FromUserName = receiveMsg.ToUserName;
                sendMsg.Articles     = new List <SendXmlArticle>();
                sendMsg.Articles.Add(new SendXmlArticle {
                    Title = "被动单图文消息", Description = "被动单图文消息,此处省略一万字。。。", PicUrl = "http://h.hiphotos.baidu.com/image/pic/item/c9fcc3cec3fdfc037d970d53d63f8794a5c2266a.jpg", Url = "http://www.wangwenzhuang.com/"
                });
                result = sendMsg.ToXml();
            }
            else if (eventMsg.EventKey.Equals("3"))
            {
                var sendMsg = new SendXmlNewsMessage();
                sendMsg.ToUserName   = receiveMsg.FromUserName;
                sendMsg.FromUserName = receiveMsg.ToUserName;
                sendMsg.Articles     = new List <SendXmlArticle>();
                sendMsg.Articles.Add(new SendXmlArticle {
                    Title = "被动多图文消息1", Description = "被动多图文消息,此处省略一万字。。。", PicUrl = "http://h.hiphotos.baidu.com/image/pic/item/c9fcc3cec3fdfc037d970d53d63f8794a5c2266a.jpg", Url = "http://www.wangwenzhuang.com/"
                });
                sendMsg.Articles.Add(new SendXmlArticle {
                    Title = "被动多图文消息2", Description = "被动多图文消息,此处省略一万字。。。", PicUrl = "http://g.hiphotos.baidu.com/image/pic/item/55e736d12f2eb93895023c7fd7628535e4dd6fcb.jpg", Url = "http://www.wangwenzhuang.com/"
                });
                sendMsg.Articles.Add(new SendXmlArticle {
                    Title = "被动多图文消息3", Description = "被动多图文消息,此处省略一万字。。。", PicUrl = "http://e.hiphotos.baidu.com/image/pic/item/63d0f703918fa0ec8426f0f7249759ee3c6ddb63.jpg", Url = "http://www.wangwenzhuang.com/"
                });
                result = sendMsg.ToXml();
            }
            else if (eventMsg.EventKey.Equals("4"))
            {
                Task t = new Task(() =>
                {
                    var sendMsg     = new CustomerJsonTextMessage();
                    sendMsg.Touser  = receiveMsg.FromUserName;
                    sendMsg.Content = "客服文本消息";
                    WeiXinService.SendCustomerMessage(sendMsg, WeiXinConfig.AppId, WeiXinConfig.AppSecret);
                });
                t.Start();
            }
            else if (eventMsg.EventKey.Equals("5"))
            {
                Task t = new Task(() =>
                {
                    var sendMsg      = new CustomerJsonNewsMessage();
                    sendMsg.Touser   = receiveMsg.FromUserName;
                    var title        = "客服单图文消息";
                    var discription  = "被动单图文消息,此处省略一万字。。。";
                    var url          = "http://www.wangwenzhuang.com/";
                    sendMsg.Articles = new List <CustomerJsonArticleMessage>();
                    sendMsg.Articles.Add(new CustomerJsonArticleMessage {
                        Title = title, Description = discription, PicUrl = "http://h.hiphotos.baidu.com/image/pic/item/c9fcc3cec3fdfc037d970d53d63f8794a5c2266a.jpg", Url = url
                    });
                    WeiXinService.SendCustomerMessage(sendMsg, WeiXinConfig.AppId, WeiXinConfig.AppSecret);
                });
                t.Start();
            }
            else if (eventMsg.EventKey.Equals("6"))
            {
                Task t = new Task(() =>
                {
                    var sendMsg      = new CustomerJsonNewsMessage();
                    sendMsg.Touser   = receiveMsg.FromUserName;
                    var discription  = "被动单图文消息,此处省略一万字。。。";
                    var url          = "http://www.wangwenzhuang.com/";
                    sendMsg.Articles = new List <CustomerJsonArticleMessage>();
                    sendMsg.Articles.Add(new CustomerJsonArticleMessage {
                        Title = "客服多图文消息1", Description = discription, PicUrl = "http://h.hiphotos.baidu.com/image/pic/item/c9fcc3cec3fdfc037d970d53d63f8794a5c2266a.jpg", Url = url
                    });
                    sendMsg.Articles.Add(new CustomerJsonArticleMessage {
                        Title = "客服多图文消息2", Description = discription, PicUrl = "http://g.hiphotos.baidu.com/image/pic/item/55e736d12f2eb93895023c7fd7628535e4dd6fcb.jpg", Url = url
                    });
                    sendMsg.Articles.Add(new CustomerJsonArticleMessage {
                        Title = "客服多图文消息3", Description = discription, PicUrl = "http://e.hiphotos.baidu.com/image/pic/item/63d0f703918fa0ec8426f0f7249759ee3c6ddb63.jpg", Url = url
                    });
                    WeiXinService.SendCustomerMessage(sendMsg, WeiXinConfig.AppId, WeiXinConfig.AppSecret);
                });
                t.Start();
            }
            else if (eventMsg.EventKey.Equals("7"))
            {
                var sendMsg = new SendXmlTextMessage();
                sendMsg.ToUserName   = receiveMsg.FromUserName;
                sendMsg.FromUserName = receiveMsg.ToUserName;
                sendMsg.Content      = "请说一段语音发来。";
                result = sendMsg.ToXml();
            }
            else if (eventMsg.EventKey.Equals("8"))
            {
                var sendMsg = new SendXmlTextMessage();
                sendMsg.ToUserName   = receiveMsg.FromUserName;
                sendMsg.FromUserName = receiveMsg.ToUserName;
                sendMsg.Content      = string.Format("<a href=\"http://112.126.67.94/wxtest/ViewOpenId.html?OpenId={0}\">获取OpenId</a>", receiveMsg.FromUserName);
                result = sendMsg.ToXml();
            }
            else if (eventMsg.EventKey.Equals("9"))
            {
                var sendMsg = new SendXmlTextMessage();
                sendMsg.ToUserName   = receiveMsg.FromUserName;
                sendMsg.FromUserName = receiveMsg.ToUserName;
                sendMsg.Content      = string.Format("OAuth2.0授权分两种,第一种获取获取 OpenId,不弹出授权界面;第二种弹出授权界面,不但能获取 OpenId,还可以获取用户的信息。\r\n<a href=\"https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri=http%3a%2f%2f112.126.67.94%2fwxtest%2fOAuth2_snsapi_base.aspx&response_type=code&scope=snsapi_base&state=0#wechat_redirect\">第一种</a>\r\n<a href=\"https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri=http://112.126.67.94/wxtest/OAuth2_snsapi_userinfo.aspx&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect\">第二种</a>", WeiXinConfig.AppId);
                result = sendMsg.ToXml();
            }
            else if (eventMsg.EventKey.Equals("12"))
            {
                Task t = new Task(() =>
                {
                    // 获取已关注列表
                    var openIds = WeiXinService.GetSubscribeUserList(WeiXinConfig.AppId, WeiXinConfig.AppSecret);
                    if (openIds != null && openIds.Count > 0)
                    {
                        var discription = string.Empty;
                        // 获取已关注列表每个人的基本信息
                        for (int i = 0; i < openIds.Count; i++)
                        {
                            var userInfo = WeiXinService.GetSubscribeUserInfo(openIds[i], WeiXinConfig.AppId, WeiXinConfig.AppSecret);
                            if (i + 1 == openIds.Count)
                            {
                                discription += string.Format("{0}、{1}", i + 1, userInfo.NickName);
                            }
                            else
                            {
                                discription += string.Format("{0}、{1}\r\n\r\n", i + 1, userInfo.NickName);
                            }
                        }
                        var sendMsg      = new CustomerJsonNewsMessage();
                        sendMsg.Touser   = receiveMsg.FromUserName;
                        var title        = "已关注用户信息";
                        var url          = "http://www.wangwenzhuang.com/";
                        sendMsg.Articles = new List <CustomerJsonArticleMessage>();
                        sendMsg.Articles.Add(new CustomerJsonArticleMessage {
                            Title = title, Description = discription, Url = url
                        });
                        WeiXinService.SendCustomerMessage(sendMsg, WeiXinConfig.AppId, WeiXinConfig.AppSecret);
                    }
                });
                t.Start();
            }
            return(result);
        }
コード例 #27
0
        /// <summary>
        /// 企业支付
        /// </summary>
        /// <param name="openId">openId</param>
        /// <param name="payCode">支付ID,订单号+支付日志ID</param>
        /// <param name="amount">金额</param>
        /// <param name="desc">付款描述信息</param>
        /// <returns></returns>
        public static string QYPay(string openId, string payCode, decimal amount, string desc)
        {
            var payStatus = 1;
            //创建支付应答对象
            RequestHandler packageReqHandler = new RequestHandler(null);
            var            nonceStr          = TenPayV3Util.GetNoncestr();

            //创建请求接口参数
            packageReqHandler.SetParameter("mch_appid", AppId);
            packageReqHandler.SetParameter("mchid", Mchid);
            packageReqHandler.SetParameter("nonce_str", nonceStr);
            packageReqHandler.SetParameter("partner_trade_no", payCode);
            packageReqHandler.SetParameter("openid", openId);
            packageReqHandler.SetParameter("check_name", "NO_CHECK");//不校验用户姓名
            packageReqHandler.SetParameter("desc", desc);
            packageReqHandler.SetParameter("amount", Convert.ToInt32(amount * 100).ToString());
            packageReqHandler.SetParameter("spbill_create_ip", IP);
            string sign = packageReqHandler.CreateMd5Sign("key", PayKey);

            packageReqHandler.SetParameter("sign", sign);

            string data = packageReqHandler.ParseXML();

            //证书相关
            var cert          = new X509Certificate2(SSLCERT_PATH, SSLCERT_PASSWORD);
            var access        = new WeixinPayLogDataAccess();
            var weixinService = new WeiXinService(access);

            try
            {
                //调用企业支付接口
                var result = TenPayV3.QYPay(data, cert);
                logger.Info("企业支付返回信息:" + result);
                var    unifiedorderRes = XDocument.Parse(result);
                string return_code     = unifiedorderRes.Element("xml").Element("return_code").Value;
                if (return_code == "SUCCESS")
                {
                    payStatus = 1;
                }
                else
                {
                    payStatus = 0;
                }

                return(return_code);
            }
            catch (Exception e)
            {
                logger.Error(e);
                //payStatus = 0;
                //var paylog = new WeixinPayLog()
                //{
                //    OrderId = orderId,
                //    WxOpenId = openId,
                //    Description = desc,
                //    Amount = amount,
                //    Status = payStatus,
                //    CreateTime = DateTime.Now
                //};
                //weixinService.InsertWeixinPayLog(paylog);
                return("ERROR");
            }
        }