Esempio n. 1
0
        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;
        }
Esempio n. 2
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.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;
        }
Esempio n. 3
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.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("回调数据中没有本系统的订单号,所以不能更新本系统数据,此次调用为脏数据");
            }
        }
Esempio n. 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>();

                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;
        }
Esempio n. 5
0
        // GET: PayBack此方法仅供直冲用户支付宝支付完成回调以及支付宝充值账户回调
        public ActionResult AlipayBack()
        {
            SortedDictionary<string, string> sPara = GetRequestGet();
            ChargeResult result = new ChargeResult() { Status= ChargeStatus.FAILED };
            if (sPara.Count > 0)//判断是否有带返回参数
            {
                AlipayConfig config = new AlipayConfig(System.IO.Path.Combine(Request.PhysicalApplicationPath, "Config\\AliPayConfig.xml"));
                Notify aliNotify = new Notify(config);
                bool verifyResult = aliNotify.Verify(sPara, Request.QueryString["notify_id"], Request.QueryString["sign"]);

                if (verifyResult)//验证成功
                {
                    //本地系统支付号
                    string out_trade_no = Request.QueryString["out_trade_no"];
                    int paymentId = 0;
                    int.TryParse(out_trade_no, out paymentId);

                    //支付宝交易号
                    string trade_no = Request.QueryString["trade_no"];

                    //买家支付宝账户
                    string buyerAccount = Request.QueryString["buyer_email"];
                    //交易状态
                    string trade_status = Request.QueryString["trade_status"];
                    if (Request.QueryString["trade_status"] == "TRADE_FINISHED" || Request.QueryString["trade_status"] == "TRADE_SUCCESS")
                    {
                        //判断该笔订单是否在商户网站中已经做过处理
                        //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序
                        //如果有做过处理,不执行商户的业务程序
                        OrderManagement orderMgr = new OrderManagement(0);
                        PaymentManagement payMgr = new PaymentManagement(0);
                        if(paymentId>0)
                        {
                            try
                            {
                                BPaymentHistory payment = null;
                                int total = 0;
                                List<BPaymentHistory> payments = payMgr.FindPayments(paymentId,0, 0,out total);
                                if(payments!=null && payments.Count==1)
                                {
                                    payment = payments[0];
                                    if(payment.PayType==0)//直冲用户支付
                                    {
                                        result = orderMgr.ProcessOrderAfterPaid(paymentId, trade_no, buyerAccount);
                                        result.Status = ChargeStatus.SUCCEED;
                                        result.Message = "支付成功,已经提交到充值系统,请耐心等待...";
                                        return Redirect("/Product/Charge?message=" + result.Message);
                                    }
                                    else if(payment.PayType==1)//代理商用户充值账户
                                    {
                                        payMgr.UpdateAccountMoneyAfterPayment(payment);
                                        return Redirect("/Agent/ChargeAccount?message=" + result.Message);
                                    }

                                }else
                                {
                                    result.Status = ChargeStatus.FAILED;
                                    result.Message = string.Format("支付号{0}在本系统中不存在",paymentId);
                                }

                            }
                            catch(KMBitException e)
                            {
                                result.Message = e.Message;
                                result.Status = ChargeStatus.FAILED;
                            }
                            catch(Exception ex)
                            {
                                result.Message = ex.Message;
                                result.Status = ChargeStatus.FAILED;
                            }
                        }
                    }
                    else
                    {
                        result.Message = string.Format("支付宝支付失败:{0}",Request.QueryString["trade_status"]);
                        result.Status = ChargeStatus.FAILED;

                        //需要删除本地系统内的支付记录或者充值订单记录TBD
                    }
                }
                else//验证失败
                {
                    result.Message = "支付宝返回数据验证失败,请不要串改支付宝返回的数据";
                    result.Status = ChargeStatus.FAILED;
                    //需要删除本地系统内的支付记录或者充值订单记录TBD
                }
            }
            else
            {
                result.Message = "支付宝没有返回任何数据,充值失败";
                result.Status = ChargeStatus.FAILED;
            }
            return Redirect("/Product/Charge?message=" + result.Message);
        }
Esempio n. 6
0
        public ActionResult DoSaoMa()
        {
            string p        = Request["p"];
            string number   = Request["mobile_number"];
            string spName   = Request["SPName"];
            string province = Request["Province"];
            string city     = Request["City"];

            if (string.IsNullOrEmpty(p))
            {
                ViewBag.Message = "参数错误,请正确扫码,输入手机号码点充值";
            }
            else
            {
                int    agentId         = 0;
                int    customerId      = 0;
                int    activityId      = 0;
                int    activityOrderId = 0;
                string parameters      = KMEncoder.Decode(p);
                if (!string.IsNullOrEmpty(parameters))
                {
                    string signature = string.Empty;
                    SortedDictionary <string, string> pvs = parseParameters(parameters, out signature);
                    if (string.IsNullOrEmpty(signature))
                    {
                        ViewBag.Message = "URL参数不正确,请重新扫码";
                        return(View("SaoMa"));
                    }
                    System.Text.StringBuilder pBuilder = new System.Text.StringBuilder();
                    if (pvs.Count > 0)
                    {
                        int count = 1;
                        foreach (KeyValuePair <string, string> pair in pvs)
                        {
                            pBuilder.Append(pair.Key);
                            pBuilder.Append("=");
                            pBuilder.Append(pair.Value);
                            if (count < pvs.Count)
                            {
                                pBuilder.Append("&");
                            }
                            count++;
                            switch (pair.Key)
                            {
                            case "agentId":
                                int.TryParse(pair.Value, out agentId);
                                break;

                            case "customerId":
                                int.TryParse(pair.Value, out customerId);
                                break;

                            case "activityId":
                                int.TryParse(pair.Value, out activityId);
                                break;

                            case "activityOrderId":
                                int.TryParse(pair.Value, out activityOrderId);
                                break;
                            }
                        }
                        CustomerManagement customerMgr = new CustomerManagement(0);
                        int total;
                        List <BCustomer> customers = customerMgr.FindCustomers(0, customerId, out total);
                        if (total <= 0 || total > 1)
                        {
                            ViewBag.Message = "URL参数不正确,请重新扫码";
                            return(View("SaoMa"));
                        }
                        pBuilder.Append("&key=");
                        pBuilder.Append(customers[0].Token);
                        string sign = UrlSignUtil.GetMD5(pBuilder.ToString());
                        if (sign != signature)
                        {
                            ViewBag.Message = "URL参数不正确,请重新扫码";
                            return(View("SaoMa"));
                        }
                        ActivityManagement activityMgr = new ActivityManagement(0);
                        BMarketOrderCharge order       = new BMarketOrderCharge()
                        {
                            ActivityId      = activityId,
                            ActivityOrderId = activityOrderId,
                            AgentId         = agentId,
                            CustomerId      = customerId,
                            City            = city,
                            Province        = province,
                            OpenId          = "",
                            Phone           = number,
                            SPName          = spName
                        };
                        KMBit.BL.Charge.ChargeResult result = activityMgr.MarketingCharge(order);
                        ViewBag.Message = result.Message;
                        //if(result.Status == ChargeStatus.FAILED)
                        //{
                        //    ViewBag.Paras = pvs;
                        //    //paras.Add("p", p);
                        //}
                    }
                }
                else
                {
                    ViewBag.Message = "不能重复扫码,或者修改扫码后的URL地址";
                }
            }

            return(View("SaoMa"));
        }
Esempio n. 7
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);
        }
Esempio n. 8
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;
        }
Esempio n. 9
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)
                        {
                            this.SendStatusBackToAgentCallback(cOrder);
                        }
                    }
                }
            }
        }
Esempio n. 10
0
        public ChargeResult ChargeCallBack(SortedDictionary<string, string> parameters)
        {
            ChargeResult result = new ChargeResult();
            if(parameters==null)
            {
                result.Status = ChargeStatus.FAILED;
                result.Message = "回调参数错误";
                return result;
            }

            string orderStrId = null;
            if(parameters.ContainsKey("transNo"))
            {
                orderStrId = parameters["transNo"];
                ICharge chargeMgr = new ChongBaCharge();
                List<WebRequestParameters> paramters = new List<WebRequestParameters>();
                paramters.Add(new WebRequestParameters("orderId", parameters["orderId"], false));
                paramters.Add(new WebRequestParameters("respCode", parameters["respCode"], false));
                paramters.Add(new WebRequestParameters("respMsg", parameters["respMsg"], false));
                paramters.Add(new WebRequestParameters("transNo", parameters["transNo"], false));
                chargeMgr.CallBack(paramters);
                result.Status = ChargeStatus.SUCCEED;
                result.Message = "回调成功";
            }
            return result;
        }
Esempio n. 11
0
        public ChargeResult ImportResourceProducts(int resourceId,int operate_user)
        {
            ChargeResult result = new ChargeResult() { Status= ChargeStatus.SUCCEED };
            ICharge chargeMgr = null;
            chargebitEntities db = new chargebitEntities();
            try
            {
                KMBit.DAL.Resource resource = (from ri in db.Resource
                                               where ri.Id==resourceId
                                               select ri).FirstOrDefault<Resource>();

                if (resource == null)
                {
                    throw new KMBitException(string.Format("编号为{0}的资源不存在",resourceId));
                }
                if (!resource.Enabled)
                {
                    throw new KMBitException(string.Format("编号为{0}的资源没有启用,请先启用在进行资源产品导入", resourceId));
                }

                KMBit.DAL.Resrouce_interface rInterface = (from ri in db.Resrouce_interface where ri.Resource_id == resourceId select ri).FirstOrDefault<Resrouce_interface>();
                if (rInterface == null)
                {
                    throw new KMBitException(string.Format("编号为{0}的资源没有配置资源接口,请先配置资源接口,并配置产品导入接口URL,然后进行资源产品导入", resourceId));
                }
                object o = null;
                Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
                Type type = assembly.GetType(rInterface.Interface_classname);
                o = Activator.CreateInstance(type);
                if (o!=null)
                {
                    chargeMgr = (ICharge)o;
                    chargeMgr.ImportProducts(resourceId, operate_user);
                }
            }
            catch(Exception ex)
            {
                result.Status = ChargeStatus.FAILED;
                result.Message = ex.Message;

            }finally
            {
                if(db!=null)
                {
                    db.Dispose();
                }
            }

            return result;
        }
Esempio n. 12
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;
        }
Esempio n. 13
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);
        }
Esempio n. 14
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!");
        }
Esempio n. 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);
        }
Esempio n. 16
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!");
            }
        }
Esempio n. 17
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("回调数据中没有本系统的订单号,所以不能更新本系统数据,此次调用为脏数据");
            }
        }
Esempio n. 18
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)
        {
            logger.Info(this.GetType().FullName+ ".ProcessOrderAfterPaid..........................");
            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.SUCCEED;
                    result.Message = string.Format("编号为:{0}的支付编号不存在", paymentId);
                    return result;
                }
                if(payment.PayType==3)
                {
                    //管理员后台充值,不是网络支付
                    result.Status = ChargeStatus.SUCCEED;
                    result.Message = "不是网络支付,不能同步";
                    return result;
                }
                if(!string.IsNullOrEmpty(payment.PaymentTradeId))
                {
                    result.Status = ChargeStatus.SUCCEED;
                    result.Message = "已经处理过,不能再次处理";
                    logger.Info(result.Message);
                    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.SUCCEED;
                        result.Message = string.Format("编号为:{0}的支付编号没有相关充值订单", paymentId);
                        logger.Info(result.Message);
                        return result;
                    }

                    //status 10 means the order is payed and ready for charge process.
                    Charge_Order corder = (from o in db.Charge_Order where o.Id==payment.ChargeOrderId select o).FirstOrDefault<Charge_Order>();
                    if(corder==null)
                    {
                        result.Status = ChargeStatus.SUCCEED;
                        result.Message = string.Format("编号为:{0}充值订单不存在", payment.ChargeOrderId);
                        logger.Info(result.Message);
                        return result;
                    }
                    if(corder.Payed)
                    {
                        result.Status = ChargeStatus.SUCCEED;
                        result.Message = string.Format("编号为:{0}充值订单已经处理过", payment.ChargeOrderId);
                        logger.Info(result.Message);
                        return result;
                    }
                    corder.Payed = true;
                    corder.Status = 10;
                    corder.Message = "充值订单已成功提交到充值系统,请耐性等待充值...";
                    logger.Info(corder.Message);
                    db.SaveChanges();
                    result.Status = ChargeStatus.SUCCEED;
                    result.Message = corder.Message;
                    //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);
                }
            }
            logger.Info("Done ProcessOrderAfterPaid..........................");
            return result;
        }
Esempio n. 19
0
        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);
        }
Esempio n. 20
0
        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;
        }
Esempio n. 21
0
        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;
        }
Esempio n. 22
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!");
        }