/// <summary> /// 跟微信同 /// </summary> /// <returns></returns> public ActionResult WeChatCode() { string code = QueryString.SafeQ("wechatcode"); VWMemberEntity mem = new VWMemberEntity(); mem = MemberBLL.Instance.GetVWMember(memid); if (!string.IsNullOrEmpty(code) && string.IsNullOrEmpty(mem.WeChat)) { MemWeChatMsgEntity shortmsg = WeiXinJsSdk.Instance.GetWeChatShortInfo(code); if (!string.IsNullOrEmpty(shortmsg.OpenId) && !string.IsNullOrEmpty(shortmsg.UnionId)) { MemWeChatMsgEntity entity = new MemWeChatMsgEntity(); entity.AppId = WeiXinConfig.GetAppId(); entity.Status = (int)WeChatStatus.ShortInfo; entity.UnionId = shortmsg.UnionId; entity.OpenId = shortmsg.OpenId; MemWeChatMsgBLL.Instance.WeChatLogin(entity); MemberBLL.Instance.BindMemWeChat(memid, shortmsg.UnionId, mem.TimeStampTab); mem = MemberBLL.Instance.GetVWMember(memid); } } ViewBag.VWMember = mem; return(View()); }
/** * * 测速上报接口实现 * @param WxPayData inputObj 提交给测速上报接口的参数 * @param int timeOut 测速上报接口超时时间 * @throws Exception * @return 成功时返回测速上报接口返回的结果,其他抛异常 */ //public static WxPayData Report(WxPayData inputObj, int timeOut = 1) //{ // string url = "https://api.mch.weixin.qq.com/payitil/report"; // //检测必填参数 // if(!inputObj.IsSet("interface_url")) // { // throw new Exception("接口URL,缺少必填参数interface_url!"); // } // if(!inputObj.IsSet("return_code")) // { // throw new Exception("返回状态码,缺少必填参数return_code!"); // } // if(!inputObj.IsSet("result_code")) // { // throw new Exception("业务结果,缺少必填参数result_code!"); // } // if(!inputObj.IsSet("user_ip")) // { // throw new Exception("访问接口IP,缺少必填参数user_ip!"); // } // if(!inputObj.IsSet("execute_time_")) // { // throw new Exception("接口耗时,缺少必填参数execute_time_!"); // } // inputObj.SetValue("appid",WxPayConfig.APPID);//公众账号ID // inputObj.SetValue("mch_id",WxPayConfig.MCHID);//商户号 // inputObj.SetValue("user_ip",WxPayConfig.IP);//终端ip // inputObj.SetValue("time",DateTime.Now.ToString("yyyyMMddHHmmss"));//商户上报时间 // inputObj.SetValue("nonce_str",GenerateNonceStr());//随机字符串 // inputObj.SetValue("sign",inputObj.MakeSign());//签名 // string xml = inputObj.ToXml(); // Log.Info("WxPayApi", "Report request : " + xml); // string response = HttpService.Post(xml, url, false, timeOut); // Log.Info("WxPayApi", "Report response : " + response); // WxPayData result = new WxPayData(); // result.FromXml(response); // return result; //} /** * 根据当前系统时间加随机序列来生成订单号 * @return 订单号 */ public static string GenerateOutTradeNo() { WeiXinConfig wxconfig = BMAConfig.WeiXinConfig; var ran = new Random(); return(string.Format("{0}{1}{2}", wxconfig.Mch_id, DateTime.Now.ToString("yyyyMMddHHmmss"), ran.Next(999))); }
/// <summary> /// 获取配置文件 /// </summary> /// <returns></returns> private static WeiXinConfig GetWeiXinConfig() { XmlDocument doc = new XmlDocument(); var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Configuration/WeiXinPush.config"); if (!File.Exists(path)) { throw new BusinessException("当前项目目录下, /Configuration/WeiXinPush.config 文件不存在!"); } doc.Load(path); XmlNode node = doc.SelectSingleNode("weiXinPush"); WeiXinConfig config = new WeiXinConfig(); config.AppID = GetXmlNodeValue(node, "appId"); config.AppSecret = GetXmlNodeValue(node, "appSecret"); config.Encoding = GetXmlNodeValue(node, "encoding"); config.GetUserInfoUrl = GetXmlNodeValue(node, "getUserInfoUrl"); config.CommonAccessTokenUrl = GetXmlNodeValue(node, "commonAccessTokenUrl"); config.TemplateMessageUrl = GetXmlNodeValue(node, "templateMessageUrl"); config.LoginUrl = GetXmlNodeValue(node, "loginUrl"); config.LoginBackUrl = GetXmlNodeValue(node, "loginBackUrl"); config.WebAccessTokenUrl = GetXmlNodeValue(node, "webAccessTokenUrl"); config.JsapiTicketUrl = GetXmlNodeValue(node, "jsapiTicketUrl"); config.JsApis = GetXmlNodeValue(node, "jsApis").Split(',').ToList(); return(config); }
public HomeController(ILogger <HomeController> logger, IConfiguration configuration, IWeatherService weatherService, IWeiXinService weiXinService) { _logger = logger; weiXinConfig = configuration.GetSection(nameof(WeiXinConfig))?.Get <WeiXinConfig>(); _weatherService = weatherService; _weiXinService = weiXinService; }
/// <summary> /// 公共API => 支付结果通用通知 /// http://pay.weixin.qq.com/wiki/doc/api/index.php?chapter=9_7 /// 微信支付回调,不需要证书 /// /// 应用场景 /// 支付完成后,微信会把相关支付结果和用户信息发送给商户,商户需要接收处理,并返回应答。 /// 对后台通知交互时,如果微信收到商户的应答不是成功或超时,微信认为通知失败,微信会通过一定的策略(如30分钟共8次)定期重新发起通知,尽可能提高通知的成功率,但微信不保证通知最终能成功。 /// 由于存在重新发送后台通知的情况,因此同样的通知可能会多次发送给商户系统。商户系统必须能够正确处理重复的通知。 /// 推荐的做法是,当收到通知进行处理时,首先检查对应业务数据的状态,判断该通知是否已经处理过,如果没有处理过再进行处理,如果处理过直接返回结果成功。在对业务数据进行状态检查和处理之前,要采用数据锁进行并发控制,以避免函数重入造成的数据混乱。 /// 技术人员可登进微信商户后台扫描加入接口报警群。 /// </summary> /// <returns></returns> // [HttpPost] public string Notify() { WeiXinConfig wxconfig = BMAConfig.WeiXinConfig; var form = Request.QueryString; var sPara = GetRequestPost(form); if (sPara.Count <= 0) { //throw new ArgumentNullException(); //Content("进来了"); return("进来了"); } BMALog.Instance.Write("111:" + form.ToString()); if (sPara["return_code"] == "SUCCESS" && sPara["return_code"] == "SUCCESS") { var sign_type = sPara["sign_type"]; var sign = sPara["sign"]; var signValue = WxPayAPI.Sign(sPara, wxconfig.PartnerKey); bool isVerify = sign == signValue; if (isVerify) { var out_trade_no = sPara["out_trade_no"]; //TODO 商户处理订单逻辑: 1.注意交易单不要重复处理;2.注意判断返回金额 var cash_fee = BrnMall.Core.Common.Utils.StrToInt(sPara["cash_fee"]); //取得type int strtype = 1; string[] arrtype = out_trade_no.Split('_'); try { strtype = BrnMall.Core.Common.Utils.StrToInt(arrtype[1]); } catch { BMALog.Instance.Write("获取Type出错,订单号:" + out_trade_no + " 订单金额:" + cash_fee); } //TODO:postData中携带该次支付的用户相关信息,这将便于商家拿到openid,以便后续提供更好的售后服务,譬如:微信公众好通知用户付款成功。如果不提供服务则可以删除此代码 var openid = sPara["openid"]; try { BrnMall.Core.BLL.SpHelp.SP_CheckPayOrder(out_trade_no, openid, cash_fee, strtype, 1); } catch (Exception ex) { BMALog.Instance.Write(ex.ToString()); } //return Content("success"); return("success"); } //return Content("fail"); return("fail"); } else { // return Content("fail"); return("fail"); } }
/// <summary> /// 通知供应商查看询价订单网址 微信入口自动封装后的网址 /// </summary> /// <param name="ordercode"></param> /// <returns></returns> public static string InquiryOrderSendWeChat(string ordercode) { string redirecturl = InquiryOrderUrl(ordercode); //int navid = WeChatNavigationBLL.Instance.GetIdByUrl(redirecturl); //string resulturl = string.Format(WeiXinConfig.URL_FORMAT_KHRedirect, WeiXinConfig.GetAppId(), System.Web.HttpContext.Current.Server.UrlEncode(redirecturl), "0"); string resulturl = string.Format(WeiXinConfig.URL_WeiXin_Redirect, WeiXinConfig.GetAppId(), System.Web.HttpContext.Current.Server.UrlEncode(redirecturl), "0"); return(resulturl); }
public JsonResult Index() { var form = Request.Form; var sPara = GetRequestPost(form); WeiXinConfig wxconfig = BMAConfig.WeiXinConfig; if (sPara.Count <= 0) { throw new ArgumentNullException(); } //LogWriter.Default.WriteInfo(form.ToString());//记录请求关键信息到日志中去 Logs.Write(form.ToString()); var out_trade_no = BrnMall.Core.Common.Utils.GenerateOutTradeNo(); //Guid.NewGuid().ToString(); var domain = wxconfig.Domain; var body = sPara["body"]; var detail = sPara["detail"]; var attach = sPara["attach"]; var fee_type = "CNY"; var total_fee = int.Parse(sPara["total_fee"]) * 100; var trade_type = sPara["trade_type"]; var spbill_create_ip = (trade_type == "APP" || trade_type == "NATIVE") ? Request.UserHostName : wxconfig.Spbill_create_ip; var time_start = DateTime.Now.ToString("yyyyMMddHHmmss"); var time_expire = DateTime.Now.AddHours(1).ToString("yyyyMMddHHmmss"); //默认1个小时订单过期,开发者可自定义其他超时机制,原则上微信订单超时时间不超过2小时 var goods_tag = sPara["goods_tag"]; var notify_url = string.Format("{0}/mobile/WXPay/Notify", domain); //与下面的Notify对应,开发者可自定义其他url地址 var product_id = sPara["product_id"]; var openid = sPara["openid"]; var partnerKey = wxconfig.PartnerKey; var content = WxPayAPI.UnifiedOrder( wxconfig.AppID, wxconfig.Mch_id, wxconfig.Device_info, Util.CreateNonce_str(), body, detail, attach, out_trade_no, fee_type, total_fee, spbill_create_ip, time_start, time_expire, goods_tag, notify_url, trade_type, product_id, openid, partnerKey); if (content.return_code.Value == "SUCCESS" && content.result_code.Value == "SUCCESS") { var result = new { prepay_id = content.prepay_id.Value, trade_type = content.trade_type.Value, sign = content.sign.Value, nonce_str = content.nonce_str.Value, return_code = content.result_code.Value, return_msg = "", }; return(Json(result)); } else { var result = new { return_code = content.return_code.Value, return_msg = content.return_msg.Value, }; return(Json(result)); } }
public ActionResult SaveConfig(WeiXinConfig configViewModel) { var result = new DataJsonResult(); if (!_configService.Save(configViewModel)) { result.ErrorMessage = "异常错误,配置文件保存失败"; } return(Json(result)); }
public RequestResultDto UpdateToken(WeiXinConfig model) { try { _config.UpdateToken(model); _result.Ret = 0; _result.Msg = "更新成功"; } catch (Exception e) { _result.Msg = e.Message; } return(_result); }
public RequestResultDto AddConfig(WeiXinConfig model) { try { _config.AddConfig(model); _result.Ret = 0; _result.Msg = "添加成功"; } catch (Exception e) { _result.Msg = e.Message; } return(_result); }
public int WeChatUrlAdd() { string _redirecturl = StringUtils.SafeCodeSmall(FormString.SafeQNo("_url", 200)); int _urltype = FormString.IntSafeQ("_urltype"); string _remark = FormString.SafeQ("_remark", 200); WeChatNavigationEntity _entity = WeChatNavigationBLL.Instance.GetNavigationByUrl(_redirecturl); if (_entity == null || _entity.Id == 0) { _entity.RedirectUrl = _redirecturl; _entity.Id = WeChatNavigationBLL.Instance.AddWeChatNavigation(_entity); } _entity.WeChatUrlType = _urltype; _entity.Remark = _remark; //_entity.WeChatUrl = string.Format(WeiXinConfig.URL_FORMAT_KHRedirect, WeiXinConfig.GetAppId(), System.Web.HttpContext.Current.Server.UrlEncode(SuperMarket.Core.ConfigCore.Instance.ConfigCommonEntity.WeChatWebUrl), _entity.Id); _entity.WeChatUrl = string.Format(WeiXinConfig.URL_WeiXin_Redirect, WeiXinConfig.GetAppId(), System.Web.HttpContext.Current.Server.UrlEncode(_redirecturl), _entity.Id); int _result = WeChatNavigationBLL.Instance.UpdateWeChatNavigation(_entity); return(_result); }
/// <summary> /// 公共API => 支付结果通用通知 /// http://pay.weixin.qq.com/wiki/doc/api/index.php?chapter=9_7 /// 微信支付回调,不需要证书 /// /// 应用场景 /// 支付完成后,微信会把相关支付结果和用户信息发送给商户,商户需要接收处理,并返回应答。 /// 对后台通知交互时,如果微信收到商户的应答不是成功或超时,微信认为通知失败,微信会通过一定的策略(如30分钟共8次)定期重新发起通知,尽可能提高通知的成功率,但微信不保证通知最终能成功。 /// 由于存在重新发送后台通知的情况,因此同样的通知可能会多次发送给商户系统。商户系统必须能够正确处理重复的通知。 /// 推荐的做法是,当收到通知进行处理时,首先检查对应业务数据的状态,判断该通知是否已经处理过,如果没有处理过再进行处理,如果处理过直接返回结果成功。在对业务数据进行状态检查和处理之前,要采用数据锁进行并发控制,以避免函数重入造成的数据混乱。 /// 技术人员可登进微信商户后台扫描加入接口报警群。 /// </summary> /// <returns></returns> // [HttpPost] //public string Notify() //{ // WeiXinConfig wxconfig = BMAConfig.WeiXinConfig; // //var form = Request.QueryString; // //var sPara = GetRequestPost(form); // var requestContent = ""; // using (StreamReader sr = new StreamReader(Request.InputStream)) // { // requestContent = sr.ReadToEnd(); // } // BMALog.Instance.Write(requestContent);//记录请求关键信息到日志中去 // //bool isVerify = false; // var sPara = GetRequestPostByXml(requestContent); // BMALog.Instance.Write("有进来过"); // if (sPara.Count <= 0) // { // //throw new ArgumentNullException(); // //Content("进来了"); // return "进来了"; // } // BMALog.Instance.Write("111:" + requestContent); // if (sPara["return_code"] == "SUCCESS" && sPara["return_code"] == "SUCCESS") // { // var sign_type = sPara["sign_type"]; // var sign = sPara["sign"]; // var signValue = WxPayAPI.Sign(sPara, wxconfig.PartnerKey); // bool isVerify = sign == signValue; // BMALog.Instance.Write("isVerify:" + isVerify + " 返回签名:" + sign + " 本地签名:" + signValue); // //if (isVerify) // //{ // var out_trade_no = sPara["out_trade_no"]; // //TODO 商户处理订单逻辑: 1.注意交易单不要重复处理;2.注意判断返回金额 // var cash_fee = BrnMall.Core.Common.Utils.StrToInt(sPara["cash_fee"]); // //取得type // int strtype = 1; // string[] arrtype = out_trade_no.Split('_'); // try // { // strtype = BrnMall.Core.Common.Utils.StrToInt(arrtype[1]); // } // catch // { // BMALog.Instance.Write("获取Type出错,订单号:" + out_trade_no + " 订单金额:" + cash_fee); // } // //TODO:postData中携带该次支付的用户相关信息,这将便于商家拿到openid,以便后续提供更好的售后服务,譬如:微信公众好通知用户付款成功。如果不提供服务则可以删除此代码 // var openid = sPara["openid"]; // try // { // BrnMall.Core.BLL.SpHelp.SP_CheckPayOrder(out_trade_no, openid, cash_fee, strtype, 1); // } // catch (Exception ex) // { // BMALog.Instance.Write(ex.ToString()); // } // //return Content("success"); // return "success"; // // } // //return Content("fail"); // return "fail"; // } // else // { // // return Content("fail"); // return "fail"; // } //} /// <summary> /// 微信退款完成后的回调 /// </summary> /// <returns></returns> public ActionResult Refund() { WeiXinConfig wxconfig = BMAConfig.WeiXinConfig; var requestContent = ""; using (StreamReader sr = new StreamReader(Request.InputStream)) { requestContent = sr.ReadToEnd(); } Logs.Write(requestContent); // LogWriter.Default.WriteInfo(requestContent);//记录请求关键信息到日志中去 bool isVerify = false; var sPara = GetRequestPostByXml(requestContent); if (sPara.Count <= 0) { throw new ArgumentNullException(); } var sign = sPara["sign"]; var retcode = sPara["retcode"]; if (retcode != "0") { isVerify = false; } else { var signValue = WxPayAPI.Sign(sPara, wxconfig.PartnerKey); isVerify = sign == signValue; } if (!isVerify) { return(Content("fail")); } //TODO:商户处理订单逻辑 return(Content("success")); }
/** * * 查询订单 * @param WxPayData inputObj 提交给查询订单API的参数 * @param int timeOut 超时时间 * @throws Exception * @return 成功时返回订单查询结果,其他抛异常 */ public static WxPayData OrderQuery(WxPayData inputObj, int timeOut = 6) { WeiXinConfig wxconfig = BMAConfig.WeiXinConfig; string url = "https://api.mch.weixin.qq.com/pay/orderquery"; //检测必填参数 if (!inputObj.IsSet("out_trade_no") && !inputObj.IsSet("transaction_id")) { throw new Exception("订单查询接口中,out_trade_no、transaction_id至少填一个!"); } inputObj.SetValue("appid", wxconfig.AppID); //公众账号ID inputObj.SetValue("mch_id", wxconfig.Mch_id); //商户号 inputObj.SetValue("nonce_str", WxPayApi.GenerateNonceStr()); //随机字符串 inputObj.SetValue("sign", inputObj.MakeSign()); //签名 string xml = inputObj.ToXml(); var start = DateTime.Now; BMALog.Instance.Write("OrderQuery request : " + xml); string response = HttpService.Post(xml, url, false, timeOut);//调用HTTP通信接口提交数据 BMALog.Instance.Write("OrderQuery response : " + response); var end = DateTime.Now; int timeCost = (int)((end - start).TotalMilliseconds);//获得接口耗时 //将xml格式的数据转化为对象以返回 WxPayData result = new WxPayData(); result.FromXml(response); //ReportCostTime(url, timeCost, result);//测速上报 return(result); }
public static string Post(string xml, string url, bool isUseCert, int timeout) { WeiXinConfig wxconfig = BMAConfig.WeiXinConfig; System.GC.Collect(); //垃圾回收,回收没有正常关闭的http连接 string result = ""; //返回结果 HttpWebRequest request = null; HttpWebResponse response = null; Stream reqStream = null; try { //设置最大连接数 ServicePointManager.DefaultConnectionLimit = 200; //设置https验证方式 if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); } /*************************************************************** * 下面设置HttpWebRequest的相关属性 * ************************************************************/ request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.Timeout = timeout * 1000; //设置代理服务器 //WebProxy proxy = new WebProxy(); //定义一个网关对象 //proxy.Address = new Uri(WxPayConfig.PROXY_URL); //网关服务器端口:端口 //request.Proxy = proxy; //设置POST的数据类型和长度 request.ContentType = "text/xml"; byte[] data = System.Text.Encoding.UTF8.GetBytes(xml); request.ContentLength = data.Length; //是否使用证书 if (isUseCert) { string path = HttpContext.Current.Request.PhysicalApplicationPath; X509Certificate2 cert = new X509Certificate2(path + wxconfig.SSLCERT_PATH, wxconfig.Sslcert_Password); request.ClientCertificates.Add(cert); BMALog.Instance.Write("PostXml used cert"); } //往服务器写入数据 reqStream = request.GetRequestStream(); reqStream.Write(data, 0, data.Length); reqStream.Close(); //获取服务端返回 response = (HttpWebResponse)request.GetResponse(); //获取服务端返回数据 StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8); result = sr.ReadToEnd().Trim(); sr.Close(); } catch (System.Threading.ThreadAbortException e) { BMALog.Instance.Write("HttpService:Thread - caught ThreadAbortException - resetting."); BMALog.Instance.Write(e.Message); System.Threading.Thread.ResetAbort(); } catch (WebException e) { BMALog.Instance.Write(e.ToString()); if (e.Status == WebExceptionStatus.ProtocolError) { BMALog.Instance.Write("HttpService:StatusCode : " + ((HttpWebResponse)e.Response).StatusCode); BMALog.Instance.Write("HttpService:StatusDescription : " + ((HttpWebResponse)e.Response).StatusDescription); } throw new Exception(e.ToString()); } catch (Exception e) { BMALog.Instance.Write("HttpService" + e.ToString()); throw new Exception(e.ToString()); } finally { //关闭连接和流 if (response != null) { response.Close(); } if (request != null) { request.Abort(); } } return(result); }
/** * * 撤销订单API接口 * @param WxPayData inputObj 提交给撤销订单API接口的参数,out_trade_no和transaction_id必填一个 * @param int timeOut 接口超时时间 * @throws Exception * @return 成功时返回API调用结果,其他抛异常 */ //public static WxPayData Reverse(WxPayData inputObj, 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 Exception("撤销订单API接口中,参数out_trade_no和transaction_id必须填写一个!"); // } // inputObj.SetValue("appid", WxPayConfig.APPID);//公众账号ID // inputObj.SetValue("mch_id", WxPayConfig.MCHID);//商户号 // inputObj.SetValue("nonce_str", GenerateNonceStr());//随机字符串 // inputObj.SetValue("sign", inputObj.MakeSign());//签名 // string xml = inputObj.ToXml(); // var start = DateTime.Now;//请求开始时间 // Log.Debug("WxPayApi", "Reverse request : " + xml); // string response = HttpService.Post(xml, url, true, timeOut); // Log.Debug("WxPayApi", "Reverse response : " + response); // var end = DateTime.Now; // int timeCost = (int)((end - start).TotalMilliseconds); // WxPayData result = new WxPayData(); // result.FromXml(response); // ReportCostTime(url, timeCost, result);//测速上报 // return result; //} /** * * 申请退款 * @param WxPayData inputObj 提交给申请退款API的参数 * @param int timeOut 超时时间 * @throws Exception * @return 成功时返回接口调用结果,其他抛异常 */ //public static WxPayData Refund(WxPayData inputObj, int timeOut = 6) //{ // string url = "https://api.mch.weixin.qq.com/secapi/pay/refund"; // //检测必填参数 // if (!inputObj.IsSet("out_trade_no") && !inputObj.IsSet("transaction_id")) // { // throw new Exception("退款申请接口中,out_trade_no、transaction_id至少填一个!"); // } // else if (!inputObj.IsSet("out_refund_no")) // { // throw new Exception("退款申请接口中,缺少必填参数out_refund_no!"); // } // else if (!inputObj.IsSet("total_fee")) // { // throw new Exception("退款申请接口中,缺少必填参数total_fee!"); // } // else if (!inputObj.IsSet("refund_fee")) // { // throw new Exception("退款申请接口中,缺少必填参数refund_fee!"); // } // else if (!inputObj.IsSet("op_user_id")) // { // throw new Exception("退款申请接口中,缺少必填参数op_user_id!"); // } // inputObj.SetValue("appid", WxPayConfig.APPID);//公众账号ID // inputObj.SetValue("mch_id", WxPayConfig.MCHID);//商户号 // inputObj.SetValue("nonce_str", Guid.NewGuid().ToString().Replace("-", ""));//随机字符串 // inputObj.SetValue("sign", inputObj.MakeSign());//签名 // string xml = inputObj.ToXml(); // var start = DateTime.Now; // Log.Debug("WxPayApi", "Refund request : " + xml); // string response = HttpService.Post(xml, url, true, timeOut);//调用HTTP通信接口提交数据到API // Log.Debug("WxPayApi", "Refund response : " + response); // var end = DateTime.Now; // int timeCost = (int)((end - start).TotalMilliseconds);//获得接口耗时 // //将xml格式的结果转换为对象以返回 // WxPayData result = new WxPayData(); // result.FromXml(response); // ReportCostTime(url, timeCost, result);//测速上报 // return result; //} /** * * 查询退款 * 提交退款申请后,通过该接口查询退款状态。退款有一定延时, * 用零钱支付的退款20分钟内到账,银行卡支付的退款3个工作日后重新查询退款状态。 * out_refund_no、out_trade_no、transaction_id、refund_id四个参数必填一个 * @param WxPayData inputObj 提交给查询退款API的参数 * @param int timeOut 接口超时时间 * @throws Exception * @return 成功时返回,其他抛异常 */ //public static WxPayData RefundQuery(WxPayData inputObj, int timeOut = 6) //{ // string url = "https://api.mch.weixin.qq.com/pay/refundquery"; // //检测必填参数 // if(!inputObj.IsSet("out_refund_no") && !inputObj.IsSet("out_trade_no") && // !inputObj.IsSet("transaction_id") && !inputObj.IsSet("refund_id")) // { // throw new Exception("退款查询接口中,out_refund_no、out_trade_no、transaction_id、refund_id四个参数必填一个!"); // } // inputObj.SetValue("appid",WxPayConfig.APPID);//公众账号ID // inputObj.SetValue("mch_id",WxPayConfig.MCHID);//商户号 // inputObj.SetValue("nonce_str",GenerateNonceStr());//随机字符串 // inputObj.SetValue("sign",inputObj.MakeSign());//签名 // string xml = inputObj.ToXml(); // var start = DateTime.Now;//请求开始时间 // Log.Debug("WxPayApi", "RefundQuery request : " + xml); // string response = HttpService.Post(xml, url, false, timeOut);//调用HTTP通信接口以提交数据到API // Log.Debug("WxPayApi", "RefundQuery response : " + response); // var end = DateTime.Now; // int timeCost = (int)((end-start).TotalMilliseconds);//获得接口耗时 // //将xml格式的结果转换为对象以返回 // WxPayData result = new WxPayData(); // result.FromXml(response); // ReportCostTime(url, timeCost, result);//测速上报 // return result; //} /** * 下载对账单 * @param WxPayData inputObj 提交给下载对账单API的参数 * @param int timeOut 接口超时时间 * @throws Exception * @return 成功时返回,其他抛异常 */ //public static WxPayData DownloadBill(WxPayData inputObj, int timeOut = 6) //{ // string url = "https://api.mch.weixin.qq.com/pay/downloadbill"; // //检测必填参数 // if (!inputObj.IsSet("bill_date")) // { // throw new Exception("对账单接口中,缺少必填参数bill_date!"); // } // inputObj.SetValue("appid", WxPayConfig.APPID);//公众账号ID // inputObj.SetValue("mch_id", WxPayConfig.MCHID);//商户号 // inputObj.SetValue("nonce_str", GenerateNonceStr());//随机字符串 // inputObj.SetValue("sign", inputObj.MakeSign());//签名 // string xml = inputObj.ToXml(); // Log.Debug("WxPayApi", "DownloadBill request : " + xml); // string response = HttpService.Post(xml, url, false, timeOut);//调用HTTP通信接口以提交数据到API // Log.Debug("WxPayApi", "DownloadBill result : " + response); // WxPayData result = new WxPayData(); // //若接口调用失败会返回xml格式的结果 // if (response.Substring(0, 5) == "<xml>") // { // result.FromXml(response); // } // //接口调用成功则返回非xml格式的数据 // else // result.SetValue("result", response); // return result; //} /** * * 转换短链接 * 该接口主要用于扫码原生支付模式一中的二维码链接转成短链接(weixin://wxpay/s/XXXXXX), * 减小二维码数据量,提升扫描速度和精确度。 * @param WxPayData inputObj 提交给转换短连接API的参数 * @param int timeOut 接口超时时间 * @throws Exception * @return 成功时返回,其他抛异常 */ // public static WxPayData ShortUrl(WxPayData inputObj, int timeOut = 6) // { // string url = "https://api.mch.weixin.qq.com/tools/shorturl"; // //检测必填参数 // if(!inputObj.IsSet("long_url")) // { // throw new Exception("需要转换的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());//签名 // string xml = inputObj.ToXml(); // var start = DateTime.Now;//请求开始时间 // Log.Debug("WxPayApi", "ShortUrl request : " + xml); // string response = HttpService.Post(xml, url, false, timeOut); // Log.Debug("WxPayApi", "ShortUrl response : " + response); // var end = DateTime.Now; // int timeCost = (int)((end - start).TotalMilliseconds); // WxPayData result = new WxPayData(); // result.FromXml(response); //ReportCostTime(url, timeCost, result);//测速上报 // return result; // } /** * * 统一下单 * @param WxPaydata inputObj 提交给统一下单API的参数 * @param int timeOut 超时时间 * @throws Exception * @return 成功时返回,其他抛异常 */ public static WxPayData UnifiedOrder(WxPayData inputObj, int timeOut = 6) { WeiXinConfig wxconfig = BMAConfig.WeiXinConfig; string url = "https://api.mch.weixin.qq.com/pay/unifiedorder"; //检测必填参数 if (!inputObj.IsSet("out_trade_no")) { throw new Exception("缺少统一支付接口必填参数out_trade_no!"); } else if (!inputObj.IsSet("body")) { throw new Exception("缺少统一支付接口必填参数body!"); } else if (!inputObj.IsSet("total_fee")) { throw new Exception("缺少统一支付接口必填参数total_fee!"); } else if (!inputObj.IsSet("trade_type")) { throw new Exception("缺少统一支付接口必填参数trade_type!"); } //关联参数 if (inputObj.GetValue("trade_type").ToString() == "JSAPI" && !inputObj.IsSet("openid")) { throw new Exception("统一支付接口中,缺少必填参数openid!trade_type为JSAPI时,openid为必填参数!"); } if (inputObj.GetValue("trade_type").ToString() == "NATIVE" && !inputObj.IsSet("product_id")) { throw new Exception("统一支付接口中,缺少必填参数product_id!trade_type为JSAPI时,product_id为必填参数!"); } //异步通知url未设置,则使用配置文件中的url if (!inputObj.IsSet("notify_url")) { inputObj.SetValue("notify_url", wxconfig.NOTIFY_URL);//异步通知url } inputObj.SetValue("appid", wxconfig.AppID); //公众账号ID inputObj.SetValue("mch_id", wxconfig.Mch_id); //商户号 //inputObj.SetValue("spbill_create_ip", WxPayConfig.IP);//终端ip inputObj.SetValue("spbill_create_ip", HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]); //终端ip inputObj.SetValue("nonce_str", GenerateNonceStr()); //随机字符串 //签名 inputObj.SetValue("sign", inputObj.MakeSign()); string xml = inputObj.ToXml(); var start = DateTime.Now; BMALog.Instance.Write("WxPayApi:" + "UnfiedOrder request : " + xml); string response = HttpService.Post(xml, url, false, timeOut); BMALog.Instance.Write("WxPayApi:" + "UnfiedOrder response : " + response); var end = DateTime.Now; int timeCost = (int)((end - start).TotalMilliseconds); WxPayData result = new WxPayData(); result.FromXml(response); ReportCostTime(url, timeCost, result);//测速上报 return(result); }
public async Task <bool> UpdateWeiXinConfigAsync(WeiXinConfig weixinconfig) { var entity = await _weixinconfigRepository.UpdateAsync(weixinconfig); return(entity != null); }
public JsonResult WxPay() //public HttpResponseMessage WxPay() { if (WebHelper.IsGet()) { var result = new { return_code = "erro", return_msg = "请求错误", }; return(Json(result)); //return new HttpResponseMessage { Content = new StringContent(result.ToString(), System.Text.Encoding.UTF8, "application/json") }; } else { var form = Request.Form; var sPara = GetRequestPost(form); WeiXinConfig wxconfig = BMAConfig.WeiXinConfig; if (sPara.Count <= 0) { throw new ArgumentNullException(); } //LogWriter.Default.WriteInfo(form.ToString());//记录请求关键信息到日志中去 BMALog.Instance.Write(form.ToString()); var out_trade_no = BrnMall.Core.Common.Utils.GenerateOutTradeNo() + "_" + sPara["paytype"]; //Guid.NewGuid().ToString(); var domain = wxconfig.Domain; var body = sPara["body"]; var detail = sPara["detail"]; var attach = sPara["attach"]; var fee_type = "CNY"; var total_fee = int.Parse(sPara["total_fee"]) * 100; var trade_type = sPara["trade_type"]; var spbill_create_ip = (trade_type == "APP" || trade_type == "NATIVE") ? Request.UserHostName : wxconfig.Spbill_create_ip; var time_start = DateTime.Now.ToString("yyyyMMddHHmmss"); var time_expire = DateTime.Now.AddHours(1).ToString("yyyyMMddHHmmss"); //默认1个小时订单过期,开发者可自定义其他超时机制,原则上微信订单超时时间不超过2小时 var goods_tag = sPara["goods_tag"]; var notify_url = wxconfig.NOTIFY_URL; //string.Format("{0}/mob/WXPay/Notify", domain);//与下面的Notify对应,开发者可自定义其他url地址 var product_id = sPara["product_id"]; var openid = sPara["openid"]; var partnerKey = wxconfig.PartnerKey; var content = WxPayAPI.UnifiedOrder( wxconfig.AppID, wxconfig.Mch_id, wxconfig.Device_info, Util.CreateNonce_str(), body, detail, attach, out_trade_no, fee_type, total_fee, spbill_create_ip, time_start, time_expire, goods_tag, notify_url, trade_type, product_id, openid, partnerKey); BMALog.Instance.Write("url:" + notify_url + "|||con:" + content); if (content.return_code.Value == "SUCCESS" && content.result_code.Value == "SUCCESS") { WxPayAPIHelp.WxPayData jsApiParam = new WxPayAPIHelp.WxPayData(); string payTimeSamp = DateTime.Now.Ticks.ToString().Substring(0, 10); jsApiParam.SetValue("appId", wxconfig.AppID); jsApiParam.SetValue("timeStamp", payTimeSamp); jsApiParam.SetValue("nonceStr", content.nonce_str.Value); jsApiParam.SetValue("package", "prepay_id=" + content.prepay_id.Value); jsApiParam.SetValue("signType", "MD5"); var result = new { prepay_id = content.prepay_id.Value, trade_type = content.trade_type.Value, sign = content.sign.Value, sign1 = jsApiParam.MakeSign(), timestamp = payTimeSamp, nonce_str = content.nonce_str.Value, return_code = content.result_code.Value, return_msg = "", }; //string result = "{\"return_code\":\"SUCCESS\",\"sc\":\"123\"}"; return(Json(result)); //return new HttpResponseMessage { Content = new StringContent(result.ToString(), System.Text.Encoding.UTF8, "application/json") }; } else { var result = new { return_code = content.return_code.Value, return_msg = content.return_msg.Value, }; return(Json(result)); //return new HttpResponseMessage { Content = new StringContent(result.ToString(), System.Text.Encoding.UTF8, "application/json") }; } } }
public ActionResult OrderPay() { //订单id列表 string oidList = WebHelper.GetQueryString("oidList"); string paySystemName = ""; decimal allSurplusMoney = 0M; List <OrderInfo> orderList = new List <OrderInfo>(); foreach (string oid in StringHelper.SplitString(oidList)) { //订单信息 OrderInfo orderInfo = Orders.GetOrderByOid(TypeHelper.StringToInt(oid)); if (orderInfo != null && orderInfo.Uid == WorkContext.Uid && orderInfo.OrderState == (int)OrderState.WaitPaying && orderInfo.PayMode == 1 && (paySystemName.Length == 0 || paySystemName == orderInfo.PaySystemName)) { orderList.Add(orderInfo); } else { return(Redirect(Url.Action("index", "home"))); } paySystemName = orderInfo.PaySystemName; allSurplusMoney += orderInfo.SurplusMoney; } if (orderList.Count < 1 || allSurplusMoney == 0M) { return(Redirect(Url.Action("index", "home"))); } WeiXinConfig wxconfig = BMAConfig.WeiXinConfig; var appId = wxconfig.AppID; //WeixinConfig.AppID; var nonceStr = Util.CreateNonce_str(); var timestamp = DateTime.Now.Ticks.ToString().Substring(0, 10); var domain = wxconfig.Domain; var url = Request.Url.ToString().Replace("#", "");// domain + Request.Url.PathAndQuery; var jsTickect = WeiXinHelp.IsExistjsapi_ticket(); var string1 = ""; var signature = WeiXinHelp.GetjsSDK_Signature(nonceStr, jsTickect, timestamp, url); //JSAPI.GetSignature(jsTickect, nonceStr, timestamp, url, out string1); var userAgent = Request.UserAgent; var userVersion = userAgent.Substring(userAgent.LastIndexOf("/") + 1); //WeiXinConfig wxconfig = BMAConfig.WeiXinConfig; //Logs.Write(form.ToString()); var out_trade_no = orderList[0].OSN; //Guid.NewGuid().ToString(); //var domain = wxconfig.Domain; var body = "购买创梦星火商城商品"; var detail = "购买创梦星火商城商品"; var attach = "购买创梦星火商城商品"; var fee_type = "CNY"; var total_fee = Decimal.ToInt32(orderList[0].SurplusMoney) * 100;// *100; var trade_type = "JSAPI"; var spbill_create_ip = (trade_type == "APP" || trade_type == "NATIVE") ? Request.UserHostName : wxconfig.Spbill_create_ip; var time_start = DateTime.Now.ToString("yyyyMMddHHmmss"); var time_expire = DateTime.Now.AddDays(7).ToString("yyyyMMddHHmmss"); //默认1个小时订单过期,开发者可自定义其他超时机制,原则上微信订单超时时间不超过2小时 var goods_tag = "商品"; var notify_url = wxconfig.NOTIFY_URL; //与下面的Notify对应,开发者可自定义其他url地址 var product_id = orderList[0].Oid.ToString(); var openid = WorkContext.Openid; var partnerKey = wxconfig.PartnerKey; var content = WxPayAPI.UnifiedOrder( wxconfig.AppID, wxconfig.Mch_id, wxconfig.Device_info, Util.CreateNonce_str(), body, detail, attach, out_trade_no, fee_type, total_fee, spbill_create_ip, time_start, time_expire, goods_tag, notify_url, trade_type, product_id, openid, partnerKey); var prepay_id = ""; //var trade_type = ""; var paySign = ""; //var timestamp = ""; var nonce_str = ""; var return_code = ""; if (content.return_code.Value == "SUCCESS" && content.result_code.Value == "SUCCESS") { WxPayAPIHelp.WxPayData jsApiParam = new WxPayAPIHelp.WxPayData(); string payTimeSamp = DateTime.Now.Ticks.ToString().Substring(0, 10); jsApiParam.SetValue("appId", wxconfig.AppID); jsApiParam.SetValue("timeStamp", payTimeSamp); jsApiParam.SetValue("nonceStr", content.nonce_str.Value); jsApiParam.SetValue("package", "prepay_id=" + content.prepay_id.Value); jsApiParam.SetValue("signType", "MD5"); //prepay_id = content.prepay_id.Value; prepay_id = content.prepay_id.Value; trade_type = content.trade_type.Value; paySign = jsApiParam.MakeSign(); timestamp = payTimeSamp; nonce_str = content.nonce_str.Value; return_code = content.result_code.Value; } else { return(PromptView("错误编号:" + content.return_code.Value + "错误信息:" + content.return_msg.Value)); } OrderPayModel model = new OrderPayModel(); model.OidList = oidList; model.AllSurplusMoney = allSurplusMoney; model.OrderList = orderList; model.PayPlugin = Plugins.GetPayPluginBySystemName(paySystemName); model.nonceStr = nonceStr; model.jsapiTicket = jsTickect; model.nonce_str = nonce_str; model.paySign = paySign; model.signature = signature; model.timestamp = timestamp; model.userAgent = userAgent; model.userVersion = userVersion; model.appId = appId; model.prepay_id = prepay_id; return(View(model)); //return PromptView("出错了!"); }
public ActionResult UserUpdate() { Models.UserUpdateModel model = new UserUpdateModel(); if (WebHelper.IsGet()) { if (WorkContext.UserLevel < 3) { WeiXinConfig wxconfig = BMAConfig.WeiXinConfig; var appId = wxconfig.AppID; //WeixinConfig.AppID; var nonceStr = Util.CreateNonce_str(); var timestamp = DateTime.Now.Ticks.ToString().Substring(0, 10); var domain = wxconfig.Domain; var url = Request.Url.ToString().Replace("#", "");// domain + Request.Url.PathAndQuery; var jsTickect = WeiXinHelp.IsExistjsapi_ticket(); var string1 = ""; var signature = WeiXinHelp.GetjsSDK_Signature(nonceStr, jsTickect, timestamp, url); //JSAPI.GetSignature(jsTickect, nonceStr, timestamp, url, out string1); var userAgent = Request.UserAgent; var userVersion = userAgent.Substring(userAgent.LastIndexOf("/") + 1); //微信版本号高于或者等于5.0才支持微信支付 model = new UserUpdateModel { appId = appId, nonceStr = nonceStr, signature = signature, timestamp = timestamp, jsapiTicket = jsTickect, string1 = string1, userAgent = userAgent, userVersion = userVersion, }; return(View(model)); //return View(model); } else { return(PromptView("/mob/ucenter", "你已是钻石会员")); } } else { int paytype = WebHelper.GetFormInt("paytype"); int payfee = 1; switch (paytype) { case 1: if (WorkContext.UserLevel >= 1) { return(AjaxResult("", "已是银卡会员")); } payfee = 100; break; case 2: if (WorkContext.UserLevel >= 2) { return(AjaxResult("error", "已是金卡会员")); } payfee = 200; if (WorkContext.UserLevel == 0) { paytype = 4; payfee = 300; } break; case 3: if (WorkContext.UserLevel >= 3) { return(AjaxResult("error", "已是钻石会员")); } payfee = 300; if (WorkContext.UserLevel == 1) { paytype = 5; payfee = 500; } if (WorkContext.UserLevel == 0) { paytype = 6; payfee = 600; } break; default: return(AjaxResult("error", "请选择卡类型")); break; } //return AjaxResult("success", WebHelper.GetRequestData("http://localhost:6174/mob/weixinweb/Notify", "body=" + paytype.ToString() + "&payfee=" + payfee)); // return AjaxResult("success", GetpayJson(paytype, payfee)); return(View()); } //model.appid = "100"; //return View(model); }
/// <summary> /// 用户登录 /// </summary> /// <returns></returns> public ActionResult Login() { if (Globals.IsMobileDevice() && Request.Url.AbsoluteUri.Contains(ConfigCore.Instance.ConfigCommonEntity.LoginWebUrl)) { return(Redirect(Request.Url.AbsoluteUri.Replace(ConfigCore.Instance.ConfigCommonEntity.LoginWebUrl, ConfigCore.Instance.ConfigCommonEntity.LoginMobileWebUrl))); } string returnurl = StringUtils.GetDbString(Request.QueryString["returnurl"]); string unionid = ""; string code = QueryString.SafeQ("wechatcode"); //微信自动登录 if (!string.IsNullOrEmpty(code)) { MemWeChatMsgEntity shortmsg = WeiXinJsSdk.Instance.GetWeChatShortInfo(code); if (!string.IsNullOrEmpty(shortmsg.OpenId) && !string.IsNullOrEmpty(shortmsg.UnionId)) { unionid = shortmsg.UnionId; System.Web.HttpContext.Current.Session[CommonKey.WeChatUnionId] = unionid; MemWeChatMsgEntity entity = new MemWeChatMsgEntity(); entity.AppId = WeiXinConfig.GetAppId(); entity.Status = (int)WeChatStatus.ShortInfo; entity.UnionId = shortmsg.UnionId; entity.OpenId = shortmsg.OpenId; MemWeChatMsgBLL.Instance.WeChatLogin(entity); ResultObj _result = MemberLoginBLL.Instance.Login(unionid, "", "", (int)ClientTypeEnum.PC, IPAddress.IP); if (_result != null && _result.Obj != null) { if (_result.Status == (int)CommonStatus.Success) { MemberLoginEntity _loginmodel = (MemberLoginEntity)_result.Obj; if (_loginmodel.Status == (int)MemberStatus.Active) { CookieBLL.SetLoginCookie(_loginmodel, false); CookieBLL.ComBineCart(1); CookieBLL.ComBineCartXuQiu(1); if (string.IsNullOrEmpty(returnurl)) { returnurl = SuperMarket.Core.ConfigCore.Instance.ConfigCommonEntity.MainWebUrl; } return(Redirect(returnurl)); } } } } } string tempcode = StringUtils.SafeCodeSmall(QueryString.SafeQNo("tempcode"));//临时自动登录 if (!string.IsNullOrEmpty(tempcode)) { ResultObj _resulttemp = MemberLoginBLL.Instance.LoginByTempCode(tempcode, unionid, (int)ClientTypeEnum.PC, IPAddress.IP); if (_resulttemp != null && _resulttemp.Obj != null) { if (_resulttemp.Status == (int)CommonStatus.Success) { MemberLoginEntity _loginmodel = (MemberLoginEntity)_resulttemp.Obj; if (_loginmodel.Status == (int)MemberStatus.Active) { CookieBLL.SetLoginCookie(_loginmodel, false); CookieBLL.ComBineCart(1); CookieBLL.ComBineCartXuQiu(1); if (string.IsNullOrEmpty(returnurl)) { returnurl = SuperMarket.Core.ConfigCore.Instance.ConfigCommonEntity.MainWebUrl; } return(Redirect(returnurl)); } } } } ViewBag.ReturnUrl = returnurl; return(View()); }
public ActionResult Monitor() { if (Request.InputStream.Length > 0) { string xml = string.Empty; using (StreamReader reader = new StreamReader(Request.InputStream)) { xml = reader.ReadToEnd(); } WeiXinPayRequestXML request = XmlOperator.Derialize <WeiXinPayRequestXML>(xml); if (request.result_code.ToUpper() != "SUCCESS") { return(Content("")); } int splitIndex = request.out_trade_no.IndexOf("_"); string orderID = request.out_trade_no; if (splitIndex > 0) { orderID = request.out_trade_no.Substring(0, splitIndex); } string where = string.Format("OrderID='{0}'", orderID); IList <Model.TD_Order_WeiXinPay> payList = weiXinPayBLL.GetList(where, "PayTime desc", null); int count = payList.Count((model) => { return(model.Status == 1); }); if (count > 0) { return(PayOK()); } var config = WeiXinConfig.GetConfig(); count = payList.Count((model) => { if (model.OrderID == orderID && model.NonceStr == request.nonce_str && config.AppID == request.appid && config.ShopID == request.mch_id) { return(true); } return(false); }); if (count > 0) { Model.TD_Order_WeiXinPay pay = new Model.TD_Order_WeiXinPay(); pay.OrderID = orderID; pay.NonceStr = request.nonce_str; pay.WeiXinOrderID = request.transaction_id; pay.OrderFee = request.total_fee; pay.CashFee = request.cash_fee; pay.Status = 1; pay.CallBackTime = DateTime.ParseExact(request.time_end, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture); int result = weiXinPayBLL.Sync(pay, orderID); if (result > 0) { return(PayOK()); } else { return(PayFail()); } } else { return(PayFail()); } } return(Content("")); }
/// <summary> /// 询价订单供应商发送微信提醒 /// </summary> /// <returns></returns> public string WeChatInquiryOrderSend() { ResultObj result = new ResultObj(); string ordercode = FormString.SafeQ("ordercode"); string memids = FormString.SafeQ("memids"); memids = memids.Trim(','); string[] memidattr = memids.Split(','); InquiryOrderEntity orderentity = InquiryOrderBLL.Instance.GetInquiryOrderByCode(ordercode); if (orderentity != null && orderentity.Status == (int)OrderInquiryStatusEnum.Quoting) { string url = string.Format(WeiXinConfig.URL_FORMAT_SendMsg, WeiXinJsSdk.Instance.GetAccessToken()); string resulturl = SuperMarketWebUrl.InquiryOrderSendWeChat(ordercode); string redirecturl = SuperMarketWebUrl.InquiryOrderUrl(ordercode); result.Obj = resulturl; ////获取链接导航Id //int navid = WeChatNavigationBLL.Instance.GetIdByUrl(redirecturl); foreach (string memidstr in memidattr) { int memid = StringUtils.GetDbInt(memidstr); MemberEntity memen = MemberBLL.Instance.GetMember(memid); if (!string.IsNullOrEmpty(memen.WeChat)) { MemWeChatMsgEntity wecharmsg = MemWeChatMsgBLL.Instance.GetMsgByAppUnionId(WeiXinConfig.GetAppId(), memen.WeChat); if (wecharmsg != null && !string.IsNullOrEmpty(wecharmsg.OpenId)) { WeiXinSendMsgEntity send = new WeiXinSendMsgEntity(); send.touser = wecharmsg.OpenId; send.template_id = WeiXinTemplet.InquiryQuoteSend; send.url = resulturl; WeiXinInquiryEntity inq = new WeiXinInquiryEntity(); inq.first = new WeiXinUnitEntity() { value = "您有订单需要报价啦,赶紧抢单,订单编号:" + orderentity.Code }; inq.tradeDateTime = new WeiXinUnitEntity() { value = orderentity.CreateTime.ToString("yyyy-MM-dd HH:mm:ss") }; inq.orderType = new WeiXinUnitEntity() { value = "询价订单" }; inq.customerInfo = new WeiXinUnitEntity() { value = "易店心" }; //inq.orderItemName = new WeiXinUnitEntity() { value = "随机名称" }; //inq.orderItemData = new WeiXinUnitEntity() { value = "随机数据" }; inq.remark = new WeiXinUnitEntity() { value = orderentity.Remark }; send.data = inq; string json = JsonJC.ObjectToJson(send); WeChatMsgEntity msg = new WeChatMsgEntity(); msg.ParamStr = json; msg.WeChatOpenId = wecharmsg.OpenId; msg.RedirectUrl = redirecturl; msg.WeChatUrl = url; msg.TemplateIid = WeiXinTemplet.InquiryQuoteSend; msg.Id = WeChatMsgBLL.Instance.AddWeChatMsg(msg); string resultrowi = WebServiceClient.QueryPostWebServiceJson(url, json); WeiXinFailEntity resulten = JsonJC.JsonToObject <WeiXinFailEntity>(resultrowi); if (resulten.errmsg.ToLower() == "ok") { CGMemQuotedBLL.Instance.CGQuotedSend(memid, ordercode); } msg.Result = resultrowi; WeChatMsgBLL.Instance.UpdateWeChatMsg(msg); } } } } else { CGMemQuotedBLL.Instance.QuotedCloseByCode(ordercode); } result.Status = (int)CommonStatus.Success; return(JsonJC.ObjectToJson(result)); }
public WeiXinHandler(IConfiguration configuration) { _weiXinConfig = configuration.GetSection(nameof(WeiXinConfig))?.Get <WeiXinConfig>(); }
public ActionResult OrderConfirm() { string paycode = QueryString.SafeQ("code"); int success = QueryString.IntSafeQ("s"); //是否需要订单成功提醒 int freshnum = QueryString.IntSafeQ("fn"); //循环次数,超过10次自动关闭 if (freshnum > 10) { return(null); } VWPayOrderEntity _payen = PayOrderBLL.Instance.GetVWPayOrderByPayCode(paycode); if (_payen.PayMethod == (int)PayType.WeChat)//微信支付 { if (Globals.IsWeiXinDevice()) { string wechatcode = ""; wechatcode = QueryString.SafeQ("wechatcode"); //是微信客户端走这边 if (string.IsNullOrEmpty(wechatcode)) { //没有获取微信授权码 string url = Request.Url.ToString(); string redirecturl = string.Format(WeiXinConfig.URL_WeiXin_Redirect, WeiXinConfig.GetAppId(), System.Web.HttpContext.Current.Server.UrlEncode(url), "0"); return(Redirect(redirecturl)); } else { //有微信授权码 JsApiPay jsApiPay = new JsApiPay(); try { jsApiPay.GetOpenidAndAccessTokenFromCode(wechatcode); } catch (Exception ex) { //授权码过期 string baseurl; Dictionary <string, string> nvc = new Dictionary <string, string>(); string oldurl = Request.Url.ToString(); StringUtils.ParseUrl(oldurl, out baseurl, out nvc); nvc.Remove("wechatcode"); if (nvc.ContainsKey("fn")) { nvc["fn"] = (StringUtils.GetDbInt(nvc["fn"]) + 1).ToString(); } else { nvc.Add("fn", "1"); } string url = baseurl + "?"; foreach (string key in nvc.Keys) { url += "&" + key + "=" + nvc[key]; } string redirecturl = string.Format(WeiXinConfig.URL_WeiXin_Redirect, WeiXinConfig.GetAppId(), System.Web.HttpContext.Current.Server.UrlEncode(url), "0"); return(Redirect(redirecturl)); } WxPayData paydata = jsApiPay.GetUnifiedOrderResult(_payen); string wxJsApiParam = jsApiPay.GetJsApiParameters();//获取H5调起JS API参数 ViewBag.WeiXinJsApiParam = wxJsApiParam; } } else { //网站类调出微信端支付通道 DateTime dtnow = DateTime.Now; NativePay nativePay = new NativePay(); WxPayData data = nativePay.GetPayUrl(_payen, "MWEB");//得到调用微信接口的路径 string url = data.GetValue("mweb_url").ToString(); return(Redirect(url)); } } ViewBag.PayOrderEntity = _payen; ViewBag.Success = success; return(View()); }
public async Task DeleteWeiXinConfigAsync(WeiXinConfig weixinconfig) { await _weixinconfigRepository.DeleteAsync(weixinconfig); }
public ActionResult WeiXin() { if (Globals.IsWeiXinDevice()) { //是微信客户端走这边 string wechatcode = QueryString.SafeQ("wechatcode"); if (string.IsNullOrEmpty(wechatcode)) { string url = Request.Url.ToString(); string redirecturl = string.Format(WeiXinConfig.URL_WeiXin_Redirect, WeiXinConfig.GetAppId(), System.Web.HttpContext.Current.Server.UrlEncode(url), "0"); return(Redirect(redirecturl)); } else { MemWeChatMsgEntity msg = WeiXinJsSdk.Instance.GetWeChatShortInfo(wechatcode); string _paycode = QueryString.SafeQ("paycode"); VWPayOrderEntity _payen = PayOrderBLL.Instance.GetVWPayOrderByPayCode(_paycode); string redirecturl = string.Format(WeiXinConfig.URL_Pay_InWeiXin, msg.OpenId, _payen.NeedPayPrice); Response.Redirect(redirecturl); } } else { //网站类调出微信端支付通道 string _paycode = QueryString.SafeQ("paycode"); VWPayOrderEntity _payen = PayOrderBLL.Instance.GetVWPayOrderByPayCode(_paycode); DateTime dtnow = DateTime.Now; NativePay nativePay = new NativePay(); WxPayData data = nativePay.GetPayUrl(_payen, "MWEB");//得到调用微信接口的路径 string url = data.GetValue("mweb_url").ToString(); return(Redirect(url)); } return(View()); }
public ActionResult SendBag() { if (WorkContext.UserLevel <= 0) { return(PromptView("请先提升您的等级!")); } Core.BLL.SendBag sendBll = new Core.BLL.SendBag(); if (WebHelper.IsGet()) { int type = WebHelper.GetQueryInt("Sendtype", 1); int page = WebHelper.GetQueryInt("page"); int count = 0; List <Core.Model.SendBag> list = sendBll.GetModelList(20, page, " Receiverid=" + WorkContext.Uid + " and status=0 and Sendtype=" + type, "id", out count); PageModel pageModel = new PageModel(20, page, count); SendBagModel model = new SendBagModel { PageModel = pageModel, SendBagList = list, Sendtype = type }; return(View(model)); } else { try { lock (this) { WeiXinConfig wxconfig = BMAConfig.WeiXinConfig; int sendid = WebHelper.GetFormInt("sendid"); List <Core.Model.SendBag> listsendbag = sendBll.GetModelList(" status=0 and id=" + sendid); if (listsendbag.Count > 0 && listsendbag[0].ReceiverID == WorkContext.Uid) { string Noncestr = ""; string paysign = ""; try { int bcount = sendBll.GetRecordCount(" status=1 and ReceiverID=" + WorkContext.Uid + " and sendtype=" + WorkContext.UserLevel); if (WorkContext.UserLevel == 1) { if (bcount >= 3) { return(AjaxResult("error", "您领取的红包已达到上限,请先提升您的等级!")); } } if (WorkContext.UserLevel == 2) { if (bcount >= 9) { return(AjaxResult("error", "您领取的红包已达到上限,请先提升您的等级!")); } } if (listsendbag[0].IsNotSend == 0) { NormalRedPackResult nop = RedPackApi.SendNormalRedPack(listsendbag[0].Mchbillno, wxconfig.AppID, wxconfig.Mch_id, wxconfig.PartnerKey, Server.MapPath(wxconfig.SSLCERT_PATH), WorkContext.Openid, "创梦星火", wxconfig.Spbill_create_ip, listsendbag[0].Pice.Value * 100, "更上一层楼", "创梦帮扶活动", "祝您更上一层楼", out Noncestr, out paysign); if (nop.err_code_des == "") { listsendbag[0].Status = 1; listsendbag[0].SendTime = DateTime.Now; sendBll.Update(listsendbag[0]); return(AjaxResult("success", "发送成功")); } else { return(AjaxResult("error", nop.err_code_des)); } } else { return(AjaxResult("error", "该红包处于冻结状态,暂时无法领取.")); } } catch (Exception ex) { return(AjaxResult("error", ex.ToString())); } } else { return(AjaxResult("error", "红包不存在或已发送")); } } } catch (Exception ex) { return(AjaxResult("error", ex.ToString())); } } }