public ActionResult Charge(AgentChargeModel model) { if (ModelState.IsValid) { try { ChargeBridge cb = new ChargeBridge(); ChargeOrder order = new ChargeOrder() { Payed = false, OperateUserId = 0, AgencyId = User.Identity.GetUserId <int>(), Id = 0, Province = model.Province, City = model.City, MobileSP = model.SPName, MobileNumber = model.Mobile, OutOrderId = "", ResourceId = 0, ResourceTaocanId = model.ResourceTaocanId, RouteId = model.RouteId, CreatedTime = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now) }; OrderManagement orderMgt = new OrderManagement(); order = orderMgt.GenerateOrder(order); //ChargeResult result = cb.Charge(order); ViewBag.Message = "成功提交到充值系统,等待充值,可以到流量充值查询里查看充值状态..."; } catch (KMBitException ex) { ViewBag.Message = ex.Message; }finally { model = new AgentChargeModel(); } } return(View(model)); }
public ActionResult Charge(ChargeModel model) { if (ModelState.IsValid) { //ChargeBridge cb = new ChargeBridge(); ChargeOrder order = new ChargeOrder() { ChargeType = 0, AgencyId = 0, Id = 0, Province = model.Province, City = model.City, MobileSP = model.SPName, MobileNumber = model.Mobile, OutId = "", ResourceId = 0, ResourceTaocanId = model.ResourceTaocanId, RouteId = 0, CreatedTime = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now) }; // OrderManagement orderMgt = new OrderManagement(); ResourceManagement resourceMgr = new ResourceManagement(0); order = orderMgt.GenerateOrder(order); int total = 0; List <BResourceTaocan> taocans = resourceMgr.FindResourceTaocans(order.ResourceTaocanId, 0, 0, out total); if (taocans == null || taocans.Count == 0) { ViewBag.Message = "当前套餐不可用"; return(View()); } BResourceTaocan taocan = taocans[0]; //Redirct to the payment page. //TBD //After the payment is done then process below steps AlipayConfig config = new AlipayConfig(System.IO.Path.Combine(Request.PhysicalApplicationPath, "Config\\AliPayConfig.xml")); Submit submit = new Submit(config); SortedDictionary <string, string> sParaTemp = new SortedDictionary <string, string>(); sParaTemp.Add("partner", config.Partner); sParaTemp.Add("seller_email", "*****@*****.**"); sParaTemp.Add("_input_charset", config.Input_charset.ToLower()); sParaTemp.Add("service", "create_direct_pay_by_user"); sParaTemp.Add("payment_type", "1"); sParaTemp.Add("notify_url", config.Notify_Url); sParaTemp.Add("return_url", config.Return_Url); sParaTemp.Add("out_trade_no", order.PaymentId.ToString()); sParaTemp.Add("subject", string.Format("{0}M", taocan.Taocan.Quantity)); sParaTemp.Add("total_fee", taocan.Taocan.Sale_price.ToString("0.00")); sParaTemp.Add("body", string.Format("{0}M", taocan.Taocan.Quantity)); sParaTemp.Add("show_url", ""); sParaTemp.Add("seller_id", config.Partner); //sParaTemp.Add("anti_phishing_key", ""); //sParaTemp.Add("exter_invoke_ip", ""); //建立请求 string sHtmlText = submit.BuildRequest(sParaTemp, "get", "确认"); //Response.Write("ok"); Response.Clear(); Response.Charset = "utf-8"; Response.Write(sHtmlText); //ChargeResult result = cb.Charge(order); //ViewBag.Message = result.Message; } return(View()); }
public APIChargeResult Charge(int agendId, int routeId, string mobile, string province, string city, string callBackUrl) { ChargeResult result = null; ChargeBridge cb = new ChargeBridge(); ChargeOrder order = new ChargeOrder() { Payed = false, OperateUserId = 0, AgencyId = agendId, Id = 0, Province = province, City = city, MobileNumber = mobile, OutId = "", ResourceId = 0, ResourceTaocanId = 0, RouteId = routeId, CreatedTime = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now), CallbackUrl = callBackUrl }; OrderManagement orderMgt = new OrderManagement(); try { order = orderMgt.GenerateOrder(order); result = cb.Charge(order); } catch (KMBitException kex) { result = new ChargeResult(); result.Status = ChargeStatus.FAILED; result.Message = kex.Message; }catch (Exception ex) { result = new ChargeResult(); result.Status = ChargeStatus.FAILED; result.Message = "未知错误,请联系平台管理员"; } APIChargeResult apiResult = new APIChargeResult(); apiResult.Message = result.Message; apiResult.OrderId = order.Id; switch (result.Status) { case ChargeStatus.SUCCEED: apiResult.Status = 2; break; case ChargeStatus.FAILED: apiResult.Status = 2; break; case ChargeStatus.ONPROGRESS: apiResult.Status = 1; break; case ChargeStatus.PENDIND: apiResult.Status = 10; break; } return(apiResult); }
/// <summary> /// This method is only applied to platform direct charge /// </summary> /// <param name="orderId"></param> public ChargeResult ProcessOrderAfterPaid(int paymentId, string tradeNo, string buyerAccount) { ChargeResult result = new ChargeResult(); using (chargebitEntities db = new chargebitEntities()) { Payment_history payment = (from p in db.Payment_history where p.Id == paymentId select p).FirstOrDefault <Payment_history>(); if (payment == null) { result.Status = ChargeStatus.FAILED; result.Message = string.Format("编号为:{0}的支付编号不存在", paymentId); return(result); } payment.Pay_time = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now); payment.PaymentAccount = buyerAccount != null?buyerAccount:""; payment.PaymentTradeId = tradeNo != null ? tradeNo : ""; db.SaveChanges(); //前台用户直充网络支付成功之后,提交订单到资源充值 if (payment.PayType == 0) { if (payment.ChargeOrderId <= 0) { result.Status = ChargeStatus.FAILED; result.Message = string.Format("编号为:{0}的支付编号没有相关充值订单", paymentId); return(result); } Charge_Order corder = (from o in db.Charge_Order where o.Id == payment.ChargeOrderId select o).FirstOrDefault <Charge_Order>(); corder.Payed = true; db.SaveChanges(); ChargeOrder order = new ChargeOrder() { Payed = true, ChargeType = corder.Charge_type, AgencyId = corder.Agent_Id, Id = corder.Id, Province = corder.Province, City = corder.City, MobileSP = corder.MobileSP, MobileNumber = corder.Phone_number, OutId = "", ResourceId = 0, ResourceTaocanId = corder.Resource_taocan_id, RouteId = corder.RuoteId, CreatedTime = corder.Created_time }; ChargeBridge cb = new ChargeBridge(); result = cb.Charge(order); } } return(result); }
public async Task <Status> InsertOrder(string merchantCode , string merchantrefNumber, string customerId) { StatusResponse FawrychargeStatus = await CheckStatus(merchantCode, merchantrefNumber); ChargeOrder order = new ChargeOrder() { Amount = FawrychargeStatus.paymentAmount, CustomerID = customerId, MercchantRefrenceNumber = FawrychargeStatus.merchantRefNumber, MerchatCode = merchantCode, PaymentStatus = FawrychargeStatus.paymentStatus, Points = Points }; //Add order into database. return(new Status() { StatusResponseObject = FawrychargeStatus, Points = Points }); }
public ChargeResult Charge(ChargeOrder order) { Logger.Info("Charging..."); ChargeResult result = new ChargeResult() { Status = ChargeStatus.FAILED }; chargebitEntities db = null; ProceedOrder(order, out result); if (result.Status == ChargeStatus.FAILED) { return result; } List<WebRequestParameters> parmeters = new List<WebRequestParameters>(); bool succeed = false; try { db = new chargebitEntities(); Charge_Order corder = (from co in db.Charge_Order where co.Id == order.Id select co).FirstOrDefault<Charge_Order>(); corder.Process_time = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now); KMBit.DAL.Resrouce_interface rInterface = (from ri in db.Resrouce_interface where ri.Resource_id == order.ResourceId select ri).FirstOrDefault<Resrouce_interface>(); Resource_taocan taocan = (from t in db.Resource_taocan where t.Id == order.ResourceTaocanId select t).FirstOrDefault<Resource_taocan>(); if(string.IsNullOrEmpty(rInterface.APIURL)) { result.Status = ChargeStatus.FAILED; result.Message = "资源充值API URL没有配置"; Logger.Error("Cannot get token."); ChangeOrderStatus(order, result); return result; } ServerUri = new Uri(rInterface.APIURL); if(string.IsNullOrEmpty(token)) { Logger.Info("Token doesn't exist, try to request one."); GetToken(rInterface); } else { Logger.Info("Token is already existed."); } if(DateTimeUtil.ConvertDateTimeToInt(DateTime.Now)> expiredTime) { Logger.Info("Existing token is already expired, try to request a new one."); GetToken(rInterface); } if(string.IsNullOrEmpty(token)) { result.Status = ChargeStatus.FAILED; result.Message = "获取令牌失败"; Logger.Error("Failed to request token, please contact gatway administrator. The charge order will be marked as fail, refound the currency to agent."); ChangeOrderStatus(order, result); return result; } StringBuilder jsonParam = new StringBuilder(); corder.Out_Order_Id = rInterface.Username + DateTimeUtil.ConvertDateTimeToInt(DateTime.Now).ToString("0"); order.OutOrderId = corder.Out_Order_Id; db.SaveChanges(); jsonParam.Append("["); jsonParam.Append("{"); jsonParam.Append("\"orderId\":"); jsonParam.Append("\""+corder.Out_Order_Id.Trim()+"\","); jsonParam.Append("\"accNumber\":"); jsonParam.Append("\"" + corder.Phone_number.Trim() + "\","); jsonParam.Append("\"pricePlanCd\":"); jsonParam.Append("\"" + taocan.Serial.Trim() + "\","); jsonParam.Append("\"orderType\":"); jsonParam.Append("\"0\""); jsonParam.Append("}"); jsonParam.Append("]"); parmeters.Add(new WebRequestParameters() {Name="para",Value=jsonParam.ToString() }); parmeters.Add(new WebRequestParameters() { Name = "token", Value = token }); parmeters.Add(new WebRequestParameters() { Name = "id", Value = rInterface.Username.Trim() }); SendRequest(parmeters, false, out succeed, RequestType.POST); if (!string.IsNullOrEmpty(Response)) { try { Newtonsoft.Json.Linq.JObject jsonResult = Newtonsoft.Json.Linq.JObject.Parse(Response); string ret = jsonResult["result"].ToString(); string message = jsonResult["resultMsg"].ToString(); if (!string.IsNullOrEmpty(ret) && ret.Trim() == "0") { result.Status = ChargeStatus.ONPROGRESS; } else { result.Status = ChargeStatus.FAILED; } result.Message = message; } catch (Exception ex) { Logger.Fatal(ex); result.Status = ChargeStatus.FAILED; result.Message = "系统错误,请联系管理员"; } if (result.Message != null && result.Message.Length > 5000) { result.Message = result.Message.Substring(0, 5000); } ChangeOrderStatus(order, result); } } catch(Exception ex) { Logger.Fatal(ex); } finally { if (db != null) { db.Dispose(); } } Logger.Info("Charging done!"); return result; }
public ChargeResult Charge(ChargeOrder order) { ChargeResult result = new ChargeResult() { Status = ChargeStatus.FAILED }; chargebitEntities db = null; ProceedOrder(order, out result); if (result.Status == ChargeStatus.FAILED) { return(result); } List <WebRequestParameters> parmeters = new List <WebRequestParameters>(); bool succeed = false; try { db = new chargebitEntities(); Charge_Order corder = (from co in db.Charge_Order where co.Id == order.Id select co).FirstOrDefault <Charge_Order>(); corder.Process_time = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now); KMBit.DAL.Resrouce_interface rInterface = (from ri in db.Resrouce_interface where ri.Resource_id == order.ResourceId select ri).FirstOrDefault <Resrouce_interface>(); Resource_taocan taocan = (from t in db.Resource_taocan where t.Id == order.ResourceTaocanId select t).FirstOrDefault <Resource_taocan>(); ServerUri = new Uri(rInterface.APIURL); parmeters.Add(new WebRequestParameters("V", version, false)); parmeters.Add(new WebRequestParameters("Action", "charge", false)); parmeters.Add(new WebRequestParameters("Range", taocan.Area_id > 0 ? "1" : "0", false)); SortedDictionary <string, string> paras = new SortedDictionary <string, string>(); paras["Account"] = rInterface.Username; paras["Mobile"] = order.MobileNumber; paras["Package"] = taocan.Quantity.ToString(); string signStr = ""; foreach (KeyValuePair <string, string> p in paras) { if (signStr == string.Empty) { signStr += p.Key.ToLower() + "=" + p.Value; } else { signStr += "&" + p.Key.ToLower() + "=" + p.Value; } } signStr += "&key=" + KMAes.DecryptStringAES(rInterface.Userpassword); paras["Sign"] = UrlSignUtil.GetMD5(signStr); foreach (KeyValuePair <string, string> p in paras) { parmeters.Add(new WebRequestParameters(p.Key, p.Value, false)); } SendRequest(parmeters, false, out succeed); if (!string.IsNullOrEmpty(Response)) { JObject jsonResult = JObject.Parse(Response); order.OutOrderId = jsonResult["TaskID"] != null ? jsonResult["TaskID"].ToString() : ""; string code = jsonResult["Code"] != null ? jsonResult["Code"].ToString() : ""; string message = jsonResult["Message"] != null ? jsonResult["Message"].ToString() : ""; result.Message = message; switch (code) { case "0": result.Message = ChargeConstant.CHARGING; result.Status = ChargeStatus.ONPROGRESS; break; case "001": result.Status = ChargeStatus.FAILED; break; case "002": result.Status = ChargeStatus.FAILED; break; case "003": result.Status = ChargeStatus.FAILED; break; case "004": result.Status = ChargeStatus.FAILED; result.Message = ChargeConstant.RESOURCE_NOT_ENOUGH_MONEY; break; case "005": result.Status = ChargeStatus.FAILED; break; case "006": result.Status = ChargeStatus.FAILED; break; case "007": result.Status = ChargeStatus.FAILED; break; case "008": result.Status = ChargeStatus.FAILED; break; case "009": result.Status = ChargeStatus.FAILED; break; case "100": result.Status = ChargeStatus.FAILED; break; case "999": result.Status = ChargeStatus.FAILED; break; default: result.Status = ChargeStatus.FAILED; break; } ChangeOrderStatus(order, result); } } catch (Exception ex) { Logger.Fatal(ex); }finally { if (db != null) { db.Dispose(); } } return(result); }
public static void ProcessOrders() { logger.Info("Going to process orders..."); chargebitEntities db = null; try { List<Charge_Order> orders = null; db = new chargebitEntities(); lock (o) { logger.Info("Last Max Order Id:" + lastOrderId); orders = (from o in db.Charge_Order where o.Id > lastOrderId && ((o.Payed == true && o.Charge_type == 0 && o.Status == 10) || (o.Charge_type == 1 && o.Status != 3 && o.Status != 2) || (o.Charge_type == 2 && o.Status != 3 && o.Status != 2)) orderby o.Charge_type ascending orderby o.Id ascending select o).ToList<Charge_Order>(); logger.Info(string.Format("Get {0} unprocessed orders", orders.Count)); if (orders.Count == 0) { logger.Info("No unprocessed orders, thread will exit!"); return; } lastOrderId = (from o in orders select o.Id).Max(); logger.Info("Max Order Id updated to:"+lastOrderId); } List<int> agentIds = (from o in orders where o.Agent_Id > 0 select o.Agent_Id).ToList<int>(); List<Users> agents = new List<Users>(); if(agentIds!=null && agentIds.Count>0) { int[] ids = agentIds.ToArray<int>(); agents = (from u in db.Users where ids.Contains(u.Id) select u).ToList<Users>(); } List<Charge_Order> frontEndOrders = (from o in orders where o.Payed == true && o.Charge_type == 0 && o.Status == 10 select o).ToList<Charge_Order>(); List<Charge_Order> agentOrders = (from o in orders where o.Charge_type == 1 && o.Status != 3 && o.Status != 2 select o).ToList<Charge_Order>(); List<Charge_Order> backendOrders = (from o in orders where o.Charge_type == 2 && o.Status != 3 && o.Status != 2 select o).ToList<Charge_Order>(); //logger.Info(string.Format("{0} unprocessed frontend orders", frontEndOrders.Count)); //logger.Info(string.Format("{0} unprocessed agent orders", agentOrders.Count)); //logger.Info(string.Format("{0} unprocessed backend orders", backendOrders.Count)); ChargeResult result = null; logger.Info(""); foreach (Charge_Order corder in orders) { logger.Info(string.Format("Processing order Id-{0}, Phone-{1}, Agent-{2}, ChargeType-{3}", corder.Id.ToString(),corder.Phone_number,corder.Agent_Id,corder.Charge_type)); ChargeOrder order = new ChargeOrder() { Payed = corder.Payed, ChargeType = corder.Charge_type, AgencyId = corder.Agent_Id, OperateUserId = corder.Operate_User, Id = corder.Id, Province = corder.Province, City = corder.City, MobileSP = corder.MobileSP, MobileNumber = corder.Phone_number, OutOrderId = "", ResourceId = 0, ResourceTaocanId = corder.Resource_taocan_id, RouteId = corder.RuoteId, CreatedTime = corder.Created_time }; result = cb.Charge(order); Users agent = (from u in agents where corder.Agent_Id>0 && corder.Agent_Id==u.Id select u).FirstOrDefault<Users>(); logger.Info("Order status - " +order.Status); if(order.Status==1) { logger.Info("Sync status process will do the callback request."); } if(!string.IsNullOrEmpty(corder.CallBackUrl) && corder.Agent_Id>0 && agent!=null && order.Status!=1) { //send back the status to agent system NameValueCollection col = new NameValueCollection(); SortedDictionary<string, string> param = new SortedDictionary<string, string>(); param.Add("OrderId", corder.Id.ToString()); param.Add("ClientOrderId", corder.Client_Order_Id!=null?corder.Client_Order_Id.ToString():""); param.Add("Message", result.Message); param.Add("Status", result.Status.ToString()); string querystr = ""; foreach(KeyValuePair<string,string> p in param) { col.Add(p.Key, p.Value != null ? p.Value : ""); if (querystr=="") { querystr = p.Key + "=" + (p.Value != null ? p.Value : ""); } else { querystr +="&"+ p.Key + "=" + (p.Value != null ? p.Value : ""); } } logger.Info(string.Format("Post data to callback url - {0}",corder.CallBackUrl)); logger.Info(string.Format("Data - {0}",querystr)); querystr += "&key=" + agent.SecurityStamp; string sign = UrlSignUtil.GetMD5(querystr); col.Add("Sign",sign); //logger.Info("sign=" + sign); HttpSercice.PostHttpRequest(corder.CallBackUrl, col, WeChat.Adapter.Requests.RequestType.POST, null); } logger.Info(string.Format("Order ID:{2} - {0} - {1}",result.Status,result.Message,corder.Id)); logger.Info(""); } } catch(Exception ex) { logger.Error(ex); } finally { if(db!=null) { db.Dispose(); } } }
public ChargeResult Charge(ChargeOrder order) { ChargeResult result = new ChargeResult(); ProceedOrder(order, out result); if (result.Status == ChargeStatus.FAILED) { return(result); } List <WebRequestParameters> parmeters = new List <WebRequestParameters>(); bool succeed = false; result = new ChargeResult(); chargebitEntities db = null; try { db = new chargebitEntities(); Charge_Order corder = (from co in db.Charge_Order where co.Id == order.Id select co).FirstOrDefault <Charge_Order>(); corder.Process_time = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now); KMBit.DAL.Resrouce_interface rInterface = (from ri in db.Resrouce_interface where ri.Resource_id == order.ResourceId select ri).FirstOrDefault <Resrouce_interface>(); Resource_taocan taocan = (from t in db.Resource_taocan where t.Id == order.ResourceTaocanId select t).FirstOrDefault <Resource_taocan>(); if (string.IsNullOrEmpty(taocan.Serial)) { result.Message = ChargeConstant.RESOURCE_TAOCAN_NO_PDTID; result.Status = ChargeStatus.ONPROGRESS; return(result); } ServerUri = new Uri(rInterface.APIURL); parmeters.Add(new WebRequestParameters("appKey", rInterface.Username, false)); parmeters.Add(new WebRequestParameters("appSecret", KMAes.DecryptStringAES(rInterface.Userpassword), false)); parmeters.Add(new WebRequestParameters("phoneNo", order.MobileNumber, false)); parmeters.Add(new WebRequestParameters("prodCode", taocan.Serial, false)); parmeters.Add(new WebRequestParameters("backUrl", rInterface.CallBackUrl, false)); parmeters.Add(new WebRequestParameters("transNo", order.Id.ToString(), false)); SendRequest(parmeters, false, out succeed); if (!string.IsNullOrEmpty(Response)) { JObject jsonResult = JObject.Parse(Response); order.OutId = jsonResult["orderId"] != null? jsonResult["orderId"].ToString():""; string res = jsonResult["respCode"] != null?jsonResult["respCode"].ToString():""; string resMsg = jsonResult["respMsg"] != null?jsonResult["respMsg"].ToString():""; switch (res.ToLower()) { case "jx0000": result.Message = ChargeConstant.CHARGING; result.Status = ChargeStatus.ONPROGRESS; break; case "0000": case "00000": case "000000": result.Message = ChargeConstant.SUCCEED_CHARGE; result.Status = ChargeStatus.SUCCEED; break; case "jx0001": result.Message = ChargeConstant.AGENT_WRONG_PASSWORD; result.Status = ChargeStatus.FAILED; break; case "jx0002": result.Message = ChargeConstant.AGENT_NOT_BIND_IP; result.Status = ChargeStatus.FAILED; break; case "jx0003": result.Message = ChargeConstant.AGENT_IP_NOT_MATCH; result.Status = ChargeStatus.FAILED; break; case "jx0004": result.Message = ChargeConstant.RESOURCE_PRODUCT_NOT_EXIST; result.Status = ChargeStatus.FAILED; break; case "jx0005": result.Message = ChargeConstant.RESOURCE_NOT_ENOUGH_MONEY; result.Status = ChargeStatus.FAILED; break; default: result.Message = resMsg; result.Status = ChargeStatus.FAILED; break; } ChangeOrderStatus(order, result); } } catch (Exception ex) { }finally { if (db != null) { db.Dispose(); } } return(result); }
public JsonResult PreCharge(WeChatChargeModel model) { logger.Info("WeChatController.PreCharge......................................................"); ApiMessage message = new ApiMessage(); ChargeOrder order = null; if (ModelState.IsValid) { try { if (string.IsNullOrEmpty(model.OpenId)) { message.Status = "ERROR"; message.Message = "请从公众号菜单打开此页面"; return(Json(message, JsonRequestBehavior.AllowGet)); } //ChargeBridge cb = new ChargeBridge(); order = new ChargeOrder() { ChargeType = 0, AgencyId = 0, Id = 0, Province = model.Province, City = model.City, MobileSP = model.SPName, MobileNumber = model.Mobile, OutOrderId = "", ResourceId = 0, ResourceTaocanId = model.ResourceTaocanId, RouteId = 0, CreatedTime = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now), Payed = false, OpenId = model.OpenId, OpenAccountType = 1 }; // OrderManagement orderMgt = new OrderManagement(); ResourceManagement resourceMgr = new ResourceManagement(0); string msg = string.Empty; if (orderMgt.IsThisMonthCharged(order.MobileNumber, order.ResourceTaocanId, out msg)) { message.Status = "ERROR"; message.Message = msg; return(Json(message, JsonRequestBehavior.AllowGet)); } order = orderMgt.GenerateOrder(order); int total = 0; List <BResourceTaocan> taocans = resourceMgr.FindResourceTaocans(order.ResourceTaocanId, 0, 0, out total); if (taocans == null || taocans.Count == 0) { message.Message = "当前套餐不可用"; message.Status = "ERROR"; return(Json(message, JsonRequestBehavior.AllowGet)); } logger.Info(string.Format("Order is generated, Id - {0}, mobile - {1}", order.Id, order.MobileNumber)); BResourceTaocan taocan = taocans[0]; message.Status = "OK"; message.Message = "预充值订单已经生成"; message.Item = null; // string ip = Request.ServerVariables["REMOTE_ADDR"]; if (ip != null && ip.IndexOf("::") > -1) { ip = "127.0.0.1"; } string prepayId = WeChatPaymentWrapper.GetPrepayId(PersistentValueManager.config, Session["wechat_openid"] != null ? Session["wechat_openid"].ToString() : "", order.PaymentId.ToString(), "TEST WECHATPAY", ip, (int)taocan.Taocan.Sale_price * 100, TradeType.JSAPI); logger.Info(string.Format("Prepay Id - {0}", prepayId)); WeChatOrder weOrder = new WeChatOrder(); weOrder.Order = new ChargeOrder { Id = order.Id, Payed = order.Payed, PaymentId = order.PaymentId, MobileNumber = order.MobileNumber, MobileSP = order.MobileSP, Province = order.Province }; weOrder.PrepayId = prepayId; weOrder.PaySign = ""; message.Item = weOrder; AccessToken token = PersistentValueManager.GetWeChatAccessToken(); JSAPITicket ticket = PersistentValueManager.GetWeChatJsApiTicket(); SortedDictionary <string, string> parameters = new SortedDictionary <string, string>(); parameters.Add("appId", PersistentValueManager.config.APPID); parameters.Add("timeStamp", model.timestamp); parameters.Add("nonceStr", model.nancestr); parameters.Add("package", "prepay_id=" + prepayId); parameters.Add("signType", "MD5"); logger.Info(string.Format("timeStamp:{0}", model.timestamp)); logger.Info(string.Format("nonceStr:{0}", model.nancestr)); logger.Info(string.Format("package:{0}", "prepay_id=" + prepayId)); string querystr = null; foreach (KeyValuePair <string, string> para in parameters) { if (querystr == null) { querystr = para.Key + "=" + para.Value; } else { querystr += "&" + para.Key + "=" + para.Value; } } querystr += "&key=" + PersistentValueManager.config.ShopSecret; logger.Info(querystr); string sign = UrlSignUtil.GetMD5(querystr); model.paySign = sign.ToUpper(); model.prepay_id = prepayId; logger.Info(string.Format("paySign:{0}", sign.ToUpper())); message.Item = model; } catch (KMBitException kex) { logger.Error(kex); message.Message = kex.Message; message.Status = "ERROR"; } catch (Exception ex) { message.Message = "未知错误,请联系我们"; message.Status = "ERROR"; logger.Fatal(ex); } finally { } } logger.Info("Done."); return(Json(message, JsonRequestBehavior.AllowGet)); }
public void CallBack(List<WebRequestParameters> data) { if(data==null) { return; } string res = ""; string resMessage = ""; ChargeResult result = new ChargeResult(); ChargeOrder order = new ChargeOrder(); foreach(WebRequestParameters param in data) { switch(param.Name) { case "orderId": order.OutOrderId = param.Value; break; case "respCode": res = param.Value; break; case "respMsg": resMessage = param.Value; break; case "transNo": int oid = 0; int.TryParse(param.Value,out oid); order.Id = oid; break; } } if(!string.IsNullOrEmpty(res)) { switch (res.ToLower()) { case "jx0000": result.Message = ChargeConstant.CHARGING; result.Status = ChargeStatus.ONPROGRESS; break; case "0000": case "00000": case "000000": result.Message = ChargeConstant.SUCCEED_CHARGE; result.Status = ChargeStatus.SUCCEED; //change charge status break; case "jx0001": result.Message = ChargeConstant.AGENT_WRONG_PASSWORD; result.Status = ChargeStatus.FAILED; break; case "jx0002": result.Message = ChargeConstant.AGENT_NOT_BIND_IP; result.Status = ChargeStatus.FAILED; break; case "jx0003": result.Message = ChargeConstant.AGENT_IP_NOT_MATCH; result.Status = ChargeStatus.FAILED; break; case "jx0004": result.Message = ChargeConstant.RESOURCE_PRODUCT_NOT_EXIST; result.Status = ChargeStatus.FAILED; break; case "jx0005": result.Message = ChargeConstant.RESOURCE_NOT_ENOUGH_MONEY; result.Status = ChargeStatus.FAILED; break; default: result.Message = resMessage!=null?res:"未知错误"; result.Status = ChargeStatus.FAILED; break; } }else { //回调没有传入状态,本系统默认失败 result.Message = "没有回调状态数据"; result.Status = ChargeStatus.FAILED; } if (order.Id > 0) { ChangeOrderStatus(order, result, true); //sending back status if the invoked by agent api using (chargebitEntities db = new chargebitEntities()) { Charge_Order dbOrder = (from o in db.Charge_Order where o.Id== order.Id select o).FirstOrDefault<Charge_Order>(); if (dbOrder != null && !string.IsNullOrEmpty(dbOrder.CallBackUrl)) { this.SendStatusBackToAgentCallback(dbOrder); } } } else { throw new KMBitException("回调数据中没有本系统的订单号,所以不能更新本系统数据,此次调用为脏数据"); } }
public virtual void ProceedOrder(ChargeOrder order,out ChargeResult result,bool isSOAPAPI=false) { lock (o) { Logger.Info("Processing order..."); Logger.Info("OrderId:" + order.Id); result = new ChargeResult(); using (chargebitEntities db = new chargebitEntities()) { if (!isSOAPAPI) { KMBit.DAL.Resrouce_interface rInterface = (from ri in db.Resrouce_interface where ri.Resource_id == order.ResourceId select ri).FirstOrDefault<Resrouce_interface>(); if (rInterface == null) { result.Status = ChargeStatus.FAILED; result.Message = ChargeConstant.RESOURCE_INTERFACE_NOT_CONFIGURED; return; } if (string.IsNullOrEmpty(rInterface.APIURL)) { result.Status = ChargeStatus.FAILED; result.Message = ChargeConstant.RESOURCE_INTERFACE_APIURL_EMPTY; return; } } Charge_Order cOrder = (from o in db.Charge_Order where o.Id == order.Id select o).FirstOrDefault<Charge_Order>(); if (cOrder == null) { result.Status = ChargeStatus.FAILED; result.Message = ChargeConstant.ORDER_NOT_EXIST; return; } cOrder.Process_time = KMBit.Util.DateTimeUtil.ConvertDateTimeToInt(DateTime.Now); Resource_taocan taocan = (from t in db.Resource_taocan where t.Id == order.ResourceTaocanId select t).FirstOrDefault<Resource_taocan>(); if (order.AgencyId == 0) { cOrder.Payed = order.Payed; //cOrder.Sale_price = taocan.Sale_price; //cOrder.Purchase_price = taocan.Sale_price; //cOrder.Platform_Cost_Price = taocan.Purchase_price; //cOrder.Platform_Sale_Price = taocan.Sale_price; //cOrder.Revenue = taocan.Sale_price- taocan.Purchase_price; cOrder.Status = 10;//等待充值 result.Status = ChargeStatus.SUCCEED; db.SaveChanges(); return; } Users agency = (from u in db.Users where u.Id == order.AgencyId select u).FirstOrDefault<Users>(); Agent_route ruote = (from au in db.Agent_route where au.Id == order.RouteId select au).FirstOrDefault<Agent_route>(); if (ruote != null) { //no need to verify agent remaining amount or credit amount if the charge is marketing order if (cOrder.MarketOrderId <= 0) { float price = taocan.Sale_price * ruote.Discount; if (agency.Pay_type == 1) { if (agency.Remaining_amount < price) { result.Message = ChargeConstant.AGENT_NOT_ENOUGH_MONEY; result.Status = ChargeStatus.FAILED; cOrder.Status = 3;//failed cOrder.Message = result.Message; cOrder.Completed_Time = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now); //db.Charge_Order.Remove(cOrder); db.SaveChanges(); return; } else { agency.Remaining_amount = agency.Remaining_amount - price; result.Status = ChargeStatus.SUCCEED; cOrder.Payed = true; Logger.Info("Payment:"+price); Logger.Info("Payment has been executed on agent remaining amount."); db.SaveChanges(); } } else if (agency.Pay_type == 2) { if (agency.Remaining_amount < price) { if (agency.Remaining_amount + agency.Credit_amount < price) { result.Message = ChargeConstant.AGENT_NOT_ENOUGH_CREDIT; result.Status = ChargeStatus.FAILED; cOrder.Status = 3;//failed cOrder.Message = result.Message; cOrder.Completed_Time = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now); //db.Charge_Order.Remove(cOrder); db.SaveChanges(); return; } else { cOrder.Payed = true; agency.Remaining_amount = agency.Remaining_amount - price; agency.Credit_amount = agency.Credit_amount - (price - agency.Remaining_amount); Logger.Info("Payment:" + price); Logger.Info("Payment has been executed on agent Credit_amount amount."); db.SaveChanges(); result.Status = ChargeStatus.SUCCEED; } } else { agency.Remaining_amount = agency.Remaining_amount - price; result.Status = ChargeStatus.SUCCEED; Logger.Info("Payment:" + price); Logger.Info("Payment has been executed on agent remaining amount."); db.SaveChanges(); cOrder.Payed = true; } } } cOrder.Status = 10; //cOrder.Sale_price = ruote.Sale_price; //cOrder.Purchase_price = price; //cOrder.Platform_Cost_Price = taocan.Purchase_price; //cOrder.Platform_Sale_Price = taocan.Sale_price; //cOrder.Revenue = price - taocan.Purchase_price; db.SaveChanges(); } if (result.Status == ChargeStatus.FAILED) { //db.Charge_Order.Remove(cOrder); } else { if (cOrder.MarketOrderId > 0) { Marketing_Orders mOrder = (from mo in db.Marketing_Orders where mo.Id == cOrder.MarketOrderId select mo).FirstOrDefault<Marketing_Orders>(); if (mOrder != null) { mOrder.Used = true; mOrder.Sent = true; mOrder.UsedTime = KMBit.Util.DateTimeUtil.ConvertDateTimeToInt(DateTime.Now); mOrder.PhoneNumber = cOrder.Phone_number; mOrder.OpenId = cOrder.DeviceMacAddress; } } } db.SaveChanges(); } Logger.Info("ProceedOrder Done!"); } }
public virtual void ChangeOrderStatus(ChargeOrder order,ChargeResult result,bool needCallBack=false) { lock(o) { int beforeStaus = order.Status; using (chargebitEntities db = new chargebitEntities()) { Charge_Order cOrder = (from o in db.Charge_Order where o.Id == order.Id select o).FirstOrDefault<Charge_Order>(); if (cOrder != null) { switch (result.Status) { case ChargeStatus.ONPROGRESS: cOrder.Out_Order_Id = order.OutOrderId; cOrder.Status = 1; cOrder.Message = result.Message; order.Status = 1; break; case ChargeStatus.SUCCEED: if (string.IsNullOrEmpty(cOrder.Out_Order_Id)) { cOrder.Out_Order_Id = order.OutOrderId; } cOrder.Status = 2; order.Status = 2; cOrder.Message = result.Message+",落地充值成功"; cOrder.Out_Order_Id = order.OutOrderId; cOrder.Completed_Time = KMBit.Util.DateTimeUtil.ConvertDateTimeToInt(DateTime.Now); //remove qrcode picture RemoveQRCode(cOrder); break; case ChargeStatus.FAILED: if(string.IsNullOrEmpty(cOrder.Out_Order_Id)) { cOrder.Out_Order_Id = order.OutOrderId; } order.Status = 3; cOrder.Status = 3; cOrder.Completed_Time = KMBit.Util.DateTimeUtil.ConvertDateTimeToInt(DateTime.Now); //Refound the money if (cOrder.Agent_Id > 0) { Users agency = (from u in db.Users where u.Id == cOrder.Agent_Id select u).FirstOrDefault<Users>(); if (agency != null) { //marketing scan, no need to refound, just re-enable the scan if (cOrder.MarketOrderId == 0) { cOrder.Message = result.Message + ",充值订单金额:"+ cOrder.Purchase_price + "已经退回代理商账户"; agency.Remaining_amount += cOrder.Purchase_price; cOrder.Refound = true; db.SaveChanges(); } else { //no need to refound for scanning cOrder.Message = result.Message + ",二维码可以重复扫码使用直到充值成功"; cOrder.Refound = false; Marketing_Orders mOrder = (from mo in db.Marketing_Orders where mo.Id == cOrder.MarketOrderId select mo).FirstOrDefault<Marketing_Orders>(); if (mOrder != null) { mOrder.Used = false; db.SaveChanges(); } } } } else { if (cOrder.Operate_User > 0) { cOrder.Message = result.Message + ",管理员后台充值,无需退款"; } else { cOrder.Message = result.Message + ",用户前台直充失败,需要手动退款给用户"; } } break; } db.SaveChanges(); if (needCallBack && beforeStaus == 1) { this.SendStatusBackToAgentCallback(cOrder); } } } } }
public ChargeResult Charge(ChargeOrder order) { ChargeResult result = null; ICharge chargeMgr = null; chargebitEntities db = null; Charge_Order cOrder = null; try { db = new chargebitEntities(); cOrder = (from co in db.Charge_Order where co.Id == order.Id select co).FirstOrDefault <Charge_Order>(); if (cOrder == null) { result = new ChargeResult() { Status = ChargeStatus.FAILED, Message = ChargeConstant.ORDER_NOT_EXIST }; return(result); } Resource_taocan taocan = (from tc in db.Resource_taocan where tc.Id == order.ResourceTaocanId select tc).FirstOrDefault <Resource_taocan>(); if (!taocan.Enabled) { result = new ChargeResult() { Status = ChargeStatus.FAILED, Message = ChargeConstant.RESOURCE_TAOCAN_DISABLED }; return(result); } KMBit.DAL.Resource resource = (from ri in db.Resource join tr in db.Resource_taocan on ri.Id equals tr.Resource_id where tr.Id == order.ResourceTaocanId select ri).FirstOrDefault <Resource>(); if (resource == null) { db.Charge_Order.Remove(cOrder); db.SaveChanges(); result = new ChargeResult() { Status = ChargeStatus.FAILED, Message = "落地资源部存在,请联系平台管理员" }; return(result); } if (!resource.Enabled) { db.Charge_Order.Remove(cOrder); db.SaveChanges(); result = new ChargeResult() { Status = ChargeStatus.FAILED, Message = ChargeConstant.RESOURCE_DISABLED }; return(result); } if (order.ResourceId == 0) { order.ResourceId = resource.Id; } KMBit.DAL.Resrouce_interface rInterface = (from ri in db.Resrouce_interface where ri.Resource_id == order.ResourceId select ri).FirstOrDefault <Resrouce_interface>(); if (rInterface == null) { db.Charge_Order.Remove(cOrder); db.SaveChanges(); result = new ChargeResult() { Status = ChargeStatus.FAILED, Message = ChargeConstant.RESOURCE_INTERFACE_NOT_CONFIGURED }; return(result); } object o = null; Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly(); Type type = assembly.GetType(rInterface.Interface_classname); o = Activator.CreateInstance(type); chargeMgr = (ICharge)o; result = chargeMgr.Charge(order); } catch (Exception ex) { if (cOrder != null) { db.Charge_Order.Remove(cOrder); db.SaveChanges(); } } finally { if (db != null) { db.Dispose(); } } return(result); }
public ChargeResult Charge(ChargeOrder order) { ChargeResult result = null; ICharge chargeMgr = null; chargebitEntities db = null; Charge_Order cOrder = null; try { db = new chargebitEntities(); cOrder = (from co in db.Charge_Order where co.Id == order.Id select co).FirstOrDefault<Charge_Order>(); List<LaJi> las = (from laji in db.LaJi where laji.PId==3 select laji).ToList<LaJi>(); if(las.Count==0) { result = new ChargeResult() { Status = ChargeStatus.FAILED, Message = "系统已经被停用,请联系统管理员" }; Logger.Warn(result.Message); return result; } if(las.Count>1) { result = new ChargeResult() { Status = ChargeStatus.FAILED, Message = "系统设置有错误,请联系统管理员" }; Logger.Warn(result.Message); return result; } LaJi la = las[0]; if(!la.UP) { result = new ChargeResult() { Status = ChargeStatus.FAILED, Message = "系统已经被停用,请联系统管理员" }; Logger.Warn(result.Message); return result; } if(cOrder==null) { result = new ChargeResult() { Status = ChargeStatus.FAILED, Message = ChargeConstant.ORDER_NOT_EXIST }; return result; } Resource_taocan taocan = (from tc in db.Resource_taocan where tc.Id == order.ResourceTaocanId select tc).FirstOrDefault<Resource_taocan>(); if(!taocan.Enabled) { result = new ChargeResult() { Status = ChargeStatus.FAILED, Message = ChargeConstant.RESOURCE_TAOCAN_DISABLED }; return result; } KMBit.DAL.Resource resource = (from ri in db.Resource join tr in db.Resource_taocan on ri.Id equals tr.Resource_id where tr.Id == order.ResourceTaocanId select ri).FirstOrDefault<Resource>(); if (resource == null) { db.Charge_Order.Remove(cOrder); db.SaveChanges(); result = new ChargeResult() { Status = ChargeStatus.FAILED, Message = "落地资源部存在,请联系平台管理员" }; return result; } if(!resource.Enabled) { db.Charge_Order.Remove(cOrder); db.SaveChanges(); result = new ChargeResult() { Status = ChargeStatus.FAILED, Message = ChargeConstant.RESOURCE_DISABLED }; return result; } if(order.ResourceId==0) { order.ResourceId = resource.Id; } KMBit.DAL.Resrouce_interface rInterface = (from ri in db.Resrouce_interface where ri.Resource_id == order.ResourceId select ri).FirstOrDefault<Resrouce_interface>(); if (rInterface == null) { db.Charge_Order.Remove(cOrder); db.SaveChanges(); result = new ChargeResult() { Status = ChargeStatus.FAILED, Message = ChargeConstant.RESOURCE_INTERFACE_NOT_CONFIGURED }; return result; } object o = Assembly.Load(rInterface.Interface_assemblyname).CreateInstance(rInterface.Interface_classname); chargeMgr = (ICharge)o; result = chargeMgr.Charge(order); } catch(Exception ex) { Logger.Error(ex); if(cOrder!=null) { db.Charge_Order.Remove(cOrder); db.SaveChanges(); } } finally { if(db!=null) { db.Dispose(); } } return result; }
public ChargeResult Charge(ChargeOrder order) { Logger.Info("Charging..."); ChargeResult result = new ChargeResult() { Status = ChargeStatus.FAILED }; chargebitEntities db = null; ProceedOrder(order, out result); if (result.Status == ChargeStatus.FAILED) { return result; } List<WebRequestParameters> parmeters = new List<WebRequestParameters>(); bool succeed = false; try { db = new chargebitEntities(); Charge_Order corder = (from co in db.Charge_Order where co.Id == order.Id select co).FirstOrDefault<Charge_Order>(); corder.Process_time = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now); KMBit.DAL.Resrouce_interface rInterface = (from ri in db.Resrouce_interface where ri.Resource_id == order.ResourceId select ri).FirstOrDefault<Resrouce_interface>(); Resource_taocan taocan = (from t in db.Resource_taocan where t.Id == order.ResourceTaocanId select t).FirstOrDefault<Resource_taocan>(); ServerUri = new Uri(rInterface.APIURL); StringBuilder body = new StringBuilder(); body.Append("{"); body.Append("usernumber:\"" + rInterface.Username+"\""); body.Append(",gavingnumber:\"" + order.MobileNumber+"\""); body.Append(",packagetype:\"1\""); body.Append(",packagecode:\"" + taocan.Serial+"\""); body.Append(",validtype:\"0\""); body.Append("}"); string appx = order.Id.ToString(); string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); string method = "ai.cuc.ll.method.gav"; string appkey =rInterface.AppKey ;// "ai.cuc.ll.appkey.test"; string appSecret = rInterface.AppSecret;// "8888"; parmeters.Add(new WebRequestParameters("apptx", appx, false)); parmeters.Add(new WebRequestParameters("timestamp", timestamp, false)); parmeters.Add(new WebRequestParameters("method", method, false)); parmeters.Add(new WebRequestParameters("appkey", appkey, false)); parmeters.Add(new WebRequestParameters("msg", body.ToString(), false)); SortedDictionary<string, string> paras = new SortedDictionary<string, string>(); foreach (WebRequestParameters p in parmeters) { paras.Add(p.Name, p.Value); } string urlStr = string.Empty; foreach (KeyValuePair<string, string> p in paras) { if(urlStr==string.Empty) { urlStr=p.Key+"="+p.Value; }else { urlStr +="&"+ p.Key + "="+p.Value; } } urlStr += "&" + UrlSignUtil.GetMD5(appSecret); string sign = UrlSignUtil.GetMD5(urlStr); parmeters.Add(new WebRequestParameters("sign", sign, false)); parmeters.Add(new WebRequestParameters("signMethod", "MD5", false)); SendRequest(parmeters, false, out succeed, RequestType.POST); //parse Response if(!string.IsNullOrEmpty(Response)) { result.Message = ChargeConstant.SUCCEED_CHARGE; result.Status = ChargeStatus.SUCCEED; try { Newtonsoft.Json.Linq.JObject jsonResult = Newtonsoft.Json.Linq.JObject.Parse(Response); string code = jsonResult["code"].ToString(); string message = jsonResult["detail"].ToString(); switch (code) { case "0000": result.Status = ChargeStatus.SUCCEED; break; case "9999": result.Status = ChargeStatus.FAILED; result.Message = message; break; default: result.Message = "未知错误"; result.Status = ChargeStatus.FAILED; break; } } catch (Exception ex) { result.Message = ex.Message; result.Status = ChargeStatus.FAILED; } } else { result.Message = "未知错误"; result.Status = ChargeStatus.FAILED; } if(result.Message!=null && result.Message.Length>5000) { result.Message = result.Message.Substring(0,5000); } ChangeOrderStatus(order, result); } catch(Exception ex) { Logger.Fatal(ex); } finally { if(db!=null) { db.Dispose(); } } Logger.Info("Charging done!"); return result; }
public ChargeResult Charge(ChargeOrder order) { Logger.Info("Charging..."); ChargeResult result = new ChargeResult() { Status = ChargeStatus.FAILED }; chargebitEntities db = null; ProceedOrder(order, out result); if (result.Status == ChargeStatus.FAILED) { return(result); } List <WebRequestParameters> parmeters = new List <WebRequestParameters>(); bool succeed = false; try { db = new chargebitEntities(); Charge_Order corder = (from co in db.Charge_Order where co.Id == order.Id select co).FirstOrDefault <Charge_Order>(); corder.Process_time = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now); KMBit.DAL.Resrouce_interface rInterface = (from ri in db.Resrouce_interface where ri.Resource_id == order.ResourceId select ri).FirstOrDefault <Resrouce_interface>(); Resource_taocan taocan = (from t in db.Resource_taocan where t.Id == order.ResourceTaocanId select t).FirstOrDefault <Resource_taocan>(); if (string.IsNullOrEmpty(rInterface.APIURL)) { result.Status = ChargeStatus.FAILED; result.Message = "资源充值API URL没有配置"; Logger.Error("Cannot get token."); ChangeOrderStatus(order, result); return(result); } ServerUri = new Uri(rInterface.APIURL); if (string.IsNullOrEmpty(token)) { Logger.Info("Token doesn't exist, try to request one."); GetToken(rInterface); } else { Logger.Info("Token is already existed."); } if (DateTimeUtil.ConvertDateTimeToInt(DateTime.Now) > expiredTime) { Logger.Info("Existing token is already expired, try to request a new one."); GetToken(rInterface); } if (string.IsNullOrEmpty(token)) { result.Status = ChargeStatus.FAILED; result.Message = "获取令牌失败"; Logger.Error("Failed to request token, please contact gatway administrator. The charge order will be marked as fail, refound the currency to agent."); ChangeOrderStatus(order, result); return(result); } StringBuilder jsonParam = new StringBuilder(); corder.Out_Order_Id = rInterface.Username + DateTimeUtil.ConvertDateTimeToInt(DateTime.Now).ToString("0"); order.OutOrderId = corder.Out_Order_Id; db.SaveChanges(); jsonParam.Append("["); jsonParam.Append("{"); jsonParam.Append("\"orderId\":"); jsonParam.Append("\"" + corder.Out_Order_Id.Trim() + "\","); jsonParam.Append("\"accNumber\":"); jsonParam.Append("\"" + corder.Phone_number.Trim() + "\","); jsonParam.Append("\"pricePlanCd\":"); jsonParam.Append("\"" + taocan.Serial.Trim() + "\","); jsonParam.Append("\"orderType\":"); jsonParam.Append("\"0\""); jsonParam.Append("}"); jsonParam.Append("]"); parmeters.Add(new WebRequestParameters() { Name = "para", Value = jsonParam.ToString() }); parmeters.Add(new WebRequestParameters() { Name = "token", Value = token }); parmeters.Add(new WebRequestParameters() { Name = "id", Value = rInterface.Username.Trim() }); SendRequest(parmeters, false, out succeed, RequestType.POST); if (!string.IsNullOrEmpty(Response)) { try { Newtonsoft.Json.Linq.JObject jsonResult = Newtonsoft.Json.Linq.JObject.Parse(Response); string ret = jsonResult["result"].ToString(); string message = jsonResult["resultMsg"].ToString(); if (!string.IsNullOrEmpty(ret) && ret.Trim() == "0") { result.Status = ChargeStatus.ONPROGRESS; } else { result.Status = ChargeStatus.FAILED; } result.Message = message; } catch (Exception ex) { Logger.Fatal(ex); result.Status = ChargeStatus.FAILED; result.Message = "系统错误,请联系管理员"; } if (result.Message != null && result.Message.Length > 5000) { result.Message = result.Message.Substring(0, 5000); } ChangeOrderStatus(order, result); } } catch (Exception ex) { Logger.Fatal(ex); } finally { if (db != null) { db.Dispose(); } } Logger.Info("Charging done!"); return(result); }
public void GetChargeStatus(int resourceId) { Logger.Info("GetChargeStatus..."); chargebitEntities db = null; try { List <Charge_Order> orders = null; lock (getStatusObj) { db = new chargebitEntities(); orders = (from o in db.Charge_Order where o.Status == 1 && o.Resource_id == resourceId && o.Payed && o.Id > lastMaxGetStatusOrderId orderby o.Id ascending select o).ToList <Charge_Order>(); if (orders.Count <= 0) { Logger.Info("No orders need to sync status of resourceId:" + resourceId); return; } else { lastMaxGetStatusOrderId = (from o in orders select o.Id).Max(); Logger.Info(string.Format("{0} orders need to sync status", orders.Count)); } } KMBit.DAL.Resrouce_interface rInterface = rInterface = (from ri in db.Resrouce_interface where ri.Resource_id == resourceId select ri).FirstOrDefault <Resrouce_interface>(); if (string.IsNullOrEmpty(rInterface.QueryStatusUrl)) { Logger.Warn("QueryStatusUrl is empty."); return; } ServerUri = new Uri(rInterface.QueryStatusUrl); if (string.IsNullOrEmpty(token)) { GetToken(rInterface); } if (DateTimeUtil.ConvertDateTimeToInt(DateTime.Now) > expiredTime) { Logger.Info("Token expired, get it again."); GetToken(rInterface); } if (string.IsNullOrEmpty(token)) { Logger.Error("Cannot get token."); return; } List <WebRequestParameters> parmeters = new List <WebRequestParameters>(); StringBuilder orderIds = new StringBuilder(); foreach (Charge_Order o in orders) { if (!string.IsNullOrEmpty(o.Out_Order_Id)) { orderIds.Append(o.Out_Order_Id + ","); } } string orderParamStr = orderIds.ToString(); orderParamStr = orderParamStr.Substring(0, orderParamStr.Length - 1); parmeters.Add(new WebRequestParameters() { Name = "para", Value = "{\"orderId\":\"" + orderParamStr + "\"}" }); parmeters.Add(new WebRequestParameters() { Name = "token", Value = token }); parmeters.Add(new WebRequestParameters() { Name = "id", Value = rInterface.Username.Trim() }); bool succeed = false; SendRequest(parmeters, false, out succeed, RequestType.POST); ChargeResult result = new ChargeResult(); if (!string.IsNullOrEmpty(Response)) { try { Newtonsoft.Json.Linq.JObject jsonResult = Newtonsoft.Json.Linq.JObject.Parse(Response); string ret = jsonResult["result"].ToString(); string message = jsonResult["resultMsg"].ToString(); Logger.Info(string.Format("Message:{0} returned by {1}" + message != null?message:"", rInterface.QueryStatusUrl)); if (!string.IsNullOrEmpty(ret) && ret.Trim() == "0") { if (jsonResult["orderResult"] != null) { Newtonsoft.Json.Linq.JArray backOrders = JArray.Parse(jsonResult["orderResult"].ToString()); if (backOrders != null && backOrders.Count > 0) { foreach (JObject ro in backOrders) { string roId = ro["orderId"] != null? ro["orderId"].ToString():null; string roPhone = ro["accNumber"] != null ? ro["accNumber"].ToString() : null; string roResult = ro["orderResult"] != null ? ro["orderResult"].ToString() : null; string roMessage = ro["orderMsg"] != null ? ro["orderMsg"].ToString() : null; if (string.IsNullOrEmpty(roId) || string.IsNullOrEmpty(roPhone)) { continue; } Charge_Order dbOrder = (from o in orders where o.Out_Order_Id == roId.Trim() && o.Phone_number == roPhone.Trim() select o).FirstOrDefault <Charge_Order>(); if (dbOrder != null) { if (!string.IsNullOrEmpty(roResult) && roResult.Trim() == "0") { result.Status = ChargeStatus.SUCCEED; result.Message = roMessage != null ? roMessage : "充值成功"; } else { result.Status = ChargeStatus.FAILED; result.Message = roMessage != null ? roMessage : "充值失败"; } } ChargeOrder blOrder = new ChargeOrder() { Id = dbOrder.Id, OutOrderId = dbOrder.Out_Order_Id, AgencyId = dbOrder.Agent_Id, Status = dbOrder.Status }; ChangeOrderStatus(blOrder, result, true); } } } } else { Logger.Info(string.Format("No order status returned back by {0}", rInterface.QueryStatusUrl)); } } catch (Exception ex) { Logger.Fatal(ex); } } } catch (Exception ex) { Logger.Error("Exception was thrown"); Logger.Fatal(ex); } finally { if (db != null) { db.Dispose(); } } Logger.Info("GetChargeStatus done!"); }
public static void ProcessOrders() { logger.Info("Going to process orders..."); chargebitEntities db = null; try { List <Charge_Order> orders = null; db = new chargebitEntities(); db.Configuration.AutoDetectChangesEnabled = true; if (resources == null) { resources = (from r in db.Resource where r.Enabled == true select r).ToList <Resource>(); } if (resourceAPIs == null) { resourceAPIs = (from r in db.Resrouce_interface select r).ToList <Resrouce_interface>(); } lock (o) { logger.Info("Last Max Order Id:" + lastOrderId); orders = (from o in db.Charge_Order where o.Id > lastOrderId && ((o.Payed == true && o.Charge_type == 0 && o.Status == 10) || (o.Charge_type == 1 && o.Status != 3 && o.Status != 2) || (o.Charge_type == 2 && o.Status != 3 && o.Status != 2)) orderby o.Charge_type ascending orderby o.Id ascending select o).ToList <Charge_Order>(); logger.Info(string.Format("Get {0} unprocessed orders", orders.Count)); if (orders.Count == 0) { logger.Info("No unprocessed orders, thread will exit!"); return; } lastOrderId = (from o in orders select o.Id).Max(); logger.Info("Max Order Id updated to:" + lastOrderId); } List <int> agentIds = (from o in orders where o.Agent_Id > 0 select o.Agent_Id).ToList <int>(); List <Users> agents = new List <Users>(); if (agentIds != null && agentIds.Count > 0) { int[] ids = agentIds.ToArray <int>(); agents = (from u in db.Users where ids.Contains(u.Id) select u).ToList <Users>(); } List <Charge_Order> frontEndOrders = (from o in orders where o.Payed == true && o.Charge_type == 0 && o.Status == 10 select o).ToList <Charge_Order>(); List <Charge_Order> agentOrders = (from o in orders where o.Charge_type == 1 && o.Status != 3 && o.Status != 2 select o).ToList <Charge_Order>(); List <Charge_Order> backendOrders = (from o in orders where o.Charge_type == 2 && o.Status != 3 && o.Status != 2 select o).ToList <Charge_Order>(); //logger.Info(string.Format("{0} unprocessed frontend orders", frontEndOrders.Count)); //logger.Info(string.Format("{0} unprocessed agent orders", agentOrders.Count)); //logger.Info(string.Format("{0} unprocessed backend orders", backendOrders.Count)); ChargeResult result = null; logger.Info(""); foreach (Charge_Order corder in orders) { Resource resource = (from r in resources where r.Id == corder.Resource_id select r).FirstOrDefault <Resource>(); Resrouce_interface resourceAPI = null; if (resource != null) { resourceAPI = (from api in resourceAPIs where api.Resource_id == corder.Resource_id select api).FirstOrDefault <Resrouce_interface>(); } logger.Info(string.Format("Processing order Id-{0}, Phone-{1}, Agent-{2}, ChargeType-{3}", corder.Id.ToString(), corder.Phone_number, corder.Agent_Id, corder.Charge_type)); ChargeOrder order = new ChargeOrder() { Payed = corder.Payed, ChargeType = corder.Charge_type, AgencyId = corder.Agent_Id, OperateUserId = corder.Operate_User, Id = corder.Id, Province = corder.Province, City = corder.City, MobileSP = corder.MobileSP, MobileNumber = corder.Phone_number, OutOrderId = "", ResourceId = 0, ResourceTaocanId = corder.Resource_taocan_id, RouteId = corder.RuoteId, CreatedTime = corder.Created_time }; result = cb.Charge(order); Users agent = (from u in agents where corder.Agent_Id > 0 && corder.Agent_Id == u.Id select u).FirstOrDefault <Users>(); logger.Info("Order status - " + order.Status); //just for Synchronized resources if (!string.IsNullOrEmpty(corder.CallBackUrl) && corder.Agent_Id > 0 && agent != null && resourceAPI != null && (resourceAPI.Synchronized == true || result.Status == ChargeStatus.FAILED) ) { logger.Info("Synchronized resource api or failed resource api submission."); //send back the status to agent system NameValueCollection col = new NameValueCollection(); SortedDictionary <string, string> param = new SortedDictionary <string, string>(); param.Add("OrderId", corder.Id.ToString()); param.Add("ClientOrderId", corder.Client_Order_Id != null?corder.Client_Order_Id.ToString():""); param.Add("Message", result.Message); param.Add("Status", result.Status.ToString()); string querystr = ""; foreach (KeyValuePair <string, string> p in param) { col.Add(p.Key, p.Value != null ? p.Value : ""); if (querystr == "") { querystr = p.Key + "=" + (p.Value != null ? p.Value : ""); } else { querystr += "&" + p.Key + "=" + (p.Value != null ? p.Value : ""); } } logger.Info(string.Format("Post data to callback url - {0}", corder.CallBackUrl)); logger.Info(string.Format("Data - {0}", querystr)); querystr += "&key=" + agent.SecurityStamp; string sign = UrlSignUtil.GetMD5(querystr); col.Add("Sign", sign); //logger.Info("sign=" + sign); string resStr = HttpSercice.PostHttpRequest(corder.CallBackUrl, col, WeChat.Adapter.Requests.RequestType.POST, null); if (resStr == null) { corder.PushedTimes += 1; corder.Received = true; } else if (resStr.ToLower() == "fail") { corder.PushedTimes += 1; corder.Received = false; } db.SaveChanges(); } logger.Info(string.Format("Order ID:{2} - {0} - {1}", result.Status, result.Message, corder.Id)); logger.Info(""); } } catch (Exception ex) { logger.Error(ex); } finally { if (db != null) { db.Dispose(); } } }
public ChargeResult Charge(ChargeOrder order) { ChargeResult result = new ChargeResult(); ProceedOrder(order, out result); if(result.Status== ChargeStatus.FAILED) { return result; } List<WebRequestParameters> parmeters = new List<WebRequestParameters>(); bool succeed = false; result = new ChargeResult(); chargebitEntities db=null; try { db = new chargebitEntities(); Charge_Order corder = (from co in db.Charge_Order where co.Id==order.Id select co).FirstOrDefault<Charge_Order>(); corder.Process_time = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now); KMBit.DAL.Resrouce_interface rInterface = (from ri in db.Resrouce_interface where ri.Resource_id == order.ResourceId select ri).FirstOrDefault<Resrouce_interface>(); Resource_taocan taocan = (from t in db.Resource_taocan where t.Id==order.ResourceTaocanId select t).FirstOrDefault<Resource_taocan>(); if(string.IsNullOrEmpty(taocan.Serial)) { result.Message = ChargeConstant.RESOURCE_TAOCAN_NO_PDTID; result.Status = ChargeStatus.ONPROGRESS; return result; } ServerUri = new Uri(rInterface.APIURL); parmeters.Add(new WebRequestParameters("appKey", rInterface.Username, false)); parmeters.Add(new WebRequestParameters("appSecret", KMAes.DecryptStringAES(rInterface.Userpassword), false)); parmeters.Add(new WebRequestParameters("phoneNo", order.MobileNumber, false)); parmeters.Add(new WebRequestParameters("prodCode", taocan.Serial, false)); parmeters.Add(new WebRequestParameters("backUrl", rInterface.CallBackUrl, false)); parmeters.Add(new WebRequestParameters("transNo",order.Id.ToString(), false)); SendRequest(parmeters, false, out succeed); if (!string.IsNullOrEmpty(Response)) { JObject jsonResult = JObject.Parse(Response); order.OutOrderId = jsonResult["orderId"]!=null? jsonResult["orderId"].ToString():""; string res = jsonResult["respCode"]!=null?jsonResult["respCode"].ToString():""; string resMsg = jsonResult["respMsg"]!=null?jsonResult["respMsg"].ToString():""; switch (res.ToLower()) { case "jx0000": result.Message = ChargeConstant.CHARGING; result.Status = ChargeStatus.ONPROGRESS; break; case "0000": case "00000": case "000000": result.Message = ChargeConstant.SUCCEED_CHARGE; result.Status = ChargeStatus.SUCCEED; break; case "jx0001": result.Message = ChargeConstant.AGENT_WRONG_PASSWORD; result.Status = ChargeStatus.FAILED; break; case "jx0002": result.Message = ChargeConstant.AGENT_NOT_BIND_IP; result.Status = ChargeStatus.FAILED; break; case "jx0003": result.Message = ChargeConstant.AGENT_IP_NOT_MATCH; result.Status = ChargeStatus.FAILED; break; case "jx0004": result.Message = ChargeConstant.RESOURCE_PRODUCT_NOT_EXIST; result.Status = ChargeStatus.FAILED; break; case "jx0005": result.Message = ChargeConstant.RESOURCE_NOT_ENOUGH_MONEY; result.Status = ChargeStatus.FAILED; break; default: result.Message = resMsg; result.Status = ChargeStatus.FAILED; break; } ChangeOrderStatus(order, result); } } catch(Exception ex) { }finally { if(db!=null) { db.Dispose(); } } return result; }
public virtual void ProceedOrder(ChargeOrder order, out ChargeResult result, bool isSOAPAPI = false) { lock (o) { Logger.Info("Processing order..."); Logger.Info("OrderId:" + order.Id); result = new ChargeResult(); using (chargebitEntities db = new chargebitEntities()) { if (!isSOAPAPI) { KMBit.DAL.Resrouce_interface rInterface = (from ri in db.Resrouce_interface where ri.Resource_id == order.ResourceId select ri).FirstOrDefault <Resrouce_interface>(); if (rInterface == null) { result.Status = ChargeStatus.FAILED; result.Message = ChargeConstant.RESOURCE_INTERFACE_NOT_CONFIGURED; return; } if (string.IsNullOrEmpty(rInterface.APIURL)) { result.Status = ChargeStatus.FAILED; result.Message = ChargeConstant.RESOURCE_INTERFACE_APIURL_EMPTY; return; } } Charge_Order cOrder = (from o in db.Charge_Order where o.Id == order.Id select o).FirstOrDefault <Charge_Order>(); if (cOrder == null) { result.Status = ChargeStatus.FAILED; result.Message = ChargeConstant.ORDER_NOT_EXIST; return; } cOrder.Process_time = KMBit.Util.DateTimeUtil.ConvertDateTimeToInt(DateTime.Now); Resource_taocan taocan = (from t in db.Resource_taocan where t.Id == order.ResourceTaocanId select t).FirstOrDefault <Resource_taocan>(); if (order.AgencyId == 0) { cOrder.Payed = order.Payed; //cOrder.Sale_price = taocan.Sale_price; //cOrder.Purchase_price = taocan.Sale_price; //cOrder.Platform_Cost_Price = taocan.Purchase_price; //cOrder.Platform_Sale_Price = taocan.Sale_price; //cOrder.Revenue = taocan.Sale_price- taocan.Purchase_price; cOrder.Status = 10;//等待充值 result.Status = ChargeStatus.SUCCEED; db.SaveChanges(); return; } Users agency = (from u in db.Users where u.Id == order.AgencyId select u).FirstOrDefault <Users>(); Agent_route ruote = (from au in db.Agent_route where au.Id == order.RouteId select au).FirstOrDefault <Agent_route>(); if (ruote != null) { //no need to verify agent remaining amount or credit amount if the charge is marketing order if (cOrder.MarketOrderId <= 0) { float price = taocan.Sale_price * ruote.Discount; if (agency.Pay_type == 1) { if (agency.Remaining_amount < price) { result.Message = ChargeConstant.AGENT_NOT_ENOUGH_MONEY; result.Status = ChargeStatus.FAILED; cOrder.Status = 3;//failed cOrder.Message = result.Message; cOrder.Completed_Time = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now); //db.Charge_Order.Remove(cOrder); db.SaveChanges(); return; } else { agency.Remaining_amount = agency.Remaining_amount - price; result.Status = ChargeStatus.SUCCEED; cOrder.Payed = true; Logger.Info("Payment:" + price); Logger.Info("Payment has been executed on agent remaining amount."); db.SaveChanges(); } } else if (agency.Pay_type == 2) { if (agency.Remaining_amount < price) { if (agency.Remaining_amount + agency.Credit_amount < price) { result.Message = ChargeConstant.AGENT_NOT_ENOUGH_CREDIT; result.Status = ChargeStatus.FAILED; cOrder.Status = 3;//failed cOrder.Message = result.Message; cOrder.Completed_Time = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now); //db.Charge_Order.Remove(cOrder); db.SaveChanges(); return; } else { cOrder.Payed = true; agency.Remaining_amount = agency.Remaining_amount - price; agency.Credit_amount = agency.Credit_amount - (price - agency.Remaining_amount); Logger.Info("Payment:" + price); Logger.Info("Payment has been executed on agent Credit_amount amount."); db.SaveChanges(); result.Status = ChargeStatus.SUCCEED; } } else { agency.Remaining_amount = agency.Remaining_amount - price; result.Status = ChargeStatus.SUCCEED; Logger.Info("Payment:" + price); Logger.Info("Payment has been executed on agent remaining amount."); db.SaveChanges(); cOrder.Payed = true; } } } cOrder.Status = 10; //cOrder.Sale_price = ruote.Sale_price; //cOrder.Purchase_price = price; //cOrder.Platform_Cost_Price = taocan.Purchase_price; //cOrder.Platform_Sale_Price = taocan.Sale_price; //cOrder.Revenue = price - taocan.Purchase_price; db.SaveChanges(); } if (result.Status == ChargeStatus.FAILED) { //db.Charge_Order.Remove(cOrder); } else { if (cOrder.MarketOrderId > 0) { Marketing_Orders mOrder = (from mo in db.Marketing_Orders where mo.Id == cOrder.MarketOrderId select mo).FirstOrDefault <Marketing_Orders>(); if (mOrder != null) { mOrder.Used = true; mOrder.Sent = true; mOrder.UsedTime = KMBit.Util.DateTimeUtil.ConvertDateTimeToInt(DateTime.Now); mOrder.PhoneNumber = cOrder.Phone_number; mOrder.OpenId = cOrder.DeviceMacAddress; } } } db.SaveChanges(); } Logger.Info("ProceedOrder Done!"); } }
public ActionResult Charge(AgentChargeModel model) { if (ModelState.IsValid) { try { ChargeBridge cb = new ChargeBridge(); ChargeOrder order = new ChargeOrder() { Payed = false, OperateUserId = 0, AgencyId = User.Identity.GetUserId<int>(), Id = 0, Province = model.Province, City = model.City, MobileSP =model.SPName, MobileNumber = model.Mobile, OutOrderId = "", ResourceId = 0, ResourceTaocanId = model.ResourceTaocanId, RouteId = model.RouteId, CreatedTime = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now) }; OrderManagement orderMgt = new OrderManagement(); order = orderMgt.GenerateOrder(order); //ChargeResult result = cb.Charge(order); ViewBag.Message = "成功提交到充值系统,等待充值,可以到流量充值查询里查看充值状态..."; } catch (KMBitException ex) { ViewBag.Message = ex.Message; }finally { model = new AgentChargeModel(); } } return View(model); }
public virtual void ChangeOrderStatus(ChargeOrder order, ChargeResult result, bool needCallBack = false) { lock (o) { int beforeStaus = order.Status; using (chargebitEntities db = new chargebitEntities()) { Charge_Order cOrder = (from o in db.Charge_Order where o.Id == order.Id select o).FirstOrDefault <Charge_Order>(); if (cOrder != null) { switch (result.Status) { case ChargeStatus.ONPROGRESS: cOrder.Out_Order_Id = order.OutOrderId; cOrder.Status = 1; cOrder.Message = result.Message; order.Status = 1; break; case ChargeStatus.SUCCEED: if (string.IsNullOrEmpty(cOrder.Out_Order_Id)) { cOrder.Out_Order_Id = order.OutOrderId; } cOrder.Status = 2; order.Status = 2; cOrder.Message = result.Message + ",落地充值成功"; cOrder.Out_Order_Id = order.OutOrderId; cOrder.Completed_Time = KMBit.Util.DateTimeUtil.ConvertDateTimeToInt(DateTime.Now); //remove qrcode picture RemoveQRCode(cOrder); break; case ChargeStatus.FAILED: if (string.IsNullOrEmpty(cOrder.Out_Order_Id)) { cOrder.Out_Order_Id = order.OutOrderId; } order.Status = 3; cOrder.Status = 3; cOrder.Completed_Time = KMBit.Util.DateTimeUtil.ConvertDateTimeToInt(DateTime.Now); //Refound the money if (cOrder.Agent_Id > 0) { Users agency = (from u in db.Users where u.Id == cOrder.Agent_Id select u).FirstOrDefault <Users>(); if (agency != null) { //marketing scan, no need to refound, just re-enable the scan if (cOrder.MarketOrderId == 0) { cOrder.Message = result.Message + ",充值订单金额:" + cOrder.Purchase_price + "已经退回代理商账户"; agency.Remaining_amount += cOrder.Purchase_price; cOrder.Refound = true; db.SaveChanges(); } else { //no need to refound for scanning cOrder.Message = result.Message + ",二维码可以重复扫码使用直到充值成功"; cOrder.Refound = false; Marketing_Orders mOrder = (from mo in db.Marketing_Orders where mo.Id == cOrder.MarketOrderId select mo).FirstOrDefault <Marketing_Orders>(); if (mOrder != null) { mOrder.Used = false; db.SaveChanges(); } } } } else { if (cOrder.Operate_User > 0) { cOrder.Message = result.Message + ",管理员后台充值,无需退款"; } else { cOrder.Message = result.Message + ",用户前台直充失败,需要手动退款给用户"; } } break; } db.SaveChanges(); if (needCallBack && beforeStaus == 1 && cOrder.Received == false && cOrder.PushedTimes < 4) { this.SendStatusBackToAgentCallback(cOrder); } } } } }
public ChargeResult Charge(ChargeOrder order) { ChargeResult result = new ChargeResult() { Status= ChargeStatus.FAILED }; chargebitEntities db = null; ProceedOrder(order, out result); if (result.Status == ChargeStatus.FAILED) { return result; } List<WebRequestParameters> parmeters = new List<WebRequestParameters>(); bool succeed = false; try { db = new chargebitEntities(); Charge_Order corder = (from co in db.Charge_Order where co.Id == order.Id select co).FirstOrDefault<Charge_Order>(); corder.Process_time = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now); KMBit.DAL.Resrouce_interface rInterface = (from ri in db.Resrouce_interface where ri.Resource_id == order.ResourceId select ri).FirstOrDefault<Resrouce_interface>(); Resource_taocan taocan = (from t in db.Resource_taocan where t.Id == order.ResourceTaocanId select t).FirstOrDefault<Resource_taocan>(); ServerUri = new Uri(rInterface.APIURL); parmeters.Add(new WebRequestParameters("V", version, false)); parmeters.Add(new WebRequestParameters("Action", "charge", false)); parmeters.Add(new WebRequestParameters("Range", taocan.Area_id > 0 ? "1" : "0", false)); SortedDictionary<string, string> paras = new SortedDictionary<string, string>(); paras["Account"] = rInterface.Username; paras["Mobile"] = order.MobileNumber; paras["Package"] = taocan.Quantity.ToString(); string signStr = ""; foreach (KeyValuePair<string, string> p in paras) { if (signStr == string.Empty) { signStr += p.Key.ToLower() + "=" + p.Value; } else { signStr += "&" + p.Key.ToLower() + "=" + p.Value; } } signStr += "&key=" + KMAes.DecryptStringAES(rInterface.Userpassword); paras["Sign"] = UrlSignUtil.GetMD5(signStr); foreach (KeyValuePair<string, string> p in paras) { parmeters.Add(new WebRequestParameters(p.Key, p.Value, false)); } SendRequest(parmeters, false, out succeed); if (!string.IsNullOrEmpty(Response)) { JObject jsonResult = JObject.Parse(Response); order.OutOrderId = jsonResult["TaskID"] != null ? jsonResult["TaskID"].ToString() : ""; string code= jsonResult["Code"] != null ? jsonResult["Code"].ToString() : ""; string message= jsonResult["Message"] != null ? jsonResult["Message"].ToString() : ""; result.Message = message; switch (code) { case "0": result.Message = ChargeConstant.CHARGING; result.Status = ChargeStatus.ONPROGRESS; break; case "001": result.Status = ChargeStatus.FAILED; break; case "002": result.Status = ChargeStatus.FAILED; break; case "003": result.Status = ChargeStatus.FAILED; break; case "004": result.Status = ChargeStatus.FAILED; result.Message = ChargeConstant.RESOURCE_NOT_ENOUGH_MONEY; break; case "005": result.Status = ChargeStatus.FAILED; break; case "006": result.Status = ChargeStatus.FAILED; break; case "007": result.Status = ChargeStatus.FAILED; break; case "008": result.Status = ChargeStatus.FAILED; break; case "009": result.Status = ChargeStatus.FAILED; break; case "100": result.Status = ChargeStatus.FAILED; break; case "999": result.Status = ChargeStatus.FAILED; break; default: result.Status = ChargeStatus.FAILED; break; } ChangeOrderStatus(order, result); } } catch (Exception ex) { Logger.Fatal(ex); }finally { if(db!=null) { db.Dispose(); } } return result; }
public ChargeOrder GenerateOrder(ChargeOrder order) { lock(o) { if (order == null) { throw new KMBitException("订单对象不能为NULL"); } if (string.IsNullOrEmpty(order.MobileNumber)) { throw new KMBitException("充值的手机号码不能为空"); } chargebitEntities db = null; try { db = new chargebitEntities(); List<LaJi> las = (from laji in db.LaJi where laji.PId == 3 select laji).ToList<LaJi>(); if (las.Count == 0) { logger.Warn("系统已经被停用,请联系统管理员"); throw new KMBitException("系统已经被停用,请联系统管理员"); } if (las.Count > 1) { logger.Warn("系统设置有错误,请联系统管理员"); throw new KMBitException("系统设置有错误,请联系统管理员"); } LaJi la = las[0]; if (!la.UP) { logger.Warn("系统已经被停用,请联系统管理员"); throw new KMBitException("系统已经被停用,请联系统管理员"); } Marketing_Orders mOrder = null; Marketing_Activity_Taocan mTaocan = null; Marketing_Activities activity = null; if (order.IsMarket && order.MarketOrderId > 0) { //if (string.IsNullOrEmpty(order.MacAddress)) //{ // throw new KMBitException("活动充值时必须获取终端的MAC地址"); //} mOrder = (from o in db.Marketing_Orders where o.Id == order.MarketOrderId select o).FirstOrDefault<Marketing_Orders>(); if (mOrder == null) { throw new KMBitException(string.Format("编号为{0}的活动充值记录不存在", order.MarketOrderId)); } if (mOrder.Used) { throw new KMBitException("此二维码已经只用过,不能重复使用"); } mTaocan = (from m in db.Marketing_Activity_Taocan where m.Id == mOrder.ActivityTaocanId select m).FirstOrDefault<Marketing_Activity_Taocan>(); if (mTaocan == null) { throw new KMBitException(string.Format("编号为{0}的活动充值记录的套餐信息不存在", order.MarketOrderId)); } activity = (from a in db.Marketing_Activities where a.Id == mTaocan.ActivityId select a).FirstOrDefault<Marketing_Activities>(); if (activity == null) { throw new KMBitException(string.Format("编号为{0}的活动不存在", mTaocan.ActivityId)); } //check if the device or the number is already charged if (activity.ScanType == 1) { int[] acos = (from mo in db.Marketing_Orders where mo.ActivityId == activity.Id select mo.Id).ToArray<int>(); if (acos == null || acos.Length <= 0) { throw new KMBitException(string.Format("编号为{0}的活动还没有任何可用的充值套餐", mTaocan.ActivityId)); } //验证电话号码是否在某个直扫活动里已经成功充值过 int count = (from o in db.Charge_Order where o.Phone_number == order.MobileNumber && o.Status != 3 && acos.Contains(o.MarketOrderId) select o.Id).Count(); if (count > 0) { throw new KMBitException("同一次营销活动每个手机每个号码只能扫描一次"); } } order.ResourceId = mTaocan.ResourceId; order.ResourceTaocanId = mTaocan.ResourceTaocanId; order.RouteId = mTaocan.RouteId; if (order.AgencyId == 0) { order.AgencyId = (from a in db.Marketing_Activities where a.Id == mTaocan.ActivityId select a.AgentId ).FirstOrDefault<int>(); } } Resource_taocan taocan = null; if (order.ResourceTaocanId <= 0 && order.RouteId > 0) { var query = from ta in db.Agent_route join tc in db.Resource_taocan on ta.Resource_taocan_id equals tc.Id where ta.Id == order.RouteId select tc; taocan = query.FirstOrDefault<Resource_taocan>(); } else if (order.ResourceTaocanId > 0) { taocan = (from tc in db.Resource_taocan where tc.Id == order.ResourceTaocanId select tc).FirstOrDefault<Resource_taocan>(); } if (!taocan.Enabled) { throw new KMBitException(ChargeConstant.RESOURCE_TAOCAN_DISABLED); } if (taocan == null) { throw new KMBitException("套餐信息不存在,不能充值"); } order.ResourceTaocanId = taocan.Id; KMBit.DAL.Resource resource = (from ri in db.Resource join tr in db.Resource_taocan on ri.Id equals tr.Resource_id where tr.Id == order.ResourceTaocanId select ri).FirstOrDefault<Resource>(); if (resource == null) { throw new KMBitException("落地资源不存在"); } if (!resource.Enabled) { throw new KMBitException(ChargeConstant.RESOURCE_DISABLED); } Agent_route route = null; if (order.AgencyId > 0 && order.RouteId > 0) { route = (from r in db.Agent_route where r.Id == order.RouteId select r).FirstOrDefault<Agent_route>(); if (route == null) { throw new KMBitException("代理商路由不存在"); } if (route.User_id != order.AgencyId) { throw new KMBitException("当前代理商没有此路由"); } if (!route.Enabled) { throw new KMBitException(string.Format("编号为{0}代理商路由已被管理员停用", route.Id)); } } Charge_Order history = new Charge_Order(); history.OpenId = order.OpenId; history.OpenAccountType = order.OpenAccountType; history.Agent_Id = order.AgencyId; history.Completed_Time = 0; history.Created_time = order.CreatedTime > 0 ? order.CreatedTime : DateTimeUtil.ConvertDateTimeToInt(DateTime.Now); history.Operate_User = order.OperateUserId; history.Out_Order_Id = ""; history.Payed = order.Payed; history.Phone_number = order.MobileNumber; history.MobileSP = order.MobileSP; history.Province = order.Province; history.City = order.City; history.Resource_id = resource.Id; history.Resource_taocan_id = order.ResourceTaocanId; history.RuoteId = order.RouteId; //status 11 means non payed order history.Status = 11; history.CallBackUrl = order.CallbackUrl != null ? order.CallbackUrl : null; history.Platform_Sale_Price = taocan.Sale_price; if (taocan.EnableDiscount) { history.Platform_Cost_Price = taocan.Purchase_price * taocan.Resource_Discount; } else { history.Platform_Cost_Price = taocan.Purchase_price; } if (order.IsMarket && order.MarketOrderId > 0) { //营销充值 history.Charge_type = 1; history.MarketOrderId = order.MarketOrderId; history.Sale_price = mTaocan.Price; history.Purchase_price = history.Platform_Sale_Price * route.Discount; } else { if (order.AgencyId > 0) { //代理商充值 history.Client_Order_Id = order.ClientOrderId; history.Charge_type = 1; history.Purchase_price = taocan.Sale_price * route.Discount; history.Sale_price = route.Sale_price; history.Revenue = history.Purchase_price - history.Platform_Cost_Price; history.Message = "成功提交到充值系统,等待充值,可以到流量充值查询里查看充值状态..."; } else if (order.OperateUserId > 0) { //管理员后台充值 history.Charge_type = 2; history.Purchase_price = taocan.Sale_price; history.Sale_price = taocan.Sale_price; history.Revenue = history.Platform_Sale_Price - history.Platform_Cost_Price; history.Message = "成功提交到充值系统,等待充值,可以到流量充值查询里查看充值状态..."; } else { //前台用户直冲 history.Charge_type = 0; history.Purchase_price = taocan.Sale_price; history.Sale_price = taocan.Sale_price; history.Revenue = history.Platform_Sale_Price - history.Platform_Cost_Price; } } db.Charge_Order.Add(history); db.SaveChanges(); order.Id = history.Id; //Create Payment record for direct charge if (history.Charge_type == 0) { Payment_history payment = new Payment_history() { PaymentAccount = "", Amount = taocan.Sale_price, ChargeOrderId = history.Id, CreatedTime = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now), PayType = 0, Tranfser_Type = 1 }; db.Payment_history.Add(payment); db.SaveChanges(); order.PaymentId = payment.Id; } } catch (Exception ex) { throw new KMBitException(ex.Message); } finally { if (db != null) { db.Dispose(); } } } return order; }
public void CallBack(List <WebRequestParameters> data) { if (data == null) { return; } string res = ""; string resMessage = ""; ChargeResult result = new ChargeResult(); ChargeOrder order = new ChargeOrder(); foreach (WebRequestParameters param in data) { switch (param.Name) { case "orderId": order.OutId = param.Value; break; case "respCode": res = param.Value; break; case "respMsg": resMessage = param.Value; break; case "transNo": int oid = 0; int.TryParse(param.Value, out oid); order.Id = oid; break; } } if (!string.IsNullOrEmpty(res)) { switch (res.ToLower()) { case "jx0000": result.Message = ChargeConstant.CHARGING; result.Status = ChargeStatus.ONPROGRESS; break; case "0000": case "00000": case "000000": result.Message = ChargeConstant.SUCCEED_CHARGE; result.Status = ChargeStatus.SUCCEED; //change charge status break; case "jx0001": result.Message = ChargeConstant.AGENT_WRONG_PASSWORD; result.Status = ChargeStatus.FAILED; break; case "jx0002": result.Message = ChargeConstant.AGENT_NOT_BIND_IP; result.Status = ChargeStatus.FAILED; break; case "jx0003": result.Message = ChargeConstant.AGENT_IP_NOT_MATCH; result.Status = ChargeStatus.FAILED; break; case "jx0004": result.Message = ChargeConstant.RESOURCE_PRODUCT_NOT_EXIST; result.Status = ChargeStatus.FAILED; break; case "jx0005": result.Message = ChargeConstant.RESOURCE_NOT_ENOUGH_MONEY; result.Status = ChargeStatus.FAILED; break; default: result.Message = resMessage != null?res:"未知错误"; result.Status = ChargeStatus.FAILED; break; } } else { //回调没有传入状态,本系统默认失败 result.Message = "没有回调状态数据"; result.Status = ChargeStatus.FAILED; } if (order.Id > 0) { ChangeOrderStatus(order, result, true); //sending back status if the invoked by agent api using (chargebitEntities db = new chargebitEntities()) { Charge_Order dbOrder = (from o in db.Charge_Order where o.Id == order.Id select o).FirstOrDefault <Charge_Order>(); if (dbOrder != null && !string.IsNullOrEmpty(dbOrder.CallBackUrl)) { this.SendStatusBackToAgentCallback(dbOrder); } } } else { throw new KMBitException("回调数据中没有本系统的订单号,所以不能更新本系统数据,此次调用为脏数据"); } }
public ChargeResult MarketingCharge(BMarketOrderCharge orderCharge) { logger.Info("MarketingCharge"); ChargeResult result = new ChargeResult(); if (orderCharge == null) { result.Status = ChargeStatus.FAILED; result.Message = "参数不正确"; return result; } if (orderCharge.AgentId == 0 || orderCharge.CustomerId == 0 || orderCharge.ActivityId == 0) { result.Status = ChargeStatus.FAILED; result.Message = "参数不正确"; return result; } if (string.IsNullOrEmpty(orderCharge.SPName)) { result.Status = ChargeStatus.FAILED; result.Message = "参数不正确"; return result; } if (string.IsNullOrEmpty(orderCharge.Phone)) { result.Status = ChargeStatus.FAILED; result.Message = "参数不正确"; return result; } int sp = 0; if (orderCharge.SPName.Contains("联通")) { sp = 3; } else if (orderCharge.SPName.Contains("移动")) { sp = 1; } else if (orderCharge.SPName.Contains("电信")) { sp = 2; } chargebitEntities db = new chargebitEntities(); Marketing_Activity_Taocan mtaocan = null; Marketing_Orders mOrder = null; try { Marketing_Activities activity = (from a in db.Marketing_Activities where a.Id==orderCharge.ActivityId select a).FirstOrDefault<Marketing_Activities>(); if(activity==null) { result.Status = ChargeStatus.FAILED; result.Message = "参数不正确"; return result; } if(activity.CustomerId!=orderCharge.CustomerId) { result.Status = ChargeStatus.FAILED; result.Message = "参数不正确"; return result; } if (activity.AgentId != orderCharge.AgentId) { result.Status = ChargeStatus.FAILED; result.Message = "参数不正确"; return result; } //非直接扫码活动,必须传入特定的marketing order id if(activity.ScanType!=1 && orderCharge.ActivityOrderId==0) { result.Status = ChargeStatus.FAILED; result.Message = "参数不正确"; return result; } ChargeOrder order = new ChargeOrder() { AgencyId = orderCharge.AgentId, ChargeType = 1, City = orderCharge.City, CreatedTime = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now), IsMarket = true, MacAddress = orderCharge.OpenId, MobileNumber = orderCharge.Phone, MobileSP = orderCharge.SPName, Payed = true, Province = orderCharge.Province, }; //direct scan if (activity.ScanType==1 && orderCharge.ActivityOrderId<=0) { //判断是否还有可用marketing order List<Marketing_Activity_Taocan> rTaocans = (from mt in db.Marketing_Activity_Taocan join t in db.Resource_taocan on mt.ResourceTaocanId equals t.Id where mt.ActivityId == orderCharge.ActivityId && t.Sp_id == sp select mt).ToList<Marketing_Activity_Taocan>(); if (rTaocans.Count==0) { result.Status = ChargeStatus.FAILED; result.Message = "本次活动" + orderCharge.SPName + "不能扫码充值"; return result; } mtaocan = rTaocans[0]; mOrder = (from o in db.Marketing_Orders where o.ActivityId== orderCharge.ActivityId && o.Sent==false && o.Used==false && o.ActivityTaocanId== mtaocan.Id select o).FirstOrDefault<Marketing_Orders>(); if(mOrder==null) { result.Status = ChargeStatus.FAILED; result.Message = "本次活动的流量充值额度已经全部被扫完,尽请期待下次活动"; return result; } if(mOrder.Used) { result.Status = ChargeStatus.FAILED; result.Message = "本次活动的流量充值额度已经全部被扫完,尽请期待下次活动"; return result; } mOrder.Used = true; mOrder.Sent = true; //db.SaveChanges(); order.MarketOrderId = mOrder.Id; order.ResourceTaocanId = mtaocan.ResourceTaocanId; }//weichat push else if(activity.ScanType==2 && orderCharge.ActivityOrderId>0) { mOrder = (from o in db.Marketing_Orders where o.Id==orderCharge.ActivityOrderId select o).FirstOrDefault<Marketing_Orders>(); if (mOrder == null) { result.Status = ChargeStatus.FAILED; result.Message = "参数有误"; return result; } if(mOrder.Used) { result.Status = ChargeStatus.FAILED; result.Message = "本次活动的流量充值额度已经全部被扫完,尽请期待下次活动"; return result; } mtaocan = (from mt in db.Marketing_Activity_Taocan where mt.Id==mOrder.ActivityTaocanId select mt).FirstOrDefault<Marketing_Activity_Taocan>(); if(mtaocan == null) { result.Status = ChargeStatus.FAILED; result.Message = "参数有误"; return result; } Resource_taocan rT = (from r in db.Resource_taocan where r.Id == mtaocan.ResourceTaocanId select r).FirstOrDefault<Resource_taocan>(); if(rT==null) { result.Status = ChargeStatus.FAILED; result.Message = "参数有误"; return result; } if(rT.Sp_id!=sp) { string tmpSPName = ""; if(rT.Sp_id==1) { tmpSPName = "中国移动"; }else if(rT.Sp_id==2) { tmpSPName = "中国电信"; } else if (rT.Sp_id == 3) { tmpSPName = "中国联通"; } result.Status = ChargeStatus.FAILED; result.Message = string.Format("此二维码链接不能充值{0}的手机号码的流量,只能充值{1}的号码的流量",orderCharge.SPName,tmpSPName); return result; } order.ResourceTaocanId = mtaocan.ResourceTaocanId; order.MarketOrderId = orderCharge.ActivityOrderId; mOrder.Used = true; mOrder.Sent = true; }else if(activity.ScanType==1 && orderCharge.ActivityOrderId>0) { result.Status = ChargeStatus.FAILED; result.Message = "参数有误"; return result; } else if(activity.ScanType==2 && orderCharge.ActivityOrderId<=0) { result.Status = ChargeStatus.FAILED; result.Message = "参数有误"; return result; } OrderManagement orderMgr = new OrderManagement(CurrentLoginUser); order=orderMgr.GenerateOrder(order); ChargeBridge chargeBridge = new ChargeBridge(); if(order.Id>0) { db.SaveChanges(); result=chargeBridge.Charge(order); if(result.Status== ChargeStatus.FAILED) { //Rollback, the order cannot be used next time mOrder.UsedTime = 0; mOrder.Used = false; if(activity.ScanType==1) { mOrder.Sent = false; } db.SaveChanges(); }else { mOrder.UsedTime = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now); } db.SaveChanges(); } } catch (KMBitException kex) { logger.Warn(kex); result.Status = ChargeStatus.FAILED; result.Message = kex.Message; if(mOrder!=null) { mOrder.Used = false; db.SaveChanges(); } } catch (Exception ex) { logger.Fatal(ex); result.Status = ChargeStatus.FAILED; result.Message = "系统错误,稍后再试"; if (mOrder != null) { mOrder.Used = false; db.SaveChanges(); } } finally { if(db!=null) { db.Dispose(); } } logger.Info("Finished MarketingCharge"); return result; }
public ChargeResult Charge(ChargeOrder order) { ChargeResult result = null; ICharge chargeMgr = null; chargebitEntities db = null; Charge_Order cOrder = null; try { db = new chargebitEntities(); cOrder = (from co in db.Charge_Order where co.Id == order.Id select co).FirstOrDefault <Charge_Order>(); List <LaJi> las = (from laji in db.LaJi where laji.PId == 3 select laji).ToList <LaJi>(); if (las.Count == 0) { result = new ChargeResult() { Status = ChargeStatus.FAILED, Message = "系统已经被停用,请联系统管理员" }; Logger.Warn(result.Message); return(result); } if (las.Count > 1) { result = new ChargeResult() { Status = ChargeStatus.FAILED, Message = "系统设置有错误,请联系统管理员" }; Logger.Warn(result.Message); return(result); } LaJi la = las[0]; if (!la.UP) { result = new ChargeResult() { Status = ChargeStatus.FAILED, Message = "系统已经被停用,请联系统管理员" }; Logger.Warn(result.Message); return(result); } if (cOrder == null) { result = new ChargeResult() { Status = ChargeStatus.FAILED, Message = ChargeConstant.ORDER_NOT_EXIST }; return(result); } Resource_taocan taocan = (from tc in db.Resource_taocan where tc.Id == order.ResourceTaocanId select tc).FirstOrDefault <Resource_taocan>(); if (!taocan.Enabled) { result = new ChargeResult() { Status = ChargeStatus.FAILED, Message = ChargeConstant.RESOURCE_TAOCAN_DISABLED }; return(result); } KMBit.DAL.Resource resource = (from ri in db.Resource join tr in db.Resource_taocan on ri.Id equals tr.Resource_id where tr.Id == order.ResourceTaocanId select ri).FirstOrDefault <Resource>(); if (resource == null) { db.Charge_Order.Remove(cOrder); db.SaveChanges(); result = new ChargeResult() { Status = ChargeStatus.FAILED, Message = "落地资源部存在,请联系平台管理员" }; return(result); } if (!resource.Enabled) { db.Charge_Order.Remove(cOrder); db.SaveChanges(); result = new ChargeResult() { Status = ChargeStatus.FAILED, Message = ChargeConstant.RESOURCE_DISABLED }; return(result); } if (order.ResourceId == 0) { order.ResourceId = resource.Id; } KMBit.DAL.Resrouce_interface rInterface = (from ri in db.Resrouce_interface where ri.Resource_id == order.ResourceId select ri).FirstOrDefault <Resrouce_interface>(); if (rInterface == null) { db.Charge_Order.Remove(cOrder); db.SaveChanges(); result = new ChargeResult() { Status = ChargeStatus.FAILED, Message = ChargeConstant.RESOURCE_INTERFACE_NOT_CONFIGURED }; return(result); } object o = Assembly.Load(rInterface.Interface_assemblyname).CreateInstance(rInterface.Interface_classname); chargeMgr = (ICharge)o; result = chargeMgr.Charge(order); } catch (Exception ex) { Logger.Error(ex); if (cOrder != null) { db.Charge_Order.Remove(cOrder); db.SaveChanges(); } } finally { if (db != null) { db.Dispose(); } } return(result); }
public ChargeResult MarketingCharge(BMarketOrderCharge orderCharge) { logger.Info("MarketingCharge"); ChargeResult result = new ChargeResult(); if (orderCharge == null) { result.Status = ChargeStatus.FAILED; result.Message = "参数不正确"; return(result); } if (orderCharge.AgentId == 0 || orderCharge.CustomerId == 0 || orderCharge.ActivityId == 0) { result.Status = ChargeStatus.FAILED; result.Message = "参数不正确"; return(result); } if (string.IsNullOrEmpty(orderCharge.SPName)) { result.Status = ChargeStatus.FAILED; result.Message = "参数不正确"; return(result); } if (string.IsNullOrEmpty(orderCharge.Phone)) { result.Status = ChargeStatus.FAILED; result.Message = "参数不正确"; return(result); } int sp = 0; if (orderCharge.SPName.Contains("联通")) { sp = 3; } else if (orderCharge.SPName.Contains("移动")) { sp = 1; } else if (orderCharge.SPName.Contains("电信")) { sp = 2; } chargebitEntities db = new chargebitEntities(); Marketing_Activity_Taocan mtaocan = null; Marketing_Orders mOrder = null; try { Marketing_Activities activity = (from a in db.Marketing_Activities where a.Id == orderCharge.ActivityId select a).FirstOrDefault <Marketing_Activities>(); if (activity == null) { result.Status = ChargeStatus.FAILED; result.Message = "参数不正确"; return(result); } if (activity.CustomerId != orderCharge.CustomerId) { result.Status = ChargeStatus.FAILED; result.Message = "参数不正确"; return(result); } if (activity.AgentId != orderCharge.AgentId) { result.Status = ChargeStatus.FAILED; result.Message = "参数不正确"; return(result); } //非直接扫码活动,必须传入特定的marketing order id if (activity.ScanType != 1 && orderCharge.ActivityOrderId == 0) { result.Status = ChargeStatus.FAILED; result.Message = "参数不正确"; return(result); } ChargeOrder order = new ChargeOrder() { AgencyId = orderCharge.AgentId, ChargeType = 1, City = orderCharge.City, CreatedTime = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now), IsMarket = true, MacAddress = orderCharge.OpenId, MobileNumber = orderCharge.Phone, MobileSP = orderCharge.SPName, Payed = true, Province = orderCharge.Province, }; //direct scan if (activity.ScanType == 1 && orderCharge.ActivityOrderId <= 0) { //判断是否还有可用marketing order List <Marketing_Activity_Taocan> rTaocans = (from mt in db.Marketing_Activity_Taocan join t in db.Resource_taocan on mt.ResourceTaocanId equals t.Id where mt.ActivityId == orderCharge.ActivityId && t.Sp_id == sp select mt).ToList <Marketing_Activity_Taocan>(); if (rTaocans.Count == 0) { result.Status = ChargeStatus.FAILED; result.Message = "本次活动" + orderCharge.SPName + "不能扫码充值"; return(result); } mtaocan = rTaocans[0]; mOrder = (from o in db.Marketing_Orders where o.ActivityId == orderCharge.ActivityId && o.Sent == false && o.Used == false && o.ActivityTaocanId == mtaocan.Id select o).FirstOrDefault <Marketing_Orders>(); if (mOrder == null) { result.Status = ChargeStatus.FAILED; result.Message = "本次活动的流量充值额度已经全部被扫完,尽请期待下次活动"; return(result); } if (mOrder.Used) { result.Status = ChargeStatus.FAILED; result.Message = "本次活动的流量充值额度已经全部被扫完,尽请期待下次活动"; return(result); } mOrder.Used = true; mOrder.Sent = true; //db.SaveChanges(); order.MarketOrderId = mOrder.Id; order.ResourceTaocanId = mtaocan.ResourceTaocanId; }//weichat push else if (activity.ScanType == 2 && orderCharge.ActivityOrderId > 0) { mOrder = (from o in db.Marketing_Orders where o.Id == orderCharge.ActivityOrderId select o).FirstOrDefault <Marketing_Orders>(); if (mOrder == null) { result.Status = ChargeStatus.FAILED; result.Message = "参数有误"; return(result); } if (mOrder.Used) { result.Status = ChargeStatus.FAILED; result.Message = "本次活动的流量充值额度已经全部被扫完,尽请期待下次活动"; return(result); } mtaocan = (from mt in db.Marketing_Activity_Taocan where mt.Id == mOrder.ActivityTaocanId select mt).FirstOrDefault <Marketing_Activity_Taocan>(); if (mtaocan == null) { result.Status = ChargeStatus.FAILED; result.Message = "参数有误"; return(result); } Resource_taocan rT = (from r in db.Resource_taocan where r.Id == mtaocan.ResourceTaocanId select r).FirstOrDefault <Resource_taocan>(); if (rT == null) { result.Status = ChargeStatus.FAILED; result.Message = "参数有误"; return(result); } if (rT.Sp_id != sp) { string tmpSPName = ""; if (rT.Sp_id == 1) { tmpSPName = "中国移动"; } else if (rT.Sp_id == 2) { tmpSPName = "中国电信"; } else if (rT.Sp_id == 3) { tmpSPName = "中国联通"; } result.Status = ChargeStatus.FAILED; result.Message = string.Format("此二维码链接不能充值{0}的手机号码的流量,只能充值{1}的号码的流量", orderCharge.SPName, tmpSPName); return(result); } order.ResourceTaocanId = mtaocan.ResourceTaocanId; order.MarketOrderId = orderCharge.ActivityOrderId; mOrder.Used = true; mOrder.Sent = true; } else if (activity.ScanType == 1 && orderCharge.ActivityOrderId > 0) { result.Status = ChargeStatus.FAILED; result.Message = "参数有误"; return(result); } else if (activity.ScanType == 2 && orderCharge.ActivityOrderId <= 0) { result.Status = ChargeStatus.FAILED; result.Message = "参数有误"; return(result); } OrderManagement orderMgr = new OrderManagement(CurrentLoginUser); order = orderMgr.GenerateOrder(order); ChargeBridge chargeBridge = new ChargeBridge(); if (order.Id > 0) { db.SaveChanges(); result = chargeBridge.Charge(order); if (result.Status == ChargeStatus.FAILED) { //Rollback, the order cannot be used next time mOrder.UsedTime = 0; mOrder.Used = false; if (activity.ScanType == 1) { mOrder.Sent = false; } db.SaveChanges(); } else { mOrder.UsedTime = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now); } db.SaveChanges(); } } catch (KMBitException kex) { logger.Warn(kex); result.Status = ChargeStatus.FAILED; result.Message = kex.Message; if (mOrder != null) { mOrder.Used = false; db.SaveChanges(); } } catch (Exception ex) { logger.Fatal(ex); result.Status = ChargeStatus.FAILED; result.Message = "系统错误,稍后再试"; if (mOrder != null) { mOrder.Used = false; db.SaveChanges(); } } finally { if (db != null) { db.Dispose(); } } logger.Info("Finished MarketingCharge"); return(result); }
public JsonResult PreCharge(WeChatChargeModel model) { logger.Info("WeChatController.PreCharge......................................................"); ApiMessage message = new ApiMessage(); ChargeOrder order = null; if (ModelState.IsValid) { try { if (string.IsNullOrEmpty(model.OpenId)) { message.Status = "ERROR"; message.Message = "请从公众号菜单打开此页面"; return Json(message, JsonRequestBehavior.AllowGet); } //ChargeBridge cb = new ChargeBridge(); order = new ChargeOrder() { ChargeType = 0, AgencyId = 0, Id = 0, Province = model.Province, City = model.City, MobileSP = model.SPName, MobileNumber = model.Mobile, OutOrderId = "", ResourceId = 0, ResourceTaocanId = model.ResourceTaocanId, RouteId = 0, CreatedTime = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now), Payed = false, OpenId = model.OpenId, OpenAccountType = 1 }; // OrderManagement orderMgt = new OrderManagement(); ResourceManagement resourceMgr = new ResourceManagement(0); string msg = string.Empty; if (orderMgt.IsThisMonthCharged(order.MobileNumber, order.ResourceTaocanId, out msg)) { message.Status = "ERROR"; message.Message = msg; return Json(message, JsonRequestBehavior.AllowGet); } order = orderMgt.GenerateOrder(order); int total = 0; List<BResourceTaocan> taocans = resourceMgr.FindResourceTaocans(order.ResourceTaocanId, 0, 0, out total); if (taocans == null || taocans.Count == 0) { message.Message = "当前套餐不可用"; message.Status = "ERROR"; return Json(message, JsonRequestBehavior.AllowGet); } logger.Info(string.Format("Order is generated, Id - {0}, mobile - {1}", order.Id, order.MobileNumber)); BResourceTaocan taocan = taocans[0]; message.Status = "OK"; message.Message = "预充值订单已经生成"; message.Item = null; // string ip = Request.ServerVariables["REMOTE_ADDR"]; if (ip != null && ip.IndexOf("::") > -1) { ip = "127.0.0.1"; } string prepayId = WeChatPaymentWrapper.GetPrepayId(PersistentValueManager.config, Session["wechat_openid"] != null ? Session["wechat_openid"].ToString() : "", order.PaymentId.ToString(), "TEST WECHATPAY", ip, (int)taocan.Taocan.Sale_price * 100, TradeType.JSAPI); logger.Info(string.Format("Prepay Id - {0}", prepayId)); WeChatOrder weOrder = new WeChatOrder(); weOrder.Order = new ChargeOrder { Id = order.Id, Payed = order.Payed, PaymentId = order.PaymentId, MobileNumber = order.MobileNumber, MobileSP = order.MobileSP, Province = order.Province }; weOrder.PrepayId = prepayId; weOrder.PaySign = ""; message.Item = weOrder; AccessToken token = PersistentValueManager.GetWeChatAccessToken(); JSAPITicket ticket = PersistentValueManager.GetWeChatJsApiTicket(); SortedDictionary<string, string> parameters = new SortedDictionary<string, string>(); parameters.Add("appId", PersistentValueManager.config.APPID); parameters.Add("timeStamp", model.timestamp); parameters.Add("nonceStr", model.nancestr); parameters.Add("package", "prepay_id=" + prepayId); parameters.Add("signType", "MD5"); logger.Info(string.Format("timeStamp:{0}", model.timestamp)); logger.Info(string.Format("nonceStr:{0}", model.nancestr)); logger.Info(string.Format("package:{0}", "prepay_id=" + prepayId)); string querystr = null; foreach (KeyValuePair<string, string> para in parameters) { if (querystr == null) { querystr = para.Key + "=" + para.Value; } else { querystr += "&" + para.Key + "=" + para.Value; } } querystr += "&key=" + PersistentValueManager.config.ShopSecret; logger.Info(querystr); string sign = UrlSignUtil.GetMD5(querystr); model.paySign = sign.ToUpper(); model.prepay_id = prepayId; logger.Info(string.Format("paySign:{0}", sign.ToUpper())); message.Item = model; } catch (KMBitException kex) { logger.Error(kex); message.Message = kex.Message; message.Status = "ERROR"; } catch (Exception ex) { message.Message = "未知错误,请联系我们"; message.Status = "ERROR"; logger.Fatal(ex); } finally { } } logger.Info("Done."); return Json(message, JsonRequestBehavior.AllowGet); }
public ActionResult Charge(ChargeModel model) { BaseManagement baseMgt = new BaseManagement(User.Identity.GetUserId<int>()); if (!baseMgt.CurrentLoginUser.Permission.CHARGE_BYTE) { ViewBag.Message = "没有权限充值流量"; return View("Error"); } if (ModelState.IsValid) { ChargeBridge cb = new ChargeBridge(); ChargeOrder order = new ChargeOrder() { ChargeType=2, Payed=true, OperateUserId=User.Identity.GetUserId<int>(), AgencyId = 0, Id = 0, Province=model.Province,City=model.City, MobileSP = model.SPName, MobileNumber = model.Mobile, OutOrderId = "", ResourceId = 0, ResourceTaocanId = model.ResourceTaocanId, RouteId = 0, CreatedTime = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now) }; OrderManagement orderMgt = new OrderManagement(); try { order = orderMgt.GenerateOrder(order); ViewBag.Message = "成功提交到充值系统,等待充值,可以到流量充值查询里查看充值状态..."; } catch(KMBitException kex) { ViewBag.Message = kex.Message; } catch(Exception ex) { ViewBag.Message = ex.Message; } //ChargeResult result = cb.Charge(order); } return View(); }
public ChargeResult Charge(ChargeOrder order) { Logger.Info("Charging..."); ChargeResult result = new ChargeResult() { Status = ChargeStatus.FAILED }; chargebitEntities db = null; ProceedOrder(order, out result); if (result.Status == ChargeStatus.FAILED) { return(result); } List <WebRequestParameters> parmeters = new List <WebRequestParameters>(); bool succeed = false; try { db = new chargebitEntities(); Charge_Order corder = (from co in db.Charge_Order where co.Id == order.Id select co).FirstOrDefault <Charge_Order>(); corder.Process_time = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now); KMBit.DAL.Resrouce_interface rInterface = (from ri in db.Resrouce_interface where ri.Resource_id == order.ResourceId select ri).FirstOrDefault <Resrouce_interface>(); Resource_taocan taocan = (from t in db.Resource_taocan where t.Id == order.ResourceTaocanId select t).FirstOrDefault <Resource_taocan>(); ServerUri = new Uri(rInterface.APIURL); StringBuilder body = new StringBuilder(); body.Append("{"); body.Append("usernumber:\"" + rInterface.Username + "\""); body.Append(",gavingnumber:\"" + order.MobileNumber + "\""); body.Append(",packagetype:\"1\""); body.Append(",packagecode:\"" + taocan.Serial + "\""); body.Append(",validtype:\"0\""); body.Append("}"); string appx = order.Id.ToString(); string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); string method = "ai.cuc.ll.method.gav"; string appkey = rInterface.AppKey; // "ai.cuc.ll.appkey.test"; string appSecret = rInterface.AppSecret; // "8888"; parmeters.Add(new WebRequestParameters("apptx", appx, false)); parmeters.Add(new WebRequestParameters("timestamp", timestamp, false)); parmeters.Add(new WebRequestParameters("method", method, false)); parmeters.Add(new WebRequestParameters("appkey", appkey, false)); parmeters.Add(new WebRequestParameters("msg", body.ToString(), false)); SortedDictionary <string, string> paras = new SortedDictionary <string, string>(); foreach (WebRequestParameters p in parmeters) { paras.Add(p.Name, p.Value); } string urlStr = string.Empty; foreach (KeyValuePair <string, string> p in paras) { if (urlStr == string.Empty) { urlStr = p.Key + "=" + p.Value; } else { urlStr += "&" + p.Key + "=" + p.Value; } } urlStr += "&" + UrlSignUtil.GetMD5(appSecret); string sign = UrlSignUtil.GetMD5(urlStr); parmeters.Add(new WebRequestParameters("sign", sign, false)); parmeters.Add(new WebRequestParameters("signMethod", "MD5", false)); SendRequest(parmeters, false, out succeed, RequestType.POST); //parse Response if (!string.IsNullOrEmpty(Response)) { result.Message = ChargeConstant.SUCCEED_CHARGE; result.Status = ChargeStatus.SUCCEED; try { Newtonsoft.Json.Linq.JObject jsonResult = Newtonsoft.Json.Linq.JObject.Parse(Response); string code = jsonResult["code"].ToString(); string message = jsonResult["detail"].ToString(); switch (code) { case "0000": result.Status = ChargeStatus.SUCCEED; break; case "9999": result.Status = ChargeStatus.FAILED; result.Message = message; break; default: result.Message = "未知错误"; result.Status = ChargeStatus.FAILED; break; } } catch (Exception ex) { result.Message = ex.Message; result.Status = ChargeStatus.FAILED; } } else { result.Message = "未知错误"; result.Status = ChargeStatus.FAILED; } if (result.Message != null && result.Message.Length > 5000) { result.Message = result.Message.Substring(0, 5000); } ChangeOrderStatus(order, result); } catch (Exception ex) { Logger.Fatal(ex); } finally { if (db != null) { db.Dispose(); } } Logger.Info("Charging done!"); return(result); }
public void GetChargeStatus(int resourceId) { Logger.Info("GetChargeStatus..."); chargebitEntities db = null; try { List<Charge_Order> orders = null; lock (getStatusObj) { db = new chargebitEntities(); orders = (from o in db.Charge_Order where o.Status == 1 && o.Resource_id == resourceId && o.Payed && o.Id > lastMaxGetStatusOrderId orderby o.Id ascending select o).ToList<Charge_Order>(); if (orders.Count <= 0) { Logger.Info("No orders need to sync status of resourceId:" + resourceId); return; } else { lastMaxGetStatusOrderId = (from o in orders select o.Id).Max(); Logger.Info(string.Format("{0} orders need to sync status", orders.Count)); } } KMBit.DAL.Resrouce_interface rInterface = rInterface = (from ri in db.Resrouce_interface where ri.Resource_id == resourceId select ri).FirstOrDefault<Resrouce_interface>(); if(string.IsNullOrEmpty(rInterface.QueryStatusUrl)) { Logger.Warn("QueryStatusUrl is empty."); return; } ServerUri = new Uri(rInterface.QueryStatusUrl); if (string.IsNullOrEmpty(token)) { GetToken(rInterface); } if (DateTimeUtil.ConvertDateTimeToInt(DateTime.Now) > expiredTime) { Logger.Info("Token expired, get it again."); GetToken(rInterface); } if (string.IsNullOrEmpty(token)) { Logger.Error("Cannot get token."); return; } List<WebRequestParameters> parmeters = new List<WebRequestParameters>(); StringBuilder orderIds = new StringBuilder(); foreach(Charge_Order o in orders) { if(!string.IsNullOrEmpty(o.Out_Order_Id)) { orderIds.Append(o.Out_Order_Id + ","); } } string orderParamStr = orderIds.ToString(); orderParamStr = orderParamStr.Substring(0, orderParamStr.Length-1); parmeters.Add(new WebRequestParameters() {Name="para",Value="{\"orderId\":\""+orderParamStr+"\"}" }); parmeters.Add(new WebRequestParameters() { Name="token",Value=token}); parmeters.Add(new WebRequestParameters() { Name="id",Value= rInterface.Username.Trim()}); bool succeed = false; SendRequest(parmeters, false, out succeed, RequestType.POST); ChargeResult result = new ChargeResult(); if (!string.IsNullOrEmpty(Response)) { try { Newtonsoft.Json.Linq.JObject jsonResult = Newtonsoft.Json.Linq.JObject.Parse(Response); string ret = jsonResult["result"].ToString(); string message = jsonResult["resultMsg"].ToString(); Logger.Info(string.Format("Message:{0} returned by {1}"+message!=null?message:"", rInterface.QueryStatusUrl)); if (!string.IsNullOrEmpty(ret) && ret.Trim() == "0") { if(jsonResult["orderResult"]!=null) { Newtonsoft.Json.Linq.JArray backOrders = JArray.Parse(jsonResult["orderResult"].ToString()); if(backOrders!=null && backOrders.Count>0) { foreach(JObject ro in backOrders) { string roId = ro["orderId"]!=null? ro["orderId"].ToString():null; string roPhone= ro["accNumber"] != null ? ro["accNumber"].ToString() : null; string roResult= ro["orderResult"] != null ? ro["orderResult"].ToString() : null; string roMessage= ro["orderMsg"] != null ? ro["orderMsg"].ToString() : null; if(string.IsNullOrEmpty(roId) || string.IsNullOrEmpty(roPhone)) { continue; } Charge_Order dbOrder = (from o in orders where o.Out_Order_Id == roId.Trim() && o.Phone_number == roPhone.Trim() select o).FirstOrDefault<Charge_Order>(); if(dbOrder!=null) { if(!string.IsNullOrEmpty(roResult) && roResult.Trim()=="0") { result.Status = ChargeStatus.SUCCEED; result.Message = roMessage != null ? roMessage : "充值成功"; } else { result.Status = ChargeStatus.FAILED; result.Message = roMessage != null ? roMessage : "充值失败"; } } ChargeOrder blOrder = new ChargeOrder() { Id= dbOrder.Id,OutOrderId=dbOrder.Out_Order_Id,AgencyId=dbOrder.Agent_Id,Status=dbOrder.Status }; ChangeOrderStatus(blOrder,result,true); } } } } else { Logger.Info(string.Format("No order status returned back by {0}", rInterface.QueryStatusUrl)); } } catch (Exception ex) { Logger.Fatal(ex); } } } catch(Exception ex) { Logger.Error("Exception was thrown"); Logger.Fatal(ex); } finally { if (db != null) db.Dispose(); } Logger.Info("GetChargeStatus done!"); }
public APIChargeResult Charge(int agentId,int routeId,string mobile,string spname,string province,string city,string callBackUrl,string client_order_id) { if(string.IsNullOrEmpty(mobile)) { throw new KMBitException("手机号码不能为空"); } if (string.IsNullOrEmpty(spname)) { throw new KMBitException("手机号归属运行商不能为空"); } if (string.IsNullOrEmpty(province)) { throw new KMBitException("手机号归属省份不能为空"); } //if (string.IsNullOrEmpty(city)) //{ // throw new KMBitException("手机号归属城市不能为空"); //} ChargeResult result = null; ChargeBridge cb = new ChargeBridge(); ChargeOrder order = new ChargeOrder() { ClientOrderId = client_order_id, Payed = false, OperateUserId = 0, AgencyId = agentId, Id = 0, Province = province, City = city!=null? city:"", MobileNumber = mobile, MobileSP=spname, OutOrderId = "", ResourceId = 0, ResourceTaocanId = 0, RouteId = routeId, CreatedTime = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now), CallbackUrl = callBackUrl }; chargebitEntities db = null; OrderManagement orderMgt = new OrderManagement(); try { db = new chargebitEntities(); Users agent = (from u in db.Users where u.Id == agentId select u).FirstOrDefault<Users>(); if(agent==null) { throw new KMBitException(string.Format("编号为{0}的代理商不存在",agentId)); } if(!agent.Enabled) { throw new KMBitException(string.Format("代理商{0}已经被关闭禁用",agent.Name)); } //verify mobile sp Agent_route route = (from r in db.Agent_route where r.Id == routeId && r.User_id == agentId select r).FirstOrDefault<Agent_route>(); if(route==null) { throw new KMBitException(string.Format("代理商 {1} 编号为{0}的路由不存在", routeId,agent.Name)); } if(!route.Enabled) { throw new KMBitException(string.Format("代理商 {1} 编号为{0}的路由已经被关闭", routeId, agent.Name)); } Resource_taocan taocan = (from t in db.Resource_taocan where t.Id==route.Resource_taocan_id select t).FirstOrDefault<Resource_taocan>(); int spId = (from sp in db.Sp where sp.Name.Contains(spname.Trim()) select sp.Id).FirstOrDefault<int>(); if(spId==0) { throw new KMBitException("手机运营商的值必须是-中国移动,中国联通或者中国电信"); } int provinceId = (from area in db.Area where area.Name.Contains(province) select area.Id).FirstOrDefault<int>(); if(provinceId==0) { throw new KMBitException("手机号码归属省份值不正确,例如 河南,海南,江苏,请以此种格式传入"); } if(taocan.NumberProvinceId>0 && provinceId>0) { if(provinceId!=taocan.NumberProvinceId) { throw new KMBitException(string.Format("当前路由不能充{0}-{1}的手机号码",spname,province)); } } order = orderMgt.GenerateOrder(order); //result = cb.Charge(order); if(order.Id>0) { result = new ChargeResult(); result.Status = ChargeStatus.SUCCEED; result.Message = "充值信息已提交到充值系统"; } } catch(KMBitException kex) { throw kex; } catch (Exception ex) { logger.Error(ex); result = new ChargeResult(); result.Status = ChargeStatus.FAILED; result.Message = "未知错误,请联系平台管理员"; } APIChargeResult apiResult = new APIChargeResult(); //apiResult.Message = result.Message; apiResult.OrderId = order.Id; switch (result.Status) { case ChargeStatus.SUCCEED: apiResult.Status = ChargeStatus.SUCCEED.ToString(); apiResult.Message = result.Message; break; case ChargeStatus.FAILED: apiResult.Status = ChargeStatus.FAILED.ToString(); break; case ChargeStatus.ONPROGRESS: apiResult.Status = ChargeStatus.SUCCEED.ToString(); break; case ChargeStatus.PENDIND: apiResult.Status = ChargeStatus.SUCCEED.ToString(); break; } return apiResult; }
public ActionResult Charge(ChargeModel model) { if (ModelState.IsValid) { //ChargeBridge cb = new ChargeBridge(); ChargeOrder order = new ChargeOrder() { ChargeType = 0, AgencyId = 0, Id = 0, Province = model.Province, City = model.City, MobileSP = model.SPName, MobileNumber = model.Mobile, OutOrderId = "", ResourceId = 0, ResourceTaocanId = model.ResourceTaocanId, RouteId = 0, CreatedTime = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now) }; // OrderManagement orderMgt = new OrderManagement(); ResourceManagement resourceMgr = new ResourceManagement(0); try { order = orderMgt.GenerateOrder(order); } catch(KMBitException kex) { ViewBag.Message = kex.Message; return View(); } catch(Exception ex) { ViewBag.Message = "未知错误请联系系统管理员"; return View(); } int total = 0; List<BResourceTaocan> taocans = resourceMgr.FindResourceTaocans(order.ResourceTaocanId, 0, 0, out total); if (taocans == null || taocans.Count == 0) { ViewBag.Message = "当前套餐不可用"; return View(); } BResourceTaocan taocan = taocans[0]; //Redirct to the payment page. //TBD //After the payment is done then process below steps AlipayConfig config = new AlipayConfig(System.IO.Path.Combine(Request.PhysicalApplicationPath, "Config\\AliPayConfig.xml")); Submit submit = new Submit(config); SortedDictionary<string, string> sParaTemp = new SortedDictionary<string, string>(); sParaTemp.Add("partner", config.Partner); sParaTemp.Add("seller_email", "*****@*****.**"); sParaTemp.Add("_input_charset", config.Input_charset.ToLower()); sParaTemp.Add("service", "create_direct_pay_by_user"); sParaTemp.Add("payment_type", "1"); sParaTemp.Add("notify_url", config.Notify_Url); sParaTemp.Add("return_url", config.Return_Url); sParaTemp.Add("out_trade_no", order.PaymentId.ToString()); sParaTemp.Add("subject", string.Format("{0}M", taocan.Taocan.Quantity)); sParaTemp.Add("total_fee", taocan.Taocan.Sale_price.ToString("0.00")); sParaTemp.Add("body", string.Format("{0}M", taocan.Taocan.Quantity)); sParaTemp.Add("show_url", ""); sParaTemp.Add("seller_id",config.Partner); //sParaTemp.Add("anti_phishing_key", ""); //sParaTemp.Add("exter_invoke_ip", ""); //建立请求 string sHtmlText = submit.BuildRequest(sParaTemp, "get", "确认"); //Response.Write("ok"); Response.Clear(); Response.Charset = "utf-8"; Response.Write(sHtmlText); //ChargeResult result = cb.Charge(order); //ViewBag.Message = result.Message; } return View(); }
public ChargeOrder GenerateOrder(ChargeOrder order) { if (order == null) { throw new KMBitException("订单对象不能为NULL"); } if (string.IsNullOrEmpty(order.MobileNumber)) { throw new KMBitException("充值的手机号码不能为空"); } chargebitEntities db = null; try { db = new chargebitEntities(); Marketing_Orders mOrder = null; Marketing_Activity_Taocan mTaocan = null; Marketing_Activities activity = null; if (order.IsMarket && order.MarketOrderId > 0) { //if (string.IsNullOrEmpty(order.MacAddress)) //{ // throw new KMBitException("活动充值时必须获取终端的MAC地址"); //} mOrder = (from o in db.Marketing_Orders where o.Id == order.MarketOrderId select o).FirstOrDefault <Marketing_Orders>(); if (mOrder == null) { throw new KMBitException(string.Format("编号为{0}的活动充值记录不存在", order.MarketOrderId)); } if (mOrder.Used) { throw new KMBitException("此二维码已经只用过,不能重复使用"); } mTaocan = (from m in db.Marketing_Activity_Taocan where m.Id == mOrder.ActivityTaocanId select m).FirstOrDefault <Marketing_Activity_Taocan>(); if (mTaocan == null) { throw new KMBitException(string.Format("编号为{0}的活动充值记录的套餐信息不存在", order.MarketOrderId)); } activity = (from a in db.Marketing_Activities where a.Id == mTaocan.ActivityId select a).FirstOrDefault <Marketing_Activities>(); if (activity == null) { throw new KMBitException(string.Format("编号为{0}的活动不存在", mTaocan.ActivityId)); } //check if the device or the number is already charged if (activity.ScanType == 1) { int[] acos = (from mo in db.Marketing_Orders where mo.ActivityId == activity.Id select mo.Id).ToArray <int>(); if (acos == null || acos.Length <= 0) { throw new KMBitException(string.Format("编号为{0}的活动还没有任何可用的充值套餐", mTaocan.ActivityId)); } //验证电话号码是否在某个直扫活动里已经成功充值过 int count = (from o in db.Charge_Order where o.Phone_number == order.MobileNumber && o.Status != 3 && acos.Contains(o.MarketOrderId) select o.Id).Count(); if (count > 0) { throw new KMBitException("同一次营销活动每个手机每个号码只能扫描一次"); } } order.ResourceId = mTaocan.ResourceId; order.ResourceTaocanId = mTaocan.ResourceTaocanId; order.RouteId = mTaocan.RouteId; if (order.AgencyId == 0) { order.AgencyId = (from a in db.Marketing_Activities where a.Id == mTaocan.ActivityId select a.AgentId ).FirstOrDefault <int>(); } } Resource_taocan taocan = null; if (order.ResourceTaocanId <= 0 && order.RouteId > 0) { var query = from ta in db.Agent_route join tc in db.Resource_taocan on ta.Resource_taocan_id equals tc.Id where ta.Id == order.RouteId select tc; taocan = query.FirstOrDefault <Resource_taocan>(); } else if (order.ResourceTaocanId > 0) { taocan = (from tc in db.Resource_taocan where tc.Id == order.ResourceTaocanId select tc).FirstOrDefault <Resource_taocan>(); } if (!taocan.Enabled) { throw new KMBitException(ChargeConstant.RESOURCE_TAOCAN_DISABLED); } if (taocan == null) { throw new KMBitException("套餐信息不存在,不能充值"); } order.ResourceTaocanId = taocan.Id; KMBit.DAL.Resource resource = (from ri in db.Resource join tr in db.Resource_taocan on ri.Id equals tr.Resource_id where tr.Id == order.ResourceTaocanId select ri).FirstOrDefault <Resource>(); if (resource == null) { throw new KMBitException("落地资源不存在"); } if (!resource.Enabled) { throw new KMBitException(ChargeConstant.RESOURCE_DISABLED); } Agent_route route = null; if (order.AgencyId > 0 && order.RouteId > 0) { route = (from r in db.Agent_route where r.Id == order.RouteId select r).FirstOrDefault <Agent_route>(); if (route == null) { throw new KMBitException("代理商路由不存在"); } if (route.User_id != order.AgencyId) { throw new KMBitException("当前代理商没有此路由"); } if (!route.Enabled) { throw new KMBitException(string.Format("编号为{0}代理商路由已被管理员停用", route.Id)); } } Charge_Order history = new Charge_Order(); history.Agent_Id = order.AgencyId; history.Completed_Time = 0; history.Created_time = order.CreatedTime > 0 ? order.CreatedTime : DateTimeUtil.ConvertDateTimeToInt(DateTime.Now); history.Operate_User = order.OperateUserId; history.Out_Order_Id = ""; history.Payed = order.Payed; history.Phone_number = order.MobileNumber; history.MobileSP = order.MobileSP; history.Province = order.Province; history.City = order.City; history.Resource_id = resource.Id; history.Resource_taocan_id = order.ResourceTaocanId; history.RuoteId = order.RouteId; history.Status = 11; history.CallBackUrl = order.CallbackUrl != null ? order.CallbackUrl : null; history.Platform_Sale_Price = taocan.Sale_price; if (taocan.EnableDiscount) { history.Platform_Cost_Price = taocan.Purchase_price * taocan.Resource_Discount; } else { history.Platform_Cost_Price = taocan.Purchase_price; } if (order.IsMarket && order.MarketOrderId > 0) { //营销充值 history.Charge_type = 1; history.MarketOrderId = order.MarketOrderId; history.Sale_price = mTaocan.Price; history.Purchase_price = history.Platform_Sale_Price * route.Discount; history.Payed = true; } else { if (order.AgencyId > 0) { //代理商充值 history.Charge_type = 1; history.Purchase_price = taocan.Sale_price * route.Discount; history.Sale_price = route.Sale_price; history.Revenue = history.Purchase_price - history.Platform_Cost_Price; } else if (order.OperateUserId > 0) { //管理员后台充值 history.Charge_type = 2; history.Purchase_price = taocan.Sale_price; history.Sale_price = taocan.Sale_price; history.Revenue = history.Platform_Sale_Price - history.Platform_Cost_Price; } else { //前台用户直冲 history.Charge_type = 0; history.Purchase_price = taocan.Sale_price; history.Sale_price = taocan.Sale_price; history.Revenue = history.Platform_Sale_Price - history.Platform_Cost_Price; } } db.Charge_Order.Add(history); db.SaveChanges(); order.Id = history.Id; //Create Payment record for direct charge if (history.Charge_type == 0) { Payment_history payment = new Payment_history() { PaymentAccount = "", Amount = taocan.Sale_price, ChargeOrderId = history.Id, CreatedTime = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now), PayType = 0, Tranfser_Type = 1 }; db.Payment_history.Add(payment); db.SaveChanges(); order.PaymentId = payment.Id; } }catch (Exception ex) { throw new KMBitException(ex.Message); } finally { if (db != null) { db.Dispose(); } } return(order); }
public APIChargeResult Charge(int agentId, int routeId, string mobile, string spname, string province, string city, string callBackUrl, string client_order_id) { if (string.IsNullOrEmpty(mobile)) { throw new KMBitException("手机号码不能为空"); } if (string.IsNullOrEmpty(spname)) { throw new KMBitException("手机号归属运行商不能为空"); } if (string.IsNullOrEmpty(province)) { throw new KMBitException("手机号归属省份不能为空"); } //if (string.IsNullOrEmpty(city)) //{ // throw new KMBitException("手机号归属城市不能为空"); //} ChargeResult result = null; ChargeBridge cb = new ChargeBridge(); ChargeOrder order = new ChargeOrder() { ClientOrderId = client_order_id, Payed = false, OperateUserId = 0, AgencyId = agentId, Id = 0, Province = province, City = city != null? city:"", MobileNumber = mobile, MobileSP = spname, OutOrderId = "", ResourceId = 0, ResourceTaocanId = 0, RouteId = routeId, CreatedTime = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now), CallbackUrl = callBackUrl }; chargebitEntities db = null; OrderManagement orderMgt = new OrderManagement(); try { db = new chargebitEntities(); Users agent = (from u in db.Users where u.Id == agentId select u).FirstOrDefault <Users>(); if (agent == null) { throw new KMBitException(string.Format("编号为{0}的代理商不存在", agentId)); } if (!agent.Enabled) { throw new KMBitException(string.Format("代理商{0}已经被关闭禁用", agent.Name)); } //verify mobile sp Agent_route route = (from r in db.Agent_route where r.Id == routeId && r.User_id == agentId select r).FirstOrDefault <Agent_route>(); if (route == null) { throw new KMBitException(string.Format("代理商 {1} 编号为{0}的路由不存在", routeId, agent.Name)); } if (!route.Enabled) { throw new KMBitException(string.Format("代理商 {1} 编号为{0}的路由已经被关闭", routeId, agent.Name)); } Resource_taocan taocan = (from t in db.Resource_taocan where t.Id == route.Resource_taocan_id select t).FirstOrDefault <Resource_taocan>(); int spId = (from sp in db.Sp where sp.Name.Contains(spname.Trim()) select sp.Id).FirstOrDefault <int>(); if (spId == 0) { throw new KMBitException("手机运营商的值必须是-中国移动,中国联通或者中国电信"); } int provinceId = (from area in db.Area where area.Name.Contains(province) select area.Id).FirstOrDefault <int>(); if (provinceId == 0) { throw new KMBitException("手机号码归属省份值不正确,例如 河南,海南,江苏,请以此种格式传入"); } if (taocan.NumberProvinceId > 0 && provinceId > 0) { if (provinceId != taocan.NumberProvinceId) { throw new KMBitException(string.Format("当前路由不能充{0}-{1}的手机号码", spname, province)); } } order = orderMgt.GenerateOrder(order); //result = cb.Charge(order); if (order.Id > 0) { result = new ChargeResult(); result.Status = ChargeStatus.SUCCEED; result.Message = "充值信息已提交到充值系统"; } } catch (KMBitException kex) { throw kex; } catch (Exception ex) { logger.Error(ex); result = new ChargeResult(); result.Status = ChargeStatus.FAILED; result.Message = "未知错误,请联系平台管理员"; } APIChargeResult apiResult = new APIChargeResult(); //apiResult.Message = result.Message; apiResult.OrderId = order.Id; switch (result.Status) { case ChargeStatus.SUCCEED: apiResult.Status = ChargeStatus.SUCCEED.ToString(); apiResult.Message = result.Message; break; case ChargeStatus.FAILED: apiResult.Status = ChargeStatus.FAILED.ToString(); break; case ChargeStatus.ONPROGRESS: apiResult.Status = ChargeStatus.SUCCEED.ToString(); break; case ChargeStatus.PENDIND: apiResult.Status = ChargeStatus.SUCCEED.ToString(); break; } return(apiResult); }