#pragma warning disable CS0246 // The type or namespace name 'Success' could not be found (are you missing a using directive or an assembly reference?)
        internal static Success SaveOrder(int userID, IShoppingCart cart)
#pragma warning restore CS0246 // The type or namespace name 'Success' could not be found (are you missing a using directive or an assembly reference?)
        {
            IOrderTransaction order = new OrderTransaction();

            try
            {
                order.StartTransaction(userID);

                foreach (KeyValuePair <IProduct, int> product in cart.CartItems)
                {
                    order.AddToOrder(product.Key, product.Value);
                }

                order.Commit();

                return(new Success(true, "Order saved successfully"));
            }
            catch
            {
                order.Revert();

                return(new Success(false, "Order failed, try again"));
            }
        }
Ejemplo n.º 2
0
        public static CreateOrderCommand ToCommand(OrderTransaction transaction)
        {
            if (transaction == null)
            {
                throw new ArgumentNullException(nameof(transaction));
            }

            return(new CreateOrderCommand
            {
                TransactionId = transaction.Id,
                UserId = transaction.OrderDetails.UserId,
                Order = new Order
                {
                    Items = transaction
                            .OrderDetails
                            .Items
                            .Select(i => new Operations.DataStructures.OrderItem
                    {
                        ProductId = i.ProductId,
                        Quantity = i.Quantity
                    })
                            .ToList()
                },
                Address = new Operations.DataStructures.Address
                {
                    City = transaction.OrderDetails.Address.City,
                    Country = transaction.OrderDetails.Address.Country,
                    House = transaction.OrderDetails.Address.House,
                    State = transaction.OrderDetails.Address.State,
                    Street = transaction.OrderDetails.Address.Street,
                    Zip = transaction.OrderDetails.Address.Zip
                }
            });
        }
 private void SchedulerCallback()
 {
     using (var myContext = new MyContext())
     {
         var UserManager = new ApplicationUserManager(new UserStore <ApplicationUser>(MyContext));
         var users       = (from u in myContext.Users where u.Status = StatusFlag.PlaceOrder select u.User).ToList();
         foreach (var user in users)
         {
             myContext.Order.Add(new MyOrder());
             myContext.Order.User = user;
             OrderTransaction transaction = new OrderTransaction();
             order.Transactions = new List <OrderTransaction>();
             order.Transactions.Add(transaction);
             user.Status = StatusFlag.OrderPlaced;
         }
         try
         {
             myContext.SaveChanges();
         }
         catch (Exception e)
         {
             Logger.LogError("Exception", e);
         }
     }
 }
Ejemplo n.º 4
0
        public void TransactionHistoryAddsOK()
        {
            OrderTransaction trans = new OrderTransaction();

            trans.Direction = OrderDirection.Buy;
            p.TransactionHistory.Add(trans);
            Assert.IsTrue(p.TransactionHistory.Count > 0);
        }
Ejemplo n.º 5
0
 private OrderStatus MapToOrderStatus(OrderTransaction orderTransaction, bool isDelivered)
 {
     return(new OrderStatus
     {
         OrderNumber = orderTransaction.OrderNumber.ToString(),
         IsDelivered = isDelivered
     });
 }
Ejemplo n.º 6
0
 private OrderConfirmation MapToOrderConfirmation(OrderTransaction orderTransaction)
 {
     return(new OrderConfirmation
     {
         OrderNumber = orderTransaction.OrderNumber.ToString(),
         ShipmentNumber = orderTransaction.ShipmentConfirmationNumber
     });
 }
Ejemplo n.º 7
0
        public void OpenTradesAddsOk()
        {
            OrderTransaction trans = new OrderTransaction();

            trans.Direction = OrderDirection.Buy;
            p.OpenTrades.Add(trans);
            Assert.IsTrue(p.OpenTrades.Count > 0);
        }
 private bool HasSuccessfulLinkedAction(List <OrderTransaction> transactions, OrderTransaction info,
                                        long lineItemId)
 {
     return(transactions.Any(t => t.Success && !t.Voided &&
                             t.Action == ActionType.RecurringSubscriptionCreate &&
                             t.LinkedToTransaction == info.IdAsString &&
                             t.RefNum2 == lineItemId.ToString()));
 }
Ejemplo n.º 9
0
        public void OpenPositionOpensABuyPositionPosition()
        {
            OrderTransaction trans = new OrderTransaction();

            trans.Direction = OrderDirection.Buy;
            trans.Symbol    = "AAPL";
            p.ProcessTransaction(trans);
            Assert.IsTrue(p.OpenPositions.Count > 0);
        }
Ejemplo n.º 10
0
        public void NoOpenPositionsReturnNull()
        {
            OrderTransaction trans = new OrderTransaction();

            trans.Symbol = "AAPL";
            IPositionInventory openPosition = p.OpenPositions.FirstOrDefault(s => s.GetSymbol() == trans.Symbol);

            Assert.IsNull(openPosition);
        }
Ejemplo n.º 11
0
        public void MatchedAndUnmatchedTransactions()
        {
            string path     = @"C:\Users\Nick\Documents\Visual Studio 2013\Projects\LeanITrend\Engine\bin\Debug\";
            string pathname = path + "transactions.csv";
            // This part of the test is just to look at the JsonConvert
            //string txt;
            //using (StreamReader sr = new StreamReader(pathname))
            //{
            //    txt = sr.ReadToEnd();
            //    sr.Close();
            //}
            //int index = txt.IndexOf("\r\n", System.StringComparison.Ordinal);
            //string titlesremoved = txt.Substring(index + 2);

            int counter = 0;
            List <OrderTransaction> list = new List <OrderTransaction>();

            OrderTransactionProcessor processor = new OrderTransactionProcessor();

            using (StreamReader sr = new StreamReader(pathname))
            {
                string line = sr.ReadLine();    // read the header but do not count it.

                while (!sr.EndOfStream)
                {
                    line = sr.ReadLine();
                    if (line != null && line.Contains("Symbol"))
                    {
                        continue;
                    }
                    Assert.IsNotNull(line);
                    counter++;
                    OrderTransaction t = new OrderTransaction();
                    CsvSerializer.Deserialize(",", line, ref t, false);
                    list.Add(t);
                    processor.ProcessTransaction(t);
                }
                sr.Close();
            }
            var csv = CsvSerializer.Serialize(",", processor.Trades, true);

            using (StreamWriter sw = new StreamWriter(path + "Trades.csv"))
            {
                foreach (var s in csv)
                {
                    sw.WriteLine(s);
                }
                sw.Flush();
                sw.Close();
            }
            var x = JsonConvert.SerializeObject(list);

            Assert.IsTrue(counter == list.Count);
            Assert.IsTrue(processor.TotalProfit == 52.75m);
            Assert.IsTrue(processor.TotalCommission == -26m);
        }
Ejemplo n.º 12
0
        public void FifoAddsBuy()
        {
            OrderTransaction trans = new OrderTransaction();

            trans.Direction = OrderDirection.Buy;
            fifo.Add(trans);
            Assert.IsTrue(fifo.Buys.Count == 1);
            fifo.Remove(Buy);
            Assert.IsTrue(fifo.Buys.Count == 0);
        }
Ejemplo n.º 13
0
        public void LifoAddsBuy()
        {
            OrderTransaction trans = new OrderTransaction();

            trans.Direction = OrderDirection.Buy;
            lifo.Add(trans);
            Assert.IsTrue(lifo.BuysCount() == 1);
            lifo.Remove(Buy);
            Assert.IsTrue(lifo.BuysCount() == 0);
        }
Ejemplo n.º 14
0
        public void LifoAddsSell()
        {
            OrderTransaction trans = new OrderTransaction();

            trans.Direction = OrderDirection.Sell;
            lifo.Add(trans);
            Assert.IsTrue(lifo.Sells.Count == 1);
            lifo.Remove(Sell);
            Assert.IsTrue(lifo.Sells.Count == 0);
        }
Ejemplo n.º 15
0
        private bool ProcessTransaction(OrderTaskContext context, OrderTransaction p)
        {
            bool result = true;

            try
            {
                var         payManager  = new OrderPaymentManager(context.Order, context.HccApp);
                var         orderNumber = !string.IsNullOrEmpty(p.OrderNumber) ? p.OrderNumber : context.Order.OrderNumber;
                Transaction t           = payManager.CreateEmptyTransaction();
                t.Card = p.CreditCard;
                t.Card.SecurityCode = context.Inputs.GetProperty("hcc", "CardSecurityCode");
                t.Amount            = p.Amount;
                t.Items             = GetLineItemsForTransaction(context, orderNumber);

                if (context.HccApp.CurrentStore.Settings.PaymentCreditCardAuthorizeOnly)
                {
                    t.Action = ActionType.CreditCardHold;
                }
                else
                {
                    t.Action = ActionType.CreditCardCharge;
                }

                PaymentGateway proc = PaymentGateways.CurrentPaymentProcessor(context.HccApp.CurrentStore);
                proc.ProcessTransaction(t);

                OrderTransaction ot = new OrderTransaction(t);
                ot.LinkedToTransaction = p.IdAsString;
                context.HccApp.OrderServices.AddPaymentTransactionToOrder(context.Order, ot);

                if (!t.Result.Succeeded || t.Action == ActionType.CreditCardIgnored)
                {
                    foreach (var m in t.Result.Messages)
                    {
                        if (m.Severity == MessageType.Error ||
                            m.Severity == MessageType.Warning)
                        {
                            context.Errors.Add(new WorkflowMessage("Payment Error:", m.Description, true));
                        }
                    }
                    result = false;
                }
            }
            catch (Exception ex)
            {
                context.Errors.Add(new WorkflowMessage("Exception During Receive Credit Card", ex.Message + ex.StackTrace, false));
                OrderNote note = new OrderNote();
                note.IsPublic = false;
                note.Note     = "EXCEPTION: " + ex.Message + " | " + ex.StackTrace;
                context.Order.Notes.Add(note);
            }

            return(result);
        }
Ejemplo n.º 16
0
        public async Task <bool> CheckIfIsDelivered(OrderTransaction orderTransaction)
        {
            var requestUri = $"{uriApiRelative}/{orderTransaction.ShipmentConfirmationNumber}";
            var response   = await httpClient
                             .GetAsync(requestUri)
                             .ConfigureAwait(false);

            var shipmentResponse = await GetShipmentResponseData(response)
                                   .ConfigureAwait(false);

            return(shipmentResponse.IsDelivered);
        }
Ejemplo n.º 17
0
        public void CanOpenPosition()
        {
            OrderTransaction trans = new OrderTransaction();

            trans.Symbol    = "AAPL";
            trans.Direction = OrderDirection.Buy;
            OrderTransactionProcessor processor    = new OrderTransactionProcessor();
            IPositionInventory        openPosition = processor.OpenPosition(trans, PositionInventoryMethod.Fifo);

            processor.OpenPositions.Add(openPosition);
            Assert.IsTrue(processor.OpenPositions.Count > 0);
        }
        private void CashReceive(HotcakesApplication app, OrderPaymentManager pm, decimal amount, Order o)
        {
            var t = pm.CreateEmptyTransaction();

            t.Amount = amount;
            t.Action = ActionType.CashReceived;
            var ot = new OrderTransaction(t)
            {
                Success = true, TimeStampUtc = o.TimeOfOrderUtc
            };

            app.OrderServices.AddPaymentTransactionToOrder(o, ot);
        }
Ejemplo n.º 19
0
        public async Task <string> HandleAsync(RegisterOrderCommand command, CancellationToken cancellationToken)
        {
            var transactionId = guidProvider.GenerateGuidString();

            using (var session = documentStore.OpenAsyncSession())
            {
                var transactionDocumentId = DocumentIdHelper.GetDocumentId <OrderTransaction>(documentStore, transactionId);
                var transactionDocument   = new OrderTransaction
                {
                    Id = transactionDocumentId,
                    TransactionStatus = TransactionStatus.NotStarted,
                    LoyaltyPointsConsumptionStepDetails = new StepDetails
                    {
                        Attempts         = 0,
                        RollbackAttempts = 0,
                        StepStatus       = StepStatus.NotStarted
                    },
                    DeliveryCreationStepDetails = new StepDetails
                    {
                        Attempts         = 0,
                        RollbackAttempts = 0,
                        StepStatus       = StepStatus.NotStarted
                    },
                    InventoryReservationStepDetails = new StepDetails
                    {
                        Attempts         = 0,
                        RollbackAttempts = 0,
                        StepStatus       = StepStatus.NotStarted
                    },
                    OrderTotalStepDetails = new OrderTotalStepDetails
                    {
                        Attempts         = 0,
                        RollbackAttempts = 0,
                        StepStatus       = StepStatus.NotStarted,
                        Total            = 0
                    },
                    OrderDetails = new OrderDetails
                    {
                        UserId  = command.UserId,
                        Address = AddressMapper.ToEntity(command.Address),
                        Items   = OrderMapper.ToEntities(command.Order)
                    }
                };

                await session.StoreAsync(transactionDocument, cancellationToken).ConfigureAwait(false);

                await session.SaveChangesAsync().ConfigureAwait(false);
            }

            return(transactionId);
        }
        protected void lnkPayPalCaptureHold_Click(object sender, EventArgs e)
        {
            this.MessageBox1.ClearMessage();
            string  transactionId = this.lstPayPalHold.SelectedItem.Value;
            decimal amount        = ParseMoney(this.PayPalHoldAmount.Text);

            if (this.PayPalHoldAmount.Text.Trim() == string.Empty)
            {
                OrderTransaction authTrans = payManager.FindTransactionById(transactionId);
                amount = authTrans.Amount;
            }
            ShowTransaction(payManager.PayPalExpressCapture(transactionId, amount));
            LoadPayPalLists();
        }
Ejemplo n.º 21
0
 public void CopyToPayment(OrderTransaction ot)
 {
     ot.CreditCard.ExpirationMonth = ExpirationMonth;
     ot.CreditCard.ExpirationYear  = ExpirationYear;
     ot.CreditCard.CardHolderName  = CardHolderName;
     if (CardNumber.StartsWith("*") == false)
     {
         ot.CreditCard.CardNumber = CardNumber;
     }
     ot.CreditCard.SecurityCode = SecurityCode;
     //if (ccissuenumber.Text.Trim() != string.Empty) {
     //    ot.CustomPropertySet("bvsoftware", "issuenumber", ccissuenumber.Text);
     //}
 }
        protected void lnkPointsRefund_Click(object sender, EventArgs e)
        {
            this.MessageBox1.ClearMessage();
            string  transactionId = this.lstPointsRefundable.SelectedItem.Value;
            decimal amount        = ParseMoney(this.PointsRefundAmount.Text);

            if (this.PointsRefundAmount.Text.Trim() == string.Empty)
            {
                OrderTransaction refTrans = payManager.FindTransactionById(transactionId);
                amount = refTrans.Amount;
            }
            ShowTransaction(payManager.RewardsPointsRefund(transactionId, amount));
            LoadPointsLists();
        }
        protected void lnkCreditCardCaptureAuth_Click(object sender, EventArgs e)
        {
            this.MessageBox1.ClearMessage();
            string  transactionId = this.lstCreditCardAuths.SelectedItem.Value;
            decimal amount        = ParseMoney(this.CreditCardAuthAmount.Text);

            if (this.CreditCardAuthAmount.Text.Trim() == string.Empty)
            {
                OrderTransaction authTrans = payManager.FindTransactionById(transactionId);
                amount = authTrans.Amount;
            }
            ShowTransaction(payManager.CreditCardCapture(transactionId, amount));
            LoadCreditCardLists();
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Logs the OrderEvent Transaction
        /// </summary>
        /// <param name="orderEvent">the OrderEvent being logged</param>
        /// <param name="includeHeader">Includes the field names</param>
        public OrderTransaction Create(OrderEvent orderEvent, OrderTicket ticket, bool includeHeader = true)
        {
            var security = _algorithm.Securities[ticket.Symbol];

            Order            order = _algorithm.Transactions.GetOrderById(orderEvent.OrderId);
            OrderTransaction t     = new OrderTransaction();

            // According to Scottrade a Buy is a negative amount (funds flow from my account to the seller's)
            //  However the Quantity filled is a negative number for Sell/Short and a positive for Buy/Long
            //  So multiply by -1 to give order value the correct sign
            decimal orderValue = -1 * ticket.QuantityFilled * ticket.AverageFillPrice;

            if (order != null)
            {
                var      orderDateTime = _algorithm.Time;
                DateTime settleDate    = orderDateTime.AddDays(orderDateTime.DayOfWeek < DayOfWeek.Wednesday ? 3 : 5);

                // Order Fees are a cost and negative to my account, therefore a negative number
                var orderFees = security.TransactionModel.GetOrderFee(security, order) * -1;

                #region "Create OrderTransaction"

                t.ActionId     = orderEvent.Direction.ToString() == "Buy" ? 1 : 13;
                t.ActionNameUS = orderEvent.Direction.ToString();
                t.Amount       = orderValue;
                t.Broker       = "IB";
                t.CUSIP        = "CUSIP";
                t.Commission   = orderFees;
                t.Description  = string.Format("{0} {1} shares of {2} at ${3}", orderEvent.Direction, ticket.Quantity, orderEvent.Symbol, order.Price);
                t.Direction    = orderEvent.Direction;
                t.Exchange     = "";
                t.Fees         = 0; // need to calculate based upon difference in Portfolio[symbol].HoldingsValue between buy and sell
                t.Id           = 0;
                t.Interest     = 0;
                t.Net          = orderValue + orderFees;
                t.OrderId      = order.Id;
                t.OrderType    = ticket.OrderType;
                t.Price        = ticket.AverageFillPrice;
                t.Quantity     = ticket.Quantity;
                t.RecordType   = "Trade";
                t.SettledDate  = settleDate;
                t.Symbol       = ticket.Symbol;
                t.TaxLotNumber = String.Empty;
                t.TradeDate    = orderDateTime;
                t.TradeNumber  = 0;
                #endregion
            }
            return(t);
        }
Ejemplo n.º 25
0
 public ActionResult Cardinfo(decimal finalamt = 0.0M, long cardno = 0, int cvv = 0, string expdate = "")
 {
     finalamt = Convert.ToDecimal(Session["finalamt"]);
     cardno   = Convert.ToInt64(Request.Form["txtcardno"]);
     cvv      = Convert.ToInt32(Request.Form["txtcvv"]);
     expdate  = Request.Form["ddlmonth"].ToString() + "/" + Request.Form["ddlyear"].ToString();
     try {
         localhost.CardInfoService svc = new localhost.CardInfoService();
         var res = svc.ProcessPayment(cardno, cvv, expdate, finalamt);
         if (string.IsNullOrEmpty(res))
         {
             ModelState.AddModelError("", "Error Adding Service");
         }
         else
         {
             ModelState.AddModelError("", res);
             OrderInfo info = new OrderInfo();
             info.OrderDate = DateTime.Now;
             info.PersonID  = Convert.ToInt32(Session["pid"]);
             info.Status    = "Payment Done";
             info.TotAmount = Convert.ToDecimal(Session["finalamt"]);
             db.OrderInfoes.Add(info);
             var r = db.SaveChanges();
             if (r > 0)
             {
                 int orderid = db.OrderInfoes.Max(x => x.OrderId);
                 lst = (List <ShoppingCartList>)Session["lst"];
                 foreach (var d in lst)
                 {
                     OrderTransaction ot = new OrderTransaction();
                     ot.OrderID = orderid;
                     ot.pid     = d.PID;
                     ot.qty     = d.Qty;
                     db.OrderTransactions.Add(ot);
                 }
                 var op = db.SaveChanges();
                 if (op > 0)
                 {
                     ModelState.AddModelError("", "Order Placed Successfully");
                 }
             }
         }
     }
     catch (Exception ex)
     {
         ModelState.AddModelError("", ex.Message);
     }
     return(View(lst));
 }
Ejemplo n.º 26
0
        private void SavePaymentInfo(CheckoutViewModel model, MonerisHPPResponse monerisResponse)
        {
            var orderTransaction = new OrderTransaction
            {
                Success  = true,
                MethodId = PaymentMethods.MonerisId,
                OrderId  = model.CurrentOrder.bvin,
                Amount   = monerisResponse.ChargeTotal,
                Action   = ActionType.ThirdPartyPayMethodCharge,
                RefNum1  = monerisResponse.ResponseOrderId,
                RefNum2  = monerisResponse.BankTransactionId
            };

            HccApp.OrderServices.AddPaymentTransactionToOrder(model.CurrentOrder, orderTransaction);
        }
Ejemplo n.º 27
0
        private void SavePaymentInfo(CheckoutViewModel model, OgoneResponse ogoneReponse)
        {
            var orderTransaction = new OrderTransaction
            {
                Success  = true,
                MethodId = PaymentMethods.OgoneId,
                OrderId  = model.CurrentOrder.bvin,
                Amount   = ogoneReponse.Amount,
                Action   = ActionType.ThirdPartyPayMethodCharge,
                RefNum1  = ogoneReponse.PaymentMethod + " " + ogoneReponse.OrderId,
                RefNum2  = ogoneReponse.PayId
            };

            HccApp.OrderServices.AddPaymentTransactionToOrder(model.CurrentOrder, orderTransaction);
        }
Ejemplo n.º 28
0
        public void InterfaceOk()
        {
            OrderTransaction trans = new OrderTransaction();

            trans.Direction = OrderDirection.Buy;
            IPositionInventory lifo = new PositionInventoryLifo();

            lifo.Add(trans);
            var count = lifo.BuysCount();

            Assert.IsTrue(lifo.BuysCount() == 1);
            trans = lifo.RemoveBuy();
            Assert.IsNotNull(trans);
            Assert.IsTrue(lifo.BuysCount() == 0);
        }
Ejemplo n.º 29
0
        private void SavePaymentInfo(CheckoutViewModel model)
        {
            var orderTransaction = new OrderTransaction
            {
                Success  = true,
                MethodId = MyPaymentMethod.Id(),
                OrderId  = model.CurrentOrder.bvin,
                Amount   = model.CurrentOrder.TotalGrandAfterStoreCredits(HccApp.OrderServices),
                Action   = ActionType.ThirdPartyPayMethodCharge,
                RefNum1  = string.Empty,
                RefNum2  = string.Empty
            };

            HccApp.OrderServices.AddPaymentTransactionToOrder(model.CurrentOrder, orderTransaction, HccApp);
        }
Ejemplo n.º 30
0
        public async Task <IHttpActionResult> CreateOrder(Order order)
        {
            try
            {
                string shipmentNumber = await shipmentProxy.OrderShipmentAsync(order.Customer);

                var orderTransaction = new OrderTransaction(order, shipmentNumber);
                orderRepository.Add(orderTransaction);

                return(Ok(MapToOrderConfirmation(orderTransaction)));
            }
            catch (ShipmentException)
            {
                return(BadRequest());
            }
        }
Ejemplo n.º 31
0
        public async Task<ActionResult> Payment(int id, string stripeToken, string stripeEmail)
        {
            var selectQuery = await _orderService.Query(x => x.ID == id).Include(x => x.Item).SelectAsync();

            // Check if order exists
            var order = selectQuery.FirstOrDefault();
            if (order == null)
                return new HttpNotFoundResult();

            var stripeConnectQuery = await _stripConnectService.Query(x => x.UserID == order.UserProvider).SelectAsync();
            var stripeConnect = stripeConnectQuery.FirstOrDefault();

            if (stripeConnect == null)
                return new HttpNotFoundResult();

            //https://stripe.com/docs/checkout
            var charge = new StripeChargeCreateOptions();

            // always set these properties
            charge.Amount = order.PriceInCents;
            charge.Currency = CacheHelper.Settings.Currency;
            charge.Card = new StripeCreditCardOptions()
            {
                TokenId = stripeToken
            };

            // set booking fee
            var bookingFee = (int)Math.Round(CacheHelper.Settings.TransactionFeePercent * order.PriceInCents);
            if (bookingFee < CacheHelper.Settings.TransactionMinimumFee * 100)
                bookingFee = (int)(CacheHelper.Settings.TransactionMinimumFee * 100);

            charge.ApplicationFee = bookingFee;
            charge.Capture = false;
            charge.Description = order.Description;
            charge.Destination = stripeConnect.stripe_user_id;
            var chargeService = new StripeChargeService(CacheHelper.GetSettingDictionary(Enum_SettingKey.StripeApiKey).Value);
            StripeCharge stripeCharge = chargeService.Create(charge);

            // Update order status
            order.Status = (int)Enum_OrderStatus.Pending;
            _orderService.Update(order);

            // Save transaction
            var transaction = new OrderTransaction()
            {
                OrderID = id,
                ChargeID = stripeCharge.Id,
                StripeEmail = stripeEmail,
                StripeToken = stripeToken,
                Created = DateTime.Now,
                LastUpdated = DateTime.Now,
                FailureCode = stripeCharge.FailureCode,
                FailureMessage = stripeCharge.FailureMessage,
                ObjectState = Repository.Pattern.Infrastructure.ObjectState.Added
            };

            _orderTransactionService.Insert(transaction);

            await _unitOfWorkAsync.SaveChangesAsync();

            ClearCache();

            // Payment succeeded
            if (string.IsNullOrEmpty(stripeCharge.FailureCode))
            {
                TempData[TempDataKeys.UserMessage] = "Thanks for your order! You payment will not be charged until the provider accepted your request.";
                return RedirectToAction("Orders", "Payment");
            }
            else
            {
                TempData[TempDataKeys.UserMessageAlertState] = "bg-danger";
                TempData[TempDataKeys.UserMessage] = stripeCharge.FailureMessage;

                return RedirectToAction("Payment");
            }
        }