예제 #1
0
 protected void RemoveQRCode(Charge_Order order)
 {
     if (order.MarketOrderId > 0)
     {
         chargebitEntities db = null;
         try
         {
             db = new chargebitEntities();
             Marketing_Orders mOrder = (from mo in db.Marketing_Orders where mo.Id == order.MarketOrderId select mo).FirstOrDefault <Marketing_Orders>();
             if (mOrder != null && !string.IsNullOrEmpty(mOrder.CodePath))
             {
                 string tmpPhysicalPath = System.IO.Path.Combine(settings.RootDirectory, mOrder.CodePath.Replace('/', '\\'));
                 if (System.IO.File.Exists(tmpPhysicalPath))
                 {
                     System.IO.File.Delete(tmpPhysicalPath);
                 }
             }
         }catch (Exception ex)
         {
             Logger.Fatal(ex);
         }finally
         {
             if (db != null)
             {
                 db.Dispose();
             }
         }
     }
 }
예제 #2
0
        /// <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);
        }
예제 #3
0
        public bool UpdatePaymentStatus(string mobile, int orderId, bool payed)
        {
            bool result = false;

            using (chargebitEntities db = new chargebitEntities())
            {
                Charge_Order cOrder = (from o in db.Charge_Order where o.Id == orderId && o.Phone_number == mobile select o).FirstOrDefault <Charge_Order>();
                if (cOrder != null)
                {
                    cOrder.Payed = payed;
                }
                else
                {
                    throw new KMBitException(string.Format("编号为{0}的充值记录不存在", orderId));
                }

                db.SaveChanges();
                result = true;
            }

            return(result);
        }
예제 #4
0
        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);
        }
예제 #5
0
파일: YiRenCharge.cs 프로젝트: 21ki/kuanmai
        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);
        }
예제 #6
0
파일: YiRenCharge.cs 프로젝트: 21ki/kuanmai
        public void GetChargeStatus(int resourceId)
        {
            chargebitEntities db = new chargebitEntities();

            try
            {
                List <Charge_Order> orders = (from o in db.Charge_Order where o.Status == 1 select o).ToList <Charge_Order>();
                if (orders.Count <= 0)
                {
                    Logger.Info("No orders need to sync status of resourceId:" + resourceId);
                    return;
                }
                Logger.Info(string.Format("{0} orders need to sync status", orders.Count));
                KMBit.DAL.Resrouce_interface rInterface = (from ri in db.Resrouce_interface where ri.Resource_id == resourceId select ri).FirstOrDefault <Resrouce_interface>();
                ServerUri = new Uri(rInterface.APIURL);
                List <WebRequestParameters> parmeters = new List <WebRequestParameters>();
                parmeters.Add(new WebRequestParameters("V", version, false));
                parmeters.Add(new WebRequestParameters("Action", "getReports", false));
                SortedDictionary <string, string> paras = new SortedDictionary <string, string>();
                paras["Account"] = rInterface.Username;
                paras["Count"]   = statusCount.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));
                }
                bool succeed = false;
                SendRequest(parmeters, false, out succeed);
                if (succeed && !string.IsNullOrEmpty(Response))
                {
                    JObject jsonRes = JObject.Parse(Response);
                    string  code    = jsonRes["Code"] != null ? jsonRes["Code"].ToString() : "";
                    string  message = jsonRes["Message"] != null ? jsonRes["Message"].ToString() : "";
                    Logger.Info(string.Format("Code:{0}, Message:{1}", code, message));
                    if (!string.IsNullOrEmpty(code) && code == "0" && !string.IsNullOrEmpty(message) && message == "OK")
                    {
                        JArray charges = (JArray)jsonRes["Reports"];
                        if (charges != null)
                        {
                            Logger.Info(string.Format("Get {0} reports from resource", charges.Count));
                            for (int i = 0; i < charges.Count; i++)
                            {
                                JObject report  = (JObject)charges[i];
                                string  taskId  = report["TaskID"] != null? report["TaskID"].ToString():"";
                                string  phone   = report["Mobile"] != null? report["Mobile"].ToString():"";
                                string  status  = report["Status"] != null? report["Status"].ToString():"";
                                string  time    = report["ReportTime"] != null?report["ReportTime"].ToString():"";
                                string  rptCode = report["ReportCode"] != null? report["ReportCode"].ToString():"";
                                Logger.Info(string.Format("TaskId:{0}, MobilePhone:{1}, Status:{2}, Time:{3}", taskId, phone, status, time));
                                Charge_Order order = (from o in orders where o.Out_Order_Id == taskId && o.Phone_number == phone select o).FirstOrDefault <Charge_Order>();
                                if (order != null && !string.IsNullOrEmpty(taskId) && !string.IsNullOrEmpty(phone) && !string.IsNullOrEmpty(status))
                                {
                                    DateTime cTime = DateTime.MinValue;
                                    DateTime.TryParse(time, out cTime);
                                    if (cTime != DateTime.MinValue)
                                    {
                                        order.Completed_Time = DateTimeUtil.ConvertDateTimeToInt(cTime);
                                    }
                                    if (status == "4")
                                    {
                                        order.Status  = 2;
                                        order.Message = "充值成功:" + rptCode;
                                        RemoveQRCode(order);
                                    }
                                    else if (status == "5")
                                    {
                                        order.Status  = 3;
                                        order.Message = "充值失败:" + rptCode;
                                        if (order.Agent_Id > 0)
                                        {
                                            if (order.MarketOrderId <= 0)
                                            {
                                                Users agency = (from u in db.Users where u.Id == order.Agent_Id select u).FirstOrDefault <Users>();
                                                if (agency != null)
                                                {
                                                    agency.Remaining_amount += order.Purchase_price;
                                                    order.Refound            = true;
                                                }
                                            }
                                            else
                                            {
                                                order.Message = string.Format("充值失败:{0},二维码可以重复扫码使用直到充值成功", rptCode);
                                                order.Refound = false;
                                                Marketing_Orders mOrder = (from mo in db.Marketing_Orders where mo.Id == order.MarketOrderId select mo).FirstOrDefault <Marketing_Orders>();
                                                if (mOrder != null)
                                                {
                                                    mOrder.Used = false;
                                                }
                                            }

                                            db.SaveChanges();
                                        }
                                    }
                                }

                                //send back status to agent api calling
                                if (!string.IsNullOrEmpty(order.CallBackUrl))
                                {
                                    this.SendStatusBackToAgentCallback(order);
                                }
                            }
                            if (charges != null && charges.Count > 0)
                            {
                                db.SaveChanges();
                            }
                        }
                    }
                }
            }
            catch (KMBitException kex)
            {
                Logger.Warn(kex);
            }catch (Exception ex)
            {
                Logger.Fatal(ex);
            }finally
            {
                if (db != null)
                {
                    db.Dispose();
                }
            }
        }
예제 #7
0
        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);
        }
예제 #8
0
        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("回调数据中没有本系统的订单号,所以不能更新本系统数据,此次调用为脏数据");
            }
        }
예제 #9
0
        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);
        }
예제 #10
0
        public void SendStatusBackToAgentCallback(object oorder)
        {
            if (oorder.GetType() != typeof(Charge_Order))
            {
                return;
            }
            Charge_Order order = oorder as Charge_Order;

            Logger.Info("SendStatusBackToAgentCallback...");
            if (order == null || order.Agent_Id <= 0 || string.IsNullOrEmpty(order.CallBackUrl))
            {
                Logger.Info("Not an agent order, no need to proceed anymore.");
                return;
            }
            Logger.Info(string.Format("Order Id {0}", order.Id.ToString()));
            if (!string.IsNullOrEmpty(order.Client_Order_Id))
            {
                Logger.Info(string.Format("Client OrderId {0}", order.Client_Order_Id.ToString()));
            }
            if (!string.IsNullOrEmpty(order.Out_Order_Id))
            {
                Logger.Info(string.Format("Out Order Id {0}", order.Out_Order_Id.ToString()));
            }
            Logger.Info(string.Format("Order Status {0}", order.Status.ToString()));
            Logger.Info(string.Format("Order Message {0}", order.Message != null?order.Message:""));
            chargebitEntities db = null;

            try
            {
                if (string.IsNullOrEmpty(order.CallBackUrl))
                {
                    Logger.Info("Order callback URL is empty, no need to callback.");
                    return;
                }
                db = new chargebitEntities();
                NameValueCollection col = new NameValueCollection();
                SortedDictionary <string, string> paras = new SortedDictionary <string, string>();
                string orderId = order.Id.ToString();
                string status  = order.Status.ToString();
                string message = order.Message != null ? order.Message : "";
                Users  agent   = (from u in db.Users where u.Id == order.Agent_Id select u).FirstOrDefault <Users>();
                Logger.Info(string.Format("Agent {0}", agent.Email));
                if (agent == null)
                {
                    status  = "3";
                    message = "代理商账户没有找到";
                }
                string token = agent.SecurityStamp;
                paras["OrderId"]       = orderId;
                paras["Status"]        = status;
                paras["ClientOrderId"] = order.Client_Order_Id != null? order.Client_Order_Id:"";
                paras["Message"]       = message;
                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;
                    }
                }
                Logger.Info(string.Format("Post data {1} to {0}", order.CallBackUrl, signStr));
                signStr += "&key=" + token;
                Logger.Info(string.Format("String to be signed {0}", signStr));
                Logger.Info(string.Format("Signature is {0}", UrlSignUtil.GetMD5(signStr)));
                paras["Sign"] = UrlSignUtil.GetMD5(signStr);
                foreach (KeyValuePair <string, string> p in paras)
                {
                    col[p.Key] = p.Value;
                }
                Charge_Order dborder = (from o in db.Charge_Order where o.Id == order.Id select o).FirstOrDefault <Charge_Order>();
                string       resStr  = HttpSercice.PostHttpRequest(order.CallBackUrl, col, WeChat.Adapter.Requests.RequestType.POST, null);
                if (resStr == null)
                {
                    dborder.PushedTimes += 1;
                    dborder.Received     = true;
                }
                else if (resStr.ToLower() == "fail")
                {
                    dborder.PushedTimes += 1;
                    dborder.Received     = false;
                }
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
            finally
            {
                if (db != null)
                {
                    db.Dispose();
                }

                Logger.Info("Leaving SendStatusBackToAgentCallback...");
            }
        }
예제 #11
0
        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);
                        }
                    }
                }
            }
        }
예제 #12
0
        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!");
            }
        }
예제 #13
0
        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);
        }
예제 #14
0
        protected void SendStatusBackToAgentCallback(Charge_Order order)
        {
            Logger.Info("SendStatusBackToAgentCallback");
            if (order == null || order.Agent_Id <= 0 || string.IsNullOrEmpty(order.CallBackUrl))
            {
                return;
            }
            Logger.Info(string.Format("Order Id {0}", order.Id.ToString()));
            Logger.Info(string.Format("Order Status {0}", order.Status.ToString()));
            Logger.Info(string.Format("Order Message {0}", order.Message != null?order.Message:""));
            chargebitEntities db = new chargebitEntities();

            try
            {
                List <WebRequestParameters>       parmeters = new List <WebRequestParameters>();
                SortedDictionary <string, string> paras     = new SortedDictionary <string, string>();
                string orderId = order.Id.ToString();
                string status  = order.Status.ToString();
                string message = order.Message != null ? order.Message : "";
                Users  agent   = (from u in db.Users where u.Id == order.Agent_Id select u).FirstOrDefault <Users>();
                Logger.Info(string.Format("Agent {0}", agent.Email));
                if (agent == null)
                {
                    status  = "3";
                    message = "代理商账户没有找到";
                }
                string token = agent.SecurityStamp;
                paras["OrderId"] = orderId;
                paras["Status"]  = status;
                paras["Message"] = message;
                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=" + token;
                Logger.Info(string.Format("Sign String {0}", signStr));
                Logger.Info(string.Format("Signature {0}", UrlSignUtil.GetMD5(signStr)));
                paras["Signature"] = UrlSignUtil.GetMD5(signStr);
                foreach (KeyValuePair <string, string> p in paras)
                {
                    parmeters.Add(new WebRequestParameters(p.Key, p.Value, false));
                }
                ServerUri = new Uri(order.CallBackUrl);
                bool succeed = false;
                SendRequest(parmeters, false, out succeed);
                if (succeed)
                {
                    Logger.Info("Successfully sent back status to anegt callback API");
                }
                else
                {
                    Logger.Info("Failed sent back status to anegt callback API");
                }
            }
            catch (Exception ex)
            {
            }finally
            {
                if (db != null)
                {
                    db.Dispose();
                }

                Logger.Info("Leaving SendStatusBackToAgentCallback");
            }
        }
예제 #15
0
        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);
        }
예제 #16
0
        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);
        }
예제 #17
0
        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!");
        }