예제 #1
0
        /**
         *
         * 关闭订单
         * @param WxPayData inputObj 提交给关闭订单API的参数
         * @param int timeOut 接口超时时间
         * @throws WxPayException
         * @return 成功时返回,其他抛异常
         */
        public static WxPayData CloseOrder(WxPayData inputObj, WX_ApiConfig config, int timeOut = 6)
        {
            string url = "https://api.mch.weixin.qq.com/pay/closeorder";

            //检测必填参数
            if (!inputObj.IsSet("out_trade_no"))
            {
                throw new WxPayException("关闭订单接口中,out_trade_no必填!");
            }

            inputObj.SetValue("appid", WxPayConfig.APPID);        //公众账号ID
            inputObj.SetValue("mch_id", WxPayConfig.MCHID);       //商户号
            inputObj.SetValue("nonce_str", GenerateNonceStr());   //随机字符串
            inputObj.SetValue("sign", inputObj.MakeSign(config)); //签名
            string xml = inputObj.ToXml();

            var start = DateTime.Now;        //请求开始时间

            string response = HttpService.Post(xml, url, false, timeOut, config);

            var end      = DateTime.Now;
            int timeCost = (int)((end - start).TotalMilliseconds);

            WxPayData result = new WxPayData();

            result.FromXml(response, config);

            ReportCostTime(url, timeCost, result, config);       //测速上报

            return(result);
        }
예제 #2
0
        /**
         *
         * 撤销订单,如果失败会重复调用10次
         * @param string out_trade_no 商户订单号
         * @param depth 调用次数,这里用递归深度表示
         * @return false表示撤销失败,true表示撤销成功
         */
        public static bool Cancel(string out_trade_no, WX_ApiConfig config, int depth = 0)
        {
            if (depth > 10)
            {
                return(false);
            }

            WxPayData reverseInput = new WxPayData();

            reverseInput.SetValue("out_trade_no", out_trade_no);
            WxPayData result = WxPayApi.Reverse(reverseInput, config);

            //接口调用失败
            if (result.GetValue("return_code").ToString() != "SUCCESS")
            {
                return(false);
            }

            //如果结果为success且不需要重新调用撤销,则表示撤销成功
            if (result.GetValue("result_code").ToString() != "SUCCESS" && result.GetValue("recall").ToString() == "N")
            {
                return(true);
            }
            else if (result.GetValue("recall").ToString() == "Y")
            {
                return(Cancel(out_trade_no, config, ++depth));
            }
            return(false);
        }
예제 #3
0
        public ActionResult Index(string companyId)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(companyId))
                {
                    return(RedirectToAction("Index", "BrowseError", new { errorMsg = "请打开扫一扫" }));
                }
                WX_ApiConfig config    = WXApiConfigServices.QueryWXApiConfig(companyId);
                var          timeStamp = DateTimeHelper.TransferUnixDateTime(DateTime.Now).ToString();
                var          nonceStr  = StringHelper.GetRndString(16);
                var          url       = Request.Url.ToString();

                var    accessToken = AccessTokenContainer.TryGetToken(config.AppId, config.AppSecret, false);
                var    ticket      = WxAdvApi.GetTicket(accessToken);
                string signature   = WxService.GetJsApiSignature(nonceStr, ticket.ticket, timeStamp, url);
                ViewBag.Signature = signature;
                ViewBag.AppId     = config.AppId;
                ViewBag.Timestamp = timeStamp;
                ViewBag.NonceStr  = nonceStr;
                return(View());
            }
            catch (Exception ex)
            {
                ExceptionsServices.AddExceptionToDbAndTxt("WeiXinPageError", "调用扫码方法异常", ex, LogFrom.WeiXin);
                return(RedirectToAction("Index", "BrowseError", new { errorMsg = "调用扫码方法异常" }));
            }
        }
예제 #4
0
 public bool Update(WX_ApiConfig model)
 {
     using (DbOperator dbOperator = ConnectionManager.CreateConnection())
     {
         StringBuilder strSql = new StringBuilder();
         strSql.Append("update WX_ApiConfig set Domain=@Domain,ServerIP=@ServerIP,SystemName=@SystemName,AppId=@AppId,AppSecret=@AppSecret,Token=@Token,Status=@Status,SupportSuperiorPay=@SupportSuperiorPay ");
         dbOperator.ClearParameters();
         if (!string.IsNullOrWhiteSpace(model.SystemLogo))
         {
             strSql.Append(",SystemLogo=@SystemLogo");
             dbOperator.AddParameter("SystemLogo", model.SystemLogo);
         }
         strSql.Append(" where CompanyID=@CompanyID");
         dbOperator.AddParameter("CompanyID", model.CompanyID);
         dbOperator.AddParameter("Domain", model.Domain);
         dbOperator.AddParameter("ServerIP", model.ServerIP);
         dbOperator.AddParameter("SystemName", model.SystemName);
         dbOperator.AddParameter("AppId", model.AppId);
         dbOperator.AddParameter("AppSecret", model.AppSecret);
         dbOperator.AddParameter("Token", model.Token);
         dbOperator.AddParameter("Status", model.Status);
         dbOperator.AddParameter("SupportSuperiorPay", model.SupportSuperiorPay);
         return(dbOperator.ExecuteNonQuery(strSql.ToString()) > 0);
     }
 }
예제 #5
0
        /**
         *
         * 撤销订单API接口
         * @param WxPayData inputObj 提交给撤销订单API接口的参数,out_trade_no和transaction_id必填一个
         * @param int timeOut 接口超时时间
         * @throws WxPayException
         * @return 成功时返回API调用结果,其他抛异常
         */
        public static WxPayData Reverse(WxPayData inputObj, WX_ApiConfig config, int timeOut = 6)
        {
            string url = "https://api.mch.weixin.qq.com/secapi/pay/reverse";

            //检测必填参数
            if (!inputObj.IsSet("out_trade_no") && !inputObj.IsSet("transaction_id"))
            {
                throw new WxPayException("撤销订单API接口中,参数out_trade_no和transaction_id必须填写一个!");
            }

            inputObj.SetValue("appid", config.AppId);             //公众账号ID
            inputObj.SetValue("mch_id", config.PartnerId);        //商户号
            inputObj.SetValue("nonce_str", GenerateNonceStr());   //随机字符串
            inputObj.SetValue("sign", inputObj.MakeSign(config)); //签名
            string xml = inputObj.ToXml();

            var start = DateTime.Now;//请求开始时间

            Log.Debug("WxPayApi", "Reverse request : " + xml);

            string response = HttpService.Post(xml, url, true, timeOut, config);

            Log.Debug("WxPayApi", "Reverse response : " + response);

            var end      = DateTime.Now;
            int timeCost = (int)((end - start).TotalMilliseconds);

            WxPayData result = new WxPayData();

            result.FromXml(response, config);

            ReportCostTime(url, timeCost, result, config);//测速上报

            return(result);
        }
예제 #6
0
        /**
         *
         * 检测签名是否正确
         * 正确返回true,错误抛异常
         */
        public bool CheckSign(WX_ApiConfig config)
        {
            //如果没有设置签名,则跳过检测
            if (!IsSet("sign"))
            {
                Log.Error(this.GetType().ToString(), "WxPayData签名存在但不合法!");
                throw new WxPayException("WxPayData签名存在但不合法!");
            }
            //如果设置了签名但是签名为空,则抛异常
            else if (GetValue("sign") == null || GetValue("sign").ToString() == "")
            {
                Log.Error(this.GetType().ToString(), "WxPayData签名存在但不合法!");
                throw new WxPayException("WxPayData签名存在但不合法!");
            }

            //获取接收到的签名
            string return_sign = GetValue("sign").ToString();

            //在本地计算新的签名
            string cal_sign = MakeSign(config);

            if (cal_sign == return_sign)
            {
                return(true);
            }

            Log.Error(this.GetType().ToString(), "WxPayData签名验证错误!");
            throw new WxPayException("WxPayData签名验证错误!");
        }
예제 #7
0
        /// <summary>
        /// 发送音乐消息
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="openId"></param>
        /// <param name="title">音乐标题(非必须)</param>
        /// <param name="description">音乐描述(非必须)</param>
        /// <param name="musicUrl">音乐链接</param>
        /// <param name="hqMusicUrl">高品质音乐链接,wifi环境优先使用该链接播放音乐</param>
        /// <param name="thumbMediaId">视频缩略图的媒体ID</param>
        /// <returns></returns>
        public static bool SendMusic(string companyId, string accessToken, string openId, string title, string description, string musicUrl, string hqMusicUrl, string thumbMediaId)
        {
            var data = new
            {
                touser  = openId,
                msgtype = "music",
                music   = new
                {
                    title          = title,
                    description    = description,
                    musicurl       = musicUrl,
                    hqmusicurl     = hqMusicUrl,
                    thumb_media_id = thumbMediaId
                }
            };
            ResError result = WxHttp.Post(WxUrl.SendMsg.ToFormat(accessToken), data);

            if (result.errcode == ResCode.请求成功)
            {
                return(true);
            }

            if (result.errcode == ResCode.获取accessToken时AppSecret错误或者accessToken无效)
            {
                WX_ApiConfig config         = WXApiConfigServices.QueryWXApiConfig(companyId);
                var          newAccessToken = AccessTokenContainer.TryGetToken(config.AppId, config.AppSecret, true);
                ResError     newResult      = WxHttp.Post(WxUrl.SendMsg.ToFormat(newAccessToken), data);
                if (newResult.errcode == ResCode.请求成功)
                {
                    return(true);
                }
            }
            TxtLogServices.WriteTxtLogEx("WeiXinBase", "发送音乐消息错误!错误代码:{0},说明:{1}", (int)result.errcode, result.errmsg);
            return(false);
        }
예제 #8
0
        public IWRespBase ReplyContent(WX_ApiConfig config, WX_Keyword gKey, WReqBase request, string qValue)
        {
            var response = request.CreateResponse <WRespText>();

            response.Content = gKey.Text;
            return(response);
        }
예제 #9
0
        /// <summary>
        /// 发送语音消息
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="openId"></param>
        /// <param name="mediaId"></param>
        /// <returns></returns>
        public static bool SendVoice(string companyId, string accessToken, string openId, string mediaId)
        {
            var data = new
            {
                touser  = openId,
                msgtype = "voice",
                voice   = new
                {
                    media_id = mediaId
                }
            };

            ResError result = WxHttp.Post(WxUrl.SendMsg.ToFormat(accessToken), data);

            if (result.errcode == ResCode.请求成功)
            {
                return(true);
            }
            if (result.errcode == ResCode.获取accessToken时AppSecret错误或者accessToken无效)
            {
                WX_ApiConfig config         = WXApiConfigServices.QueryWXApiConfig(companyId);
                var          newAccessToken = AccessTokenContainer.TryGetToken(config.AppId, config.AppSecret, true);
                ResError     newResult      = WxHttp.Post(WxUrl.SendMsg.ToFormat(newAccessToken), data);
                if (newResult.errcode == ResCode.请求成功)
                {
                    return(true);
                }
            }
            TxtLogServices.WriteTxtLogEx("WeiXinBase", "发送语音消息错误!错误代码:{0},说明:{1}", (int)result.errcode, result.errmsg);
            return(false);
        }
예제 #10
0
        public static WX_Info GetWxUserBaseInfo(WX_ApiConfig config, string openId, bool errorRetry = true)
        {
            var accessToken = AccessTokenContainer.TryGetToken(config.AppId, config.AppSecret);

            if (!string.IsNullOrWhiteSpace(accessToken) && !string.IsNullOrWhiteSpace(openId))
            {
                try
                {
                    WX_Info user     = new WX_Info();
                    var     userInfo = WxAdvApi.GetUserInfo(accessToken, openId);
                    if (userInfo.subscribe == 0)
                    {
                        return(null);
                    }
                    user.City              = userInfo.city;
                    user.Country           = userInfo.country;
                    user.Headimgurl        = DownloadHeadImg(openId, userInfo.headimgurl, config.CompanyID);
                    user.Language          = userInfo.language;
                    user.NickName          = userInfo.nickname;
                    user.Province          = userInfo.province;
                    user.Sex               = userInfo.sex == "1" ? "M" : "F";
                    user.LastSubscribeDate = DateTimeHelper.TransferUnixDateTime(userInfo.subscribe_time);
                    return(user);
                }
                catch (Exception)
                {
                    if (errorRetry)
                    {
                        GetWxUserBaseInfo(config, openId, false);
                    }
                }
            }
            return(null);
        }
예제 #11
0
        /**
         *
         * 转换短链接
         * 该接口主要用于扫码原生支付模式一中的二维码链接转成短链接(weixin://wxpay/s/XXXXXX),
         * 减小二维码数据量,提升扫描速度和精确度。
         * @param WxPayData inputObj 提交给转换短连接API的参数
         * @param int timeOut 接口超时时间
         * @throws WxPayException
         * @return 成功时返回,其他抛异常
         */
        public static WxPayData ShortUrl(WxPayData inputObj, WX_ApiConfig config, int timeOut = 6)
        {
            string url = "https://api.mch.weixin.qq.com/tools/shorturl";

            //检测必填参数
            if (!inputObj.IsSet("long_url"))
            {
                throw new WxPayException("需要转换的URL,签名用原串,传输需URL encode!");
            }

            inputObj.SetValue("appid", WxPayConfig.APPID);        //公众账号ID
            inputObj.SetValue("mch_id", WxPayConfig.MCHID);       //商户号
            inputObj.SetValue("nonce_str", GenerateNonceStr());   //随机字符串
            inputObj.SetValue("sign", inputObj.MakeSign(config)); //签名
            string xml = inputObj.ToXml();

            var start = DateTime.Now;        //请求开始时间

            Log.Debug("WxPayApi", "ShortUrl request : " + xml);
            string response = HttpService.Post(xml, url, false, timeOut, config);

            Log.Debug("WxPayApi", "ShortUrl response : " + response);

            var end      = DateTime.Now;
            int timeCost = (int)((end - start).TotalMilliseconds);

            WxPayData result = new WxPayData();

            result.FromXml(response, config);
            ReportCostTime(url, timeCost, result, config);            //测速上报

            return(result);
        }
예제 #12
0
        /// <summary>
        /// 发送商家充值失败 退款失败提醒
        /// </summary>
        /// <param name="orderId">订单编号</param>
        /// <param name="reason">原因</param>
        /// <param name="money">金额</param>
        /// <param name="openId">接受者openid</param>
        /// <returns></returns>
        public static bool SendSellerRechargeRefundFail(string companyId, string orderId, string reason, decimal money, string openId)
        {
            try
            {
                string value = WXOtherConfigServices.GetConfigValue(companyId, ConfigType.ParkingRefundFailTemplateId);
                if (string.IsNullOrWhiteSpace(value))
                {
                    return(false);
                }


                string       firstDes    = "您好,商家充值失败了,同时退款失败了。";
                string       topColor    = "#FF0000";
                WX_ApiConfig config      = GetWX_ApiConfig(companyId);
                var          accessToken = AccessTokenContainer.TryGetToken(config.AppId, config.AppSecret);
                var          data        = new
                {
                    first    = new { value = firstDes, color = "#173177" },
                    keyword1 = new { value = orderId, color = "#173177" },
                    keyword2 = new { value = string.Format("{0}元", money), color = "#173177" },
                    keyword3 = new { value = reason, color = "#173177" },
                    remark   = new { value = "请尽快联系我们,我们将进行人工退款。", color = "#173177" }
                };
                return(WxAdvApi.SendTemplateMessage(companyId, accessToken, openId, value, topColor, data));
            }
            catch (Exception ex)
            {
                ExceptionsServices.AddExceptionToDbAndTxt("SendTemplateMessage", "发送发送商家充值失败通知失败", ex, LogFrom.WeiXin);
                return(false);
            }
        }
예제 #13
0
        public static bool SendTemplateMessage <T>(string companyId, string accessToken, string openId, string templateId, string topcolor, T data)
        {
            var pdata = new Templete
            {
                template_id = templateId,
                topcolor    = topcolor,
                touser      = openId,
                data        = data
            };
            ResError result = WxHttp.Post(WxUrl.TemplateSend.ToFormat(accessToken), pdata);

            if (result.errcode == ResCode.请求成功)
            {
                return(true);
            }
            if (result.errcode == ResCode.获取accessToken时AppSecret错误或者accessToken无效)
            {
                WX_ApiConfig config         = WXApiConfigServices.QueryWXApiConfig(companyId);
                var          newAccessToken = AccessTokenContainer.TryGetToken(config.AppId, config.AppSecret, true);
                ResError     newResult      = WxHttp.Post(WxUrl.TemplateSend.ToFormat(newAccessToken), pdata);
                if (newResult.errcode == ResCode.请求成功)
                {
                    return(true);
                }
            }
            TxtLogServices.WriteTxtLogEx("WeiXinBase", "发送模板消息错误!错误代码:{0},说明:{1}", (int)result.errcode, result.errmsg);
            return(false);
        }
예제 #14
0
        /// <summary>
        /// 账号充值成功提醒
        /// </summary>
        /// <param name="orderId">订单编号</param>
        /// <param name="money">充值金额(元)</param>
        /// <param name="openId">接收者编号</param>
        /// <param name="balance">账号余额</param>
        /// <param name="payTime">充值时间</param>
        /// <returns></returns>
        //public static bool SendAccountRechargeSuccess(string orderId, decimal money, decimal balance, string openId, DateTime payTime)
        //{
        //    try
        //    {
        //        string value = WXOtherConfigServices.GetConfigValue(ConfigType.AccountRechargeSuccessTemplateId);
        //        if (string.IsNullOrWhiteSpace(value)) return false;

        //        string payTimeDes = string.Format("{0}月{1}日 {2}时{3}分", payTime.Month.ToString().PadLeft(2, '0'), payTime.Day.ToString().PadLeft(2, '0'), payTime.Hour.ToString().PadLeft(2, '0'), payTime.Minute.ToString().PadLeft(2, '0'));
        //        string topColor = "#FF0000";
        //        WX_ApiConfig config = GetWX_ApiConfig();
        //        var accessToken = AccessTokenContainer.TryGetToken(config.AppId, config.AppSecret);
        //        var data = new
        //        {
        //            first = new { value = "您好,您的账号已充值成功!", color = "#173177" },
        //            keyword1 = new { value = string.Format("{0}元", money), color = "#173177" },
        //            keyword2 = new { value = string.Format("{0}元", balance), color = "#173177" },
        //            keyword3 = new { value = orderId, color = "#173177" },
        //            keyword4 = new { value = payTimeDes, color = "#173177" },
        //            remark = new { value = "如有疑问,请尽快联系我们", color = "#173177" }
        //        };
        //        return WxAdvApi.SendTemplateMessage(accessToken, openId, value, topColor, data);
        //    }
        //    catch (Exception ex)
        //    {
        //        ExceptionsServices.AddExceptionToDbAndTxt("SendTemplateMessage", "发送账号充值成功提醒失败", ex, LogFrom.WeiXin);
        //        return false;
        //    }

        //}
        /// <summary>
        /// 月卡充值成功提醒
        /// </summary>
        /// <param name="plateNumber">车牌号</param>
        /// <param name="parkingName">停车场名称</param>
        /// <param name="money">支付金额(分)</param>
        /// <param name="lastEffectiveTime">最后有效期</param>
        /// <param name="openId">微信openid</param>
        /// <returns></returns>
        public static bool SendMonthCardRechargeSuccess(string companyId, string plateNumber, string parkingName, decimal money, DateTime lastEffectiveTime, string openId)
        {
            try
            {
                string value = WXOtherConfigServices.GetConfigValue(companyId, ConfigType.MonthCardRechargeSuccessTemplateId);
                if (string.IsNullOrWhiteSpace(value))
                {
                    return(false);
                }

                string topColor = "#FF0000";

                string       effectiveTime = string.Format("{0}年{1}月{2}日", lastEffectiveTime.Year, lastEffectiveTime.Month, lastEffectiveTime.Day);
                WX_ApiConfig config        = GetWX_ApiConfig(companyId);
                var          accessToken   = AccessTokenContainer.TryGetToken(config.AppId, config.AppSecret);
                var          data          = new
                {
                    first    = new { value = "您好,您的月卡已续期成功!", color = "#173177" },
                    keyword1 = new { value = plateNumber, color = "#173177" },
                    keyword2 = new { value = parkingName, color = "#173177" },
                    keyword3 = new { value = string.Format("{0}元", money), color = "#173177" },
                    keyword4 = new { value = string.Format("{0}元", money), color = "#173177" },
                    keyword5 = new { value = effectiveTime, color = "#173177" },
                    remark   = new { value = "感谢您的使用。", color = "#173177" }
                };
                return(WxAdvApi.SendTemplateMessage(companyId, accessToken, openId, value, topColor, data));
            }
            catch (Exception ex)
            {
                ExceptionsServices.AddExceptionToDbAndTxt("SendTemplateMessage", "发送月卡充值成功提醒失败", ex, LogFrom.WeiXin);
                return(false);
            }
        }
예제 #15
0
        /// <summary>
        /// 发送预约车位支付同步支付结果失败的 退款成功提醒
        /// </summary>
        /// <param name="orderId">订单编号</param>
        /// <param name="reason">原因</param>
        /// <param name="money">金额</param>
        /// <param name="openId">接受者openid</param>
        /// <returns></returns>
        public static bool SendBookingBitNoRefundSuccess(string companyId, string orderId, string reason, decimal money, string openId)
        {
            try
            {
                string value = WXOtherConfigServices.GetConfigValue(companyId, ConfigType.ParkingRefundSuccessTemplateId);
                if (string.IsNullOrWhiteSpace(value))
                {
                    return(false);
                }

                string       firstDes    = "您好,由于车场网络原因,您预约车位失败了,我们将您支付的钱返还到您的账号了,请查收。";
                string       topColor    = "#FF0000";
                WX_ApiConfig config      = GetWX_ApiConfig(companyId);
                var          accessToken = AccessTokenContainer.TryGetToken(config.AppId, config.AppSecret);
                var          data        = new
                {
                    first    = new { value = firstDes, color = "#173177" },
                    keyword1 = new { value = orderId, color = "#173177" },
                    keyword2 = new { value = reason, color = "#173177" },
                    keyword3 = new { value = string.Format("{0}元", money), color = "#173177" },
                    remark   = new { value = "如有疑问,请尽快联系我们。", color = "#173177" }
                };
                return(WxAdvApi.SendTemplateMessage(companyId, accessToken, openId, value, topColor, data));
            }
            catch (Exception ex)
            {
                ExceptionsServices.AddExceptionToDbAndTxt("SendTemplateMessage", "发送车位预订退款成功提醒失败", ex, LogFrom.WeiXin);
                return(false);
            }
        }
예제 #16
0
        /// <summary>
        /// 发送停车场入场通知
        /// </summary>
        /// <param name="plateNumber">车牌号</param>
        /// <param name="parkingName">停车场名称</param>
        /// <param name="entranceTime">进场时间</param>
        /// <param name="openId">接受消息的openid</param>
        public static bool SendParkIn(string companyId, string plateNumber, string parkingName, string entranceTime, string openId)
        {
            try
            {
                string value = WXOtherConfigServices.GetConfigValue(companyId, ConfigType.ParkInTemplateId);
                if (string.IsNullOrWhiteSpace(value))
                {
                    return(false);
                }

                string topColor = "#FF0000";
                string remark   = "谢谢您的支持!";

                WX_ApiConfig config      = GetWX_ApiConfig(companyId);
                var          accessToken = AccessTokenContainer.TryGetToken(config.AppId, config.AppSecret);
                var          data        = new
                {
                    first    = new { value = "欢迎您再次进入停车场\r\n", color = "#173177" },
                    keyword1 = new { value = plateNumber, color = "#173177" },
                    keyword2 = new { value = parkingName, color = "#173177" },
                    keyword3 = new { value = entranceTime.ToString(), color = "#173177" },
                    remark   = new { value = remark, color = "#173177" }
                };
                return(WxAdvApi.SendTemplateMessage(companyId, accessToken, openId, value, topColor, data));
            }
            catch (Exception ex)
            {
                ExceptionsServices.AddExceptionToDbAndTxt("SendTemplateMessage", "发送停车场入场通知失败", ex, LogFrom.WeiXin);
                return(false);
            }
        }
예제 #17
0
        public static IWRespBase GoGKey(WX_ApiConfig config, ReplyType rType, string qValue, WReqBase request)
        {
            var gkey = WXKeywordServices.QueryByReplyType(config.CompanyID, rType, qValue);

            if (gkey == null)
            {
                return(null);
            }
            IKey iKey;

            switch (gkey.KeywordType)
            {
            // 文字
            case KeywordType.Text:
                iKey = new ReplyText();
                break;

            // 图文
            case KeywordType.Article:
                iKey = new ReplyArticle();
                break;

            default:
                return(null);
            }
            return(iKey.ReplyContent(config, gkey, request, qValue));
        }
예제 #18
0
        /// <summary>
        /// 发送商家充值成功通知
        /// </summary>
        /// <param name="companyId">单位编号</param>
        /// <param name="money">充值金额(元)</param>
        /// <param name="balance">账号预额(元)</param>
        /// <param name="realPayTime">支付时间</param>
        /// <param name="openId">接受消息的openid</param>
        public static bool SendSellerRechargeSuccess(string companyId, decimal money, decimal balance, DateTime realPayTime, string openId)
        {
            try
            {
                string value = WXOtherConfigServices.GetConfigValue(companyId, ConfigType.SellerRechargeTemplateId);
                if (string.IsNullOrWhiteSpace(value))
                {
                    return(false);
                }

                string topColor   = "#FF0000";
                string payTimeDes = string.Format("{0}月{1}日 {2}时{3}分", realPayTime.Month.ToString().PadLeft(2, '0'), realPayTime.Day.ToString().PadLeft(2, '0'), realPayTime.Hour.ToString().PadLeft(2, '0'), realPayTime.Minute.ToString().PadLeft(2, '0'));

                WX_ApiConfig config      = GetWX_ApiConfig(companyId);
                var          accessToken = AccessTokenContainer.TryGetToken(config.AppId, config.AppSecret);
                var          data        = new
                {
                    first    = new { value = "您好,您已充值成功!", color = "#173177" },
                    keyword1 = new { value = payTimeDes, color = "#173177" },
                    keyword2 = new { value = money, color = "#173177" },
                    keyword3 = new { value = balance, color = "#173177" },
                    remark   = new { value = "您的充值已成功,可在充值记录查看明细", color = "#173177" }
                };
                return(WxAdvApi.SendTemplateMessage(companyId, accessToken, openId, value, topColor, data));
            }
            catch (Exception ex)
            {
                ExceptionsServices.AddExceptionToDbAndTxt("SendTemplateMessage", "发送停车场缴费成功通知失败", ex, LogFrom.WeiXin);
                return(false);
            }
        }
예제 #19
0
        /// <summary>
        /// 移动用户分组
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="openId"></param>
        /// <param name="toGroupId"></param>
        /// <returns></returns>
        public static bool UpdateUserGroup(string companyId, string accessToken, string openId, int toGroupId)
        {
            var data = new
            {
                openid     = openId,
                to_groupid = toGroupId
            };
            ResError result = WxHttp.Post(WxUrl.UpdateUserGroup.ToFormat(accessToken), data);

            if (result.errcode == ResCode.请求成功)
            {
                return(true);
            }
            if (result.errcode == ResCode.获取accessToken时AppSecret错误或者accessToken无效)
            {
                WX_ApiConfig config         = WXApiConfigServices.QueryWXApiConfig(companyId);
                var          newAccessToken = AccessTokenContainer.TryGetToken(config.AppId, config.AppSecret, true);
                ResError     newResult      = WxHttp.Post(WxUrl.UpdateUserGroup.ToFormat(newAccessToken), data);
                if (newResult.errcode == ResCode.请求成功)
                {
                    return(true);
                }
            }
            TxtLogServices.WriteTxtLogEx("WeiXinBase", "移动用户分组发生错误!错误代码:{0},说明:{1}", (int)result.errcode, result.errmsg);
            return(false);
        }
예제 #20
0
        public ActionResult Index(string preferentialMoney = "0", string payMoney = "0", bool showPreferentialMoney = true, string alreadyPayment = "0", bool showWaitPayMoney = true)
        {
            ViewBag.PreferentialMoney     = preferentialMoney;
            ViewBag.PayMoney              = payMoney;
            ViewBag.ShowWaitPayMoney      = showWaitPayMoney;
            ViewBag.ShowPreferentialMoney = showPreferentialMoney;
            ViewBag.AlreadyPayment        = alreadyPayment;
            bool SupportWeiXinPayment = false;
            bool SupportAliPayment    = false;

            if (!string.IsNullOrWhiteSpace(GetRequestCompanyId))
            {
                AliPayApiConfig config = AliPayApiConfigServices.QueryAliPayConfig(GetRequestCompanyId);
                if (config != null)
                {
                    SupportAliPayment = true;
                }
                WX_ApiConfig wxConfig = WXApiConfigServices.QueryWXApiConfig(GetRequestCompanyId);
                if (wxConfig != null)
                {
                    SupportWeiXinPayment = true;
                }
            }
            ViewBag.SupportWeiXinPayment = SupportWeiXinPayment;
            ViewBag.SupportAliPayment    = SupportAliPayment;
            return(PartialView());
        }
예제 #21
0
        /// <summary>
        /// 删除群发
        /// 请注意,只有已经发送成功的消息才能删除删除消息只是将消息的图文详情页失效,已经收到的用户,还是能在其本地看到消息卡片。
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="msgId">发送出去的消息ID</param>
        /// <returns></returns>
        public static bool SendAllDelete(string companyId, string accessToken, long msgId)
        {
            var data = new
            {
                msgid = msgId
            };

            ResError result = WxHttp.Post(WxUrl.SendAllDelete.ToFormat(accessToken), data);

            if (result.errcode == ResCode.请求成功)
            {
                return(true);
            }
            if (result.errcode == ResCode.获取accessToken时AppSecret错误或者accessToken无效)
            {
                WX_ApiConfig config         = WXApiConfigServices.QueryWXApiConfig(companyId);
                var          newAccessToken = AccessTokenContainer.TryGetToken(config.AppId, config.AppSecret, true);
                ResError     newResult      = WxHttp.Post(WxUrl.SendAllDelete.ToFormat(newAccessToken), data);
                if (newResult.errcode == ResCode.请求成功)
                {
                    return(true);
                }
            }
            TxtLogServices.WriteTxtLogEx("WeiXinBase", "删除群发发生错误!错误代码:{0},说明:{1}", (int)result.errcode, result.errmsg);
            return(false);
        }
예제 #22
0
 public JsonResult PublishMenu(string companyId)
 {
     try
     {
         WX_ApiConfig config = WXApiConfigServices.QueryWXApiConfig(companyId);
         if (config == null || string.IsNullOrWhiteSpace(config.AppId) || string.IsNullOrWhiteSpace(config.AppSecret) ||
             string.IsNullOrWhiteSpace(config.SystemName))
         {
             throw new MyException("获取微信基础信息失败,请确认微信基础信息已配置");
         }
         var accessToken = AccessTokenContainer.TryGetToken(config.AppId, config.AppSecret, false);
         var buttonGroup = ToButtonGroup(WXMenuServices.GetMenus(companyId));
         TxtLogServices.WriteTxtLogEx("PublishMenu", JsonHelper.GetJsonString(buttonGroup));
         var result = WxApi.CreateMenu(companyId, accessToken, buttonGroup);
         if (!result)
         {
             throw new MyException("发布菜单失败");
         }
         return(Json(MyResult.Success()));
     }
     catch (MyException ex)
     {
         return(Json(MyResult.Error(ex.Message)));
     }
     catch (Exception ex)
     {
         ExceptionsServices.AddExceptions(ex, "发布菜单失败");
         return(Json(MyResult.Error("发布菜单失败")));
     }
 }
예제 #23
0
        /// <summary>
        /// 微信单独授权 type  0-支付  1-岗亭扫码进入
        /// </summary>
        /// <param name="id">ControllerName_actionName_ispayauthorize=0^orderId=123</param>
        /// <param name="code"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        public ActionResult Index(string id, string code, string state)
        {
            try
            {
                if (SourceClient != RequestSourceClient.WeiXin)
                {
                    return(RedirectToAction("Index", "ErrorPrompt", new { message = "请在微信中打开" }));
                }
                ClearQRCodeCookie();
                WX_ApiConfig config = null;
                Dictionary <string, string> dicParams = GetRequestParams(id);
                if (string.IsNullOrWhiteSpace(dicParams["COMPANYID"]))
                {
                    throw new MyException("获取单位信息失败");
                }
                config = WXApiConfigServices.QueryWXApiConfig(dicParams["COMPANYID"]);
                if (config == null)
                {
                    return(RedirectToAction("Index", "ErrorPrompt", new { message = "获取微信配置失败" }));
                }
                if (!config.Status)
                {
                    return(RedirectToAction("Index", "ErrorPrompt", new { message = "该公众号暂停使用,稍后再试!" }));
                }
                Session["CurrLoginWeiXinApiConfig"] = config;
                if (string.IsNullOrEmpty(state))
                {
                    string redirectUri = config.Domain.IndexOf("http://", StringComparison.Ordinal) < 0 ? string.Format("http://{0}", config.Domain) : config.Domain;
                    redirectUri = string.Format("{0}/WeiXinAuthorize/{1}", redirectUri, id);

                    TxtLogServices.WriteTxtLogEx("WeiXinAuthorize", "获取微信OpenId请求redirectUri:{0}", redirectUri);
                    string url = WxAdvApi.GetAuthorizeUrl(config.AppId, redirectUri, "1", OAuthScope.snsapi_base);
                    TxtLogServices.WriteTxtLogEx("WeiXinAuthorize", "获取微信OpenId请求url:{0}", url);
                    return(Redirect(url));
                }
                TxtLogServices.WriteTxtLogEx("WeiXinAuthorize", "state不为空进入,id:{0}, code:{1}, state:{2}", id, code, state);
                if (string.IsNullOrEmpty(code))
                {
                    return(RedirectToAction("Index", "ErrorPrompt", new { message = "微信获取授权失败,请重新进入或请联系管理员" }));
                }

                var accessToken = WxAdvApi.GetAccessToken(config.AppId, config.AppSecret, code);
                TxtLogServices.WriteTxtLogEx("WeiXinAuthorize", "调用微信的AccessToken接口:openid:{0}, access_token:{1}", accessToken.openid, accessToken.access_token);
                if (accessToken == null || string.IsNullOrWhiteSpace(accessToken.openid))
                {
                    throw new MyException("获取微信用户信息失败");
                }

                //添加登陆
                Response.Cookies.Add(new HttpCookie("SmartSystem_WeiXinOpenId", accessToken.openid));
                TxtLogServices.WriteTxtLogEx("WeiXinAuthorize", "获取OpenId成功:openid:{0},cookie openid:{1}", accessToken.openid, WeiXinOpenId);
                return(Redir(id, accessToken.openid));
            }
            catch (Exception ex) {
                ExceptionsServices.AddExceptionToDbAndTxt("WeiXinAuthorize", "WeiXinAuthorize方法处理异常", ex, LogFrom.WeiXin);
                return(RedirectToAction("Index", "ErrorPrompt", new { message = "微信获取授权失败,请重新进入或请联系管理员" }));
            }
        }
예제 #24
0
        //public string SendParkingOutNotify(string cmd, string plateNo, string cpid,
        //                                string pkname, string indate, string outdate, string durtime, string amount, string app)
        //{
        //    return SendParkingOutNotify(cmd,plateNo,cpid,pkname,indate,outdate,durtime,"",amount,app);
        //}

        //[HttpPost]
        public string SendParkingOutNotify(string cmd, string plateNo, string cpid,
                                           string pkname, string indate, string outdate, string durtime, string payType, string amount, string app)
        {
            if (cmd.IsEmpty())
            {
                return("-4");
            }

            WX_ApiConfig config = WXApiConfigServices.QueryWXApiConfig(cpid);

            if (config == null)
            {
                return("-1");
            }
            if (!config.Status)
            {
                return("-2");
            }

            WX_Info user = WXUserServices.GetWXInfoByPlateNo(plateNo);

            if (user == null)
            {
                return("-3");
            }

            if (cmd == "In")
            {
            }
            else if (cmd == "Out")
            {
                bool isApp = app == "1" ? true : false;

                if (amount.EndsWith("元"))
                {
                    amount = amount + "元";
                }

                if (payType.IsEmpty())
                {
                    //默认
                    payType = "APP支付";
                }

                bool isSuc = TemplateMessageServices.SendParkOut(config.CompanyID, plateNo, pkname, indate, outdate, durtime, payType, amount, user.OpenID, isApp);
                if (isSuc)
                {
                    return("1");
                }
                else
                {
                    return("0");
                }
            }

            return("");
        }
예제 #25
0
 public WeiXinConversation(string token, Stream inputStream) : base(inputStream)
 {
     config = WXApiConfigServices.QueryByToKen(token);
     if (config == null || string.IsNullOrWhiteSpace(config.AppId) || string.IsNullOrWhiteSpace(config.AppSecret) ||
         string.IsNullOrWhiteSpace(config.Domain) || string.IsNullOrWhiteSpace(config.Token))
     {
         CancelExcute = true;
     }
 }
예제 #26
0
        private static WX_ApiConfig GetWX_ApiConfig(string companyId)
        {
            WX_ApiConfig config = WXApiConfigServices.QueryWXApiConfig(companyId);

            if (config == null || string.IsNullOrWhiteSpace(config.AppId) || string.IsNullOrWhiteSpace(config.AppSecret))
            {
                throw new MyException("获取微信基本配置信息失败");
            }
            return(config);
        }
예제 #27
0
        private WX_ApiConfig GetApiConfig(string id)
        {
            TxtLogServices.WriteTxtLogEx("RedirectHandle", "获取微信配置信息,id:{0}", id);
            var separator = new[] { '|', '_' };
            var param     = new[] { '^' };//^参数分隔符
            var ids       = id.Split(separator, StringSplitOptions.RemoveEmptyEntries);

            var parameters = ids[2].Split(param, StringSplitOptions.RemoveEmptyEntries);

            if (parameters.Length == 0)
            {
                throw new MyException("获取单位失败");
            }
            foreach (var item in parameters)
            {
                var parame = item.Split(new[] { '=' });
                if (parame.Length == 2)
                {
                    if (parame[0].ToUpper() == "CID")
                    {
                        WX_ApiConfig config = WXApiConfigServices.QueryWXApiConfig(parame[1]);
                        if (config == null)
                        {
                            throw new MyException("获取微信配置失败");
                        }
                        if (config.CompanyID != parame[1])
                        {
                            throw new MyException("该公众号暂停使用");
                        }
                        return(config);
                    }
                    if (parame[0] == "PARKINGID" || parame[0] == "PID")
                    {
                        BaseCompany company = CompanyServices.QueryByParkingId(parame[1]);
                        if (company == null)
                        {
                            throw new MyException("获取单位信息失败");
                        }

                        WX_ApiConfig config = WXApiConfigServices.QueryWXApiConfig(company.CPID);
                        if (config == null)
                        {
                            throw new MyException("获取微信配置失败");
                        }
                        if (config.CompanyID != parame[1])
                        {
                            throw new MyException("该公众号暂停使用");
                        }
                        return(config);
                    }
                }
            }
            throw new MyException("获取微信配置失败,id:" + id);
        }
예제 #28
0
        public static string GenerateQRCode(string companyId, string content, int size, string qrCodeName, string folderName = "QRCode")
        {
            QRCodeEncoder.ENCODE_MODE      QRCodeEncodeMode   = QRCodeEncoder.ENCODE_MODE.BYTE;
            QRCodeEncoder.ERROR_CORRECTION QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
            int          border = GetQRCodeBorder(size);
            string       imageUrl = string.Empty;
            int          QRCodeVersion = 0; int QRCodeScale = 5;
            WX_ApiConfig config = WXApiConfigServices.QueryWXApiConfig(companyId);

            if (config != null && !string.IsNullOrWhiteSpace(config.SystemLogo))
            {
                imageUrl = config.SystemLogo;
            }
            TxtLogServices.WriteTxtLogEx("GenerateQRCode", imageUrl);
            var bitmap = GenerateQRCode(content, QRCodeEncodeMode, QRCodeErrorCorrect, QRCodeVersion, QRCodeScale, size, border);

            if (bitmap == null)
            {
                return(string.Empty);
            }
            string filePath = string.Format("/Uploads/{2}/{0}.{1}", qrCodeName, "jpg", folderName);

            TxtLogServices.WriteTxtLogEx("GenerateQRCode", "filePath:" + filePath);
            string savePath = GetFileSavePath(string.Format("/Uploads/{0}", folderName), string.Format("{0}.{1}", qrCodeName, "jpg"));

            TxtLogServices.WriteTxtLogEx("GenerateQRCode", "savePath:" + filePath);
            string pathImage = string.Empty;

            if (!string.IsNullOrWhiteSpace(imageUrl))
            {
                pathImage = System.Web.HttpContext.Current.Server.MapPath("~" + imageUrl);
            }
            if (!string.IsNullOrWhiteSpace(pathImage) && File.Exists(pathImage))
            {
                var   logoSize = GetLogoImageSize(size);
                Image bitmap1  = CombinImage(bitmap, pathImage, logoSize);
                if (File.Exists(savePath))
                {
                    File.Delete(savePath);
                }
                bitmap1.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                bitmap1.Dispose();
            }
            else
            {
                if (File.Exists(savePath))
                {
                    File.Delete(savePath);
                }
                bitmap.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                bitmap.Dispose();
            }
            return(filePath);
        }
예제 #29
0
        public static UnifiedPayModel CreateUnifiedModel(string companyId)
        {
            UnifiedPayModel wxPayModel = new UnifiedPayModel();
            WX_ApiConfig    config     = WXApiConfigServices.QueryWXApiConfig(companyId);

            wxPayModel.SetAppId(config.AppId);
            wxPayModel.SetKey(config.PartnerKey);
            wxPayModel.SetPartnerId(config.PartnerId);
            wxPayModel.SetServerIP(config.ServerIP);
            return(wxPayModel);
        }
예제 #30
0
        public static bool UpdatePayConfig(WX_ApiConfig model)
        {
            IWXApiConfig factory = WXApiConfigFactory.GetFactory();
            bool         result  = factory.UpdatePayConfig(model);

            if (result)
            {
                RefreshCache();
                OperateLogServices.AddOperateLog <WX_ApiConfig>(model, OperateType.Update);
            }
            return(result);
        }