/// <summary>
 /// Initializes a new instance of the <see cref="UpdatePaymentRequest"/> class.
 /// </summary>
 /// <param name="idempotencyKey">idempotency_key.</param>
 /// <param name="payment">payment.</param>
 public UpdatePaymentRequest(
     string idempotencyKey,
     Models.Payment payment = null)
 {
     this.Payment        = payment;
     this.IdempotencyKey = idempotencyKey;
 }
        public async Task <IActionResult> CreatePayment(string Amount, string Currency)
        {
            try
            {
                var user = await _userManager.GetUserAsync(User);

                var transaction = _paymentService.GetTransactionByUserId(user.Id);
                if (transaction != null)
                {
                    double addAmount = double.Parse(Amount);
                    double tAmount   = double.Parse(transaction.amount);
                    tAmount               += addAmount;
                    transaction.amount     = tAmount.ToString();
                    transaction.expireDate = transaction.expireDate.AddDays(365);
                    _paymentService.UpdateTransaction(transaction);
                }
                else
                {
                    // create transaction
                    var paymentDB = new Models.Payment()
                    {
                        userId     = Guid.Parse(user.Id),
                        amount     = Amount,
                        currency   = Currency,
                        expireDate = DateTime.Now.ToUniversalTime().AddDays(365)
                    };
                    _paymentService.AddTransaction(paymentDB);
                }
                return(RedirectToAction("Index", "Home"));
            }catch (Exception e)
            {
                throw e;
            }
        }
예제 #3
0
        public IActionResult ProcessPayment(Models.Payment payment)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var ps = new PaymentStatus();
                    ps.Payment = _mapper.Map <DB.Payment>(payment);
                    ps.Status  = DB.Enums.PaymentStatuses.Pending;
                    _unitOfWork.PaymentStatuses.InsertPaymentStatus(ps);

                    ICommand cmd       = _invoker.GetCommand((double)payment.Amount);
                    bool     isSuccess = cmd.Execute();
                    if (isSuccess)
                    {
                        ps.Status = DB.Enums.PaymentStatuses.Processed;
                        _unitOfWork.Commit();
                        return(Ok(new { Message = "Payment succeeded" }));
                    }
                    else
                    {
                        ps.Status = DB.Enums.PaymentStatuses.Failed;
                        _unitOfWork.Commit();
                        return(Problem("Internal Server Error!"));
                    }
                }
                return(ValidationProblem("The request is invalid!"));
            }
            catch (Exception ex)
            {
                _logger.LogError("Exception in Payment/ProcessPayment : " + ex.Message);
            }
            return(Problem());
        }
예제 #4
0
        public Task <PaymentProcessingResults> InitiatePayment(Models.Payment payment)
        {
            var status = PaymentStatus.Declined;

            if (_mockedCards != null)
            {
                foreach (var card in _mockedCards)
                {
                    if (card.Value == payment.CardNumber)
                    {
                        var statusName = card.Key.Replace("BankProvider:MockCardNumber", "");
                        Enum.TryParse(statusName, out status);

                        break;
                    }
                }
            }

            return(Task.FromResult(new PaymentProcessingResults
            {
                PaymentStatus = status,
                Error = PaymentProcessingErrorCodes.none,
                BankIdentifier = Guid.NewGuid().ToString()
            }));
        }
예제 #5
0
        public void DefaultValues()
        {
            var p = new Models.Payment();

            var defaultPaymentOption = PaymentHelpers.FirstPaymentOptions[0];

            Assert.AreEqual(defaultPaymentOption.Option, p.FirstPaymentOption.Option);
            Assert.AreEqual(defaultPaymentOption.Description, p.FirstPaymentOption.Description);

            var defaultPaymentDate = PaymentHelpers.FirstPaymentDates[0];

            Assert.AreEqual(defaultPaymentDate.Option, p.FirstPaymentDate.Option);
            Assert.AreEqual(defaultPaymentDate.Description, p.FirstPaymentDate.Description);

            var defaultPaymentMethod = PaymentHelpers.PaymentMethods[0];

            Assert.AreEqual(defaultPaymentMethod.Code, p.PaymentMethod.Code);
            Assert.AreEqual(defaultPaymentMethod.Name, p.PaymentMethod.Name);
            Assert.AreEqual(defaultPaymentMethod.IsBankReceipt, p.PaymentMethod.IsBankReceipt);

            Assert.AreEqual(30, p.FirstPaymentDateAdditionalDays);
            Assert.AreEqual(1, p.Installments);
            Assert.AreEqual(30, p.InstallmentsEveryNumberOfDays);
            Assert.IsTrue(p.ShouldForceToEndOfMonth);
        }
예제 #6
0
        public void ConnectToBank(BehpardakhtMVC.Models.Basket basket)
        {
            DateTime date           = DateTime.Now.Date;
            TimeSpan time           = DateTime.Now.TimeOfDay;
            long     amount         = 1000;
            string   additionalInfo = "";
            long     payId          = 0;

            using (Models.ShopEntities1 db = new Models.ShopEntities1())
            {
                var pay = new Models.Payment();
                pay.Amount    = basket.Amount;
                pay.BasketId  = basket.Id;
                pay.PayMethod = "online-mellat";
                pay.PayStatus = 0;
                db.Payments.Add(pay);
                db.SaveChanges();
                payId = pay.Id;
            }


            int?payType = null;

            BypassCertificateError();
            string ip      = "";
            var    ressult = new Behpardakht().bpPayRequest(amount, date, time, additionalInfo, payId, ip, payType);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="CancelPaymentResponse"/> class.
 /// </summary>
 /// <param name="errors">errors.</param>
 /// <param name="payment">payment.</param>
 public CancelPaymentResponse(
     IList <Models.Error> errors = null,
     Models.Payment payment      = null)
 {
     this.Errors  = errors;
     this.Payment = payment;
 }
예제 #8
0
        public async Task <IActionResult> Payment(int idOrden)
        {
            var order = await _ordersService.GetOrder(idOrden);

            if (order == null)
            {
                return(NotFound());
            }

            Gateway gateway = _ordersService.GetGateway();

            Person person = new Person(
                document: order.CustomerDocument,
                documentType: "CC",
                name: order.CustomerName,
                surname: order.CustomerName.Replace(" ", ""),
                email: order.CustomerEmail,
                mobile: order.CustomerMobile
                );

            Amount amount = new Amount(Convert.ToDouble(order.ValorOrder), currency);

            PlacetoPay.Integrations.Library.CSharp.Entities.Payment payment = new PlacetoPay.Integrations.Library.CSharp.Entities.Payment($"TEST_{DateTime.Now:yyyyMMdd_hhmmss}_{order.Id}", $"Pago básico de prueba orden {order.Id} ", amount, false, person);
            RedirectRequest request = new RedirectRequest(payment,
                                                          urlLocalhostDetails + order.Id.ToString(),
                                                          ipAddress,
                                                          "PlacetoPay Sandbox",
                                                          (order.CreatedAt.AddMinutes(60)).ToString(formatDate),
                                                          person,
                                                          person);

            RedirectResponse response = gateway.Request(request);

            if (response.IsSuccessful())
            {
                Models.Payment pago = new Models.Payment()
                {
                    OrderId   = order.Id,
                    Fecha     = Convert.ToDateTime(response.Status.Date),
                    RequestId = Convert.ToInt32(response.RequestId),
                    UrlPago   = response.ProcessUrl,
                    Status    = response.Status.status,
                    Reason    = response.Status.Reason,
                    Message   = response.Status.Message
                };

                if (await _paymentsService.CreatePayment(pago) == 0)
                {
                    // NotFound Response Status 404.
                    return(NotFound());
                }


                return(RedirectToAction("Payment", "Orders", new { idOrden = order.Id, urlPago = response.ProcessUrl }));
            }
            else
            {
                return(RedirectToAction("Details", "Orders", new { id = order.Id, message = response.Status.Message }));
            }
        }
예제 #9
0
        public Task <Models.Payment> Get(Guid id)
        {
            Models.Payment payment = null;
            _storage.TryGetValue(id, out payment);

            return(Task.FromResult(payment));
        }
예제 #10
0
        public async Task <Models.Payment> AddPayment(PaymentRequest paymentRequest)
        {
            Models.Payment payment = null;
            payment = new Models.Payment
            {
                Amount              = paymentRequest.Amount,
                Currency            = paymentRequest.Currency,
                RequestedOn         = DateTime.Now,
                Status              = PaymentStatus.Requested,
                CardNumber          = paymentRequest.CardNumber,
                Cvv                 = paymentRequest.Cvv,
                ExpiryDate          = paymentRequest.ExpiryDate,
                IdempotencyUniqueId = UniqueIdempotencyId(paymentRequest)
            };

            if (await _paymentRepository.Add(payment) == StoreNewPaymentResult.DuplicateUniqueIdempotencyId)
            {
                return(await _paymentRepository.GetByIdempotencyKey(payment.IdempotencyUniqueId));
            }

            var response = await _bankClient.InitiatePayment(payment);

            payment.Status         = response.PaymentStatus;
            payment.BankIdentifier = response.BankIdentifier;

            await _paymentRepository.Update(payment);

            return(payment);
        }
 public IHttpActionResult Pay(Models.Payment payment)
 {
     if (BussinessLogic.Payment.Pay(payment.PayUser, payment.Sum))
     {
         return(Ok());
     }
     return(InternalServerError());
 }
예제 #12
0
        private async void PaymentButton_OnClick(object sender, RoutedEventArgs e)
        {
            try
            {
                //Guardo el modelo de pago
                var amount   = CurrentAmount - int.Parse(AmounTxt.Text);
                var abonated = int.Parse(AmounTxt.Text);
                var payment  = new Models.Payment
                {
                    Supplier = SupplierNameTxt.Text,
                    Concept  = ConceptTxt.Text,
                    Amount   = int.Parse(AmounTxt.Text),
                    State    = amount.Equals(0) ? "Completado" : "Abonado"
                };

                await payment.SaveAsync();

                //Actualizar el documento, si el balance abonado es el total a pagar, entonces el balance será 0, por ende pasa de pendiente a pagado
                var document = await new ParseQuery <Models.DocumentEntry>()
                               .Where(p => p.ObjectId.Equals(ID)).FirstAsync();

                document.Amount = amount;
                document.Status = (amount.Equals(0)) ? "pagado" : "pendiente";

                await document.SaveAsync();

                //Actualizar el balance total  de cada suplidor. El balance total es la suma de todos los documentos pendientes
                //Retira una lista de balance de los documentos donde exista un suplidor N
                var sumOfDocuments =
                    await new ParseQuery <Models.DocumentEntry>()
                    .Where(d => d.Supplier.Equals(payment.Supplier)).FindAsync();

                var listOfDocumentBalance = sumOfDocuments.Sum(sum => sum.Amount);
                var updateSupplier        = await new ParseQuery <Models.Supplier>()
                                            .Where(o => o.Name.Equals(payment.Supplier)).FirstAsync(); //Como no existe dos veces un suplidor. Busco el objeto por el nombre

                updateSupplier.Balance -= int.Parse(AmounTxt.Text);                                    //Actualizo su balance
                await updateSupplier.SaveAsync();

                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://contabilidadservice.azurewebsites.net/");
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    var accountEntry  = new { entradasContables = new { descripcion = ConceptTxt.Text, auxiliar = 1, cuenta = 8, tipoMovimiento = "CR", monto = AmounTxt.Text, moneda = 1 } };
                    var json          = new JavaScriptSerializer().Serialize(accountEntry);
                    var stringContent = new StringContent(json, Encoding.UTF8, "application/json");

                    var response = client.PostAsync("ContabilidadWS/webresources/ContabilidadWS/registrarAsientos", stringContent).Result;
                    MessageBox.Show(response.Content.ReadAsStringAsync().Result);
                }
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
예제 #13
0
 internal static DirectPaymentViewModel Create(Models.Payment payment, Models.Checkout checkout)
 {
     return(new DirectPaymentViewModel
     {
         Name = checkout.Name,
         Amount = checkout.Amount,
         State = payment.State,
     });
 }
예제 #14
0
        public Task <bool> Update(Models.Payment payment)
        {
            if (payment.Id.HasValue)
            {
                Task.FromResult(_storage.TryUpdate(payment.Id.Value, payment, payment));
            }

            return(Task.FromResult(false));
        }
예제 #15
0
 public Models.Payment convertPayService(ServiceReference1.Payment py)
 {
     Models.Payment pay = new Models.Payment();
     pay.MaDH  = py.MaDH;
     pay.Ngay  = py.Ngay;
     pay.Phi   = py.Phi;
     pay.TenGD = py.TenGD;
     return(pay);
 }
예제 #16
0
        public ActionResult Payment(Models.Payment payment)
        {
            //set the order payment to be our payment object.
            this.MyOrder.Payment = payment;
            //save changes
            db.SaveChanges();

            //kick user to the review screen
            return(RedirectToAction("Review"));
        }
예제 #17
0
        public async Task UploadProofOfPayment(Models.Payment payment)
        {
            using (ApplicationDbContext context = new ApplicationDbContext())
            {
                var model = await context.Payment.FindAsync(payment.Id);

                model.ProofOfPayment = payment.ProofOfPayment;
                model.Status         = Constant.MagicStringReplacer.PaidStatus;
                await context.SaveChangesAsync();
            }
        }
예제 #18
0
        public void Post([FromBody] Models.Payment paymentRecord)
        {
            _logger.Log(LogLevel.Information, "Request recieved to create a new payment Record", null);

            var record = JsonConvert.SerializeObject(paymentRecord);

            System.IO.File.WriteAllText(Path.Combine(Path.GetTempPath(), "log_" + Guid.NewGuid() + ".txt"), record);

            var Id = _paymentService.CreatePayment(paymentRecord);

            _logger.Log(LogLevel.Information, "Creation of new payment Record is completed", null);
        }
예제 #19
0
 public ActionResult Finalise()
 {
     try
     {
         Models.Payment pay = new Models.Payment {
             Order = _order, Card = db.Cards.Where(c => c.Active && c.ID == ChosenCard).First()
         };
         return(View(pay));
     }
     catch
     {
         return(new StatusCodeResult(500));
     }
 }
 internal static PaymentViewModel Create(Models.Payment payment, Models.Checkout checkout)
 {
     return(new PaymentViewModel
     {
         Name = checkout.Name,
         Amount = checkout.Amount,
         PaymentMethod = checkout.PaymentMethod,
         State = payment.State,
         VirtualBankAccount = payment.VirtualBankAccount,
         VirtualBankAccountHolder = payment.VirtualBankAccountHolder,
         VirtualBankExpirationTime = checkout.VirtualBankExpirationTime,
         VirtualBankName = payment.VirtualBankName,
     });
 }
예제 #21
0
        public static bool IsSuccessfulPayment(this Models.Payment payment)
        {
            var statuses = new[]
            {
                PaymentApiConstants.PaymentStatusAuthorised,
                PaymentApiConstants.PaymentStatusCaptured,
                PaymentApiConstants.PaymentStatusCompensated,
                PaymentApiConstants.PaymentStatusPartiallyCompensated,
                PaymentApiConstants.PaymentStatusRefunded,
                PaymentApiConstants.PaymentStatusPartiallyRefunded,
            };

            return(payment.HasOneOfStatuses(statuses));
        }
        private IEnumerable <UserReportPortion> AggregateUserTransactions(Models.Payment payment, Transaction[] allTransactions, Granularity granularity)
        {
            var transactions   = allTransactions.Where(t => t.PaymentId == payment.Id).ToArray();
            var withTimestamps = transactions.Select(t => new TransactionWithTimestamp {
                Timestamp = t.Timestamp.ToDateTime(), Transaction = t
            });
            var portions = Aggregations.GroupByPeriods(granularity, withTimestamps);

            foreach (var portion in portions)
            {
                var debits = portion.Sum(p => (float?)p.Transaction.Amount) ?? 0;
                yield return(new UserReportPortion {
                    Period = portion.Key, Debits = debits, Element = payment.Name
                });
            }
        }
        public Models.Payment Create(float amount, DateTime startTimestamp, TimeSpan interval, string accountId, string recipient)
        {
            var payment = new Models.Payment
            {
                Id                        = Guid.NewGuid().ToString(),
                Amount                    = amount,
                StartTimestamp            = startTimestamp,
                LatestProcessingTimestamp = null,
                Interval                  = interval,
                Status                    = Models.PaymentStatus.ACTIVE,
                AccountId                 = accountId,
                Recipient                 = recipient
            };

            payments.Add(payment.Id, payment);
            return(payment);
        }
예제 #24
0
        //private bool CallCustomerCreation()
        //{
        //    if (String.IsNullOrEmpty(this.CustomerId))
        //    {
        //        Customer NewCustomer = new Customer();
        //        NewCustomer.Email = this.Email;
        //        NewCustomer.Description = this.Description;
        //        NewCustomer.SourceToken = this.CardId;
        //        try
        //        {
        //            StripeCustomer stpCustomer = NewCustomer.AddCustomer();
        //            this.CustomerId = stpCustomer.Id;
        //        }
        //        catch (Exception ex)
        //        {
        //            this.ErrorMsg = ex.Message;
        //            ErrorLog.Log(ex);
        //            return false;
        //        }
        //    }
        //    return true;
        //}
        //private StripeCustomer AddCustomer()
        //{
        //    StripeError err = new StripeError();
        //    StripeCustomerCreateOptions Customer = new StripeCustomerCreateOptions();
        //    Customer.Email = this.Email;
        //    Customer.Description = this.Description;
        //    Customer.SourceToken = this.CardId;
        //    StripeCustomerService CustomerService = new StripeCustomerService();
        //    CustomerService.ApiKey = "sk_test_9wnKd0ODnOXr00bysp5h7BD7";
        //    StripeCustomer StripUser = CustomerService.Create(Customer);
        //    this.CustomerId = StripUser.Id;
        //    return StripUser;
        //}

        public bool Payment()
        {
            if (CreateCustmer())
            {
                if (CreateCardDetails())
                {
                    try
                    {
                        StripeChargeService       service = new StripeChargeService(Params.stripeApiKey);
                        StripeChargeCreateOptions options = new StripeChargeCreateOptions();
                        options.Currency     = string.IsNullOrEmpty(this.Currency) ? "inr" : "inr";
                        options.Amount       = this.Amount * 100;
                        options.CustomerId   = this.CustomerId;
                        options.Description  = this.Description;
                        options.ReceiptEmail = this.Email;
                        options.SourceTokenOrExistingSourceId = this.CardId;
                        var getPayment = service.Create(options);
                        if (!string.IsNullOrEmpty(getPayment.Id))
                        {
                            Payment pay = new Models.Payment();
                            pay.Id            = Guid.NewGuid();
                            pay.TransactionNo = getPayment.Id;
                            pay.CustomerId    = this.CustomerId;
                            pay.Userid        = new Guid(this.UserId);
                            pay.CardId        = this.CardId;
                            pay.IsActive      = true;
                            pay.IsDeleted     = false;
                            this.unit._paymentRepository.Save(pay);
                            this.unit.Commit();
                            return(true);
                        }
                    }
                    catch (Exception ex)
                    {
                        return(false);
                    }
                }
            }

            return(false);
        }
예제 #25
0
        public Task <StoreNewPaymentResult> Add(Models.Payment payment)
        {
            payment.Id = Guid.NewGuid();

            if (!string.IsNullOrEmpty(payment.IdempotencyUniqueId))
            {
                lock (_lockObject)
                {
                    if (_idempotencyKeys.ContainsKey(payment.IdempotencyUniqueId))
                    {
                        return(Task.FromResult(StoreNewPaymentResult.DuplicateUniqueIdempotencyId));
                    }

                    _idempotencyKeys.Add(payment.IdempotencyUniqueId, payment.Id.Value);
                }
            }

            _storage.TryAdd(payment.Id.Value, payment);

            return(Task.FromResult(StoreNewPaymentResult.Success));
        }
예제 #26
0
        private void VerifyPaymentState(RedirectInformation response, Order order, Models.Payment pay)
        {
            switch (response.Status.status)
            {
            case "APPROVED":
                order.Status    = "PAYED";
                order.UpdatedAt = Convert.ToDateTime(response.Status.Date);
                pay.Status      = response.Status.status;
                pay.FechaUpdate = Convert.ToDateTime(response.Status.Date);
                break;

            case "PENDING":
                pay.Status      = response.Status.status;
                pay.FechaUpdate = Convert.ToDateTime(response.Status.Date);
                break;

            case "REJECTED":
                pay.Status      = response.Status.status;
                pay.FechaUpdate = Convert.ToDateTime(response.Status.Date);
                pay.Message     = response.Status.Message;
                break;
            }
        }
예제 #27
0
        public async Task Accept(Guid id)
        {
            using (ApplicationDbContext context = new ApplicationDbContext())
            {
                var model = context.Contract.Find(id);
                model.Status = Constant.MagicStringReplacer.AcceptedStatus;

                //Add Payment
                Models.Payment payment = new Models.Payment()
                {
                    Id                 = Guid.NewGuid(),
                    ProjectName        = model.ProjectName,
                    AmountDue          = decimal.Parse(model.ProjectCost),
                    Status             = Constant.MagicStringReplacer.PendingStatus,
                    ContractId         = id,
                    ClientId           = model.ClientId,
                    QuotationReference = model.QuotationReference
                };
                context.Payment.Add(payment);
                //
                await context.SaveChangesAsync();
            }
        }
예제 #28
0
        public ActionResult AddToPayment(Models.Payment pa1)
        {
            var PayId = db.Payments.Add(pa1);

            db.SaveChanges();
            List <Models.Product> listproduct = new List <Models.Product>();

            if (Session["Cart"] != null)
            {
                PaymentDetail pd1 = new PaymentDetail();
                listproduct = Session["Cart"] as List <Models.Product>;
                foreach (var item in listproduct)
                {
                    pd1.IdProduct        = item.IdProduct;
                    pd1.ProductPrice     = item.Price;
                    pd1.NumbersOfProduct = item.NumbersOfProduct;
                    pd1.IdPayment        = PayId.IdPayment;
                    db.paymentdetails.Add(pd1);
                    db.SaveChanges();
                }
            }
            return(View());
        }
예제 #29
0
        public bool Add(Models.Payment payment)
        {
            StreamWriter writer = null;

            try
            {
                writer = new StreamWriter(System.Web.HttpContext.Current.Server.MapPath("~/Payments.txt"), true);
                writer.WriteLine(payment.ToString());
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
            finally
            {
                if (writer != null)
                {
                    writer.Dispose();
                    writer = null;
                }
            }
        }
예제 #30
0
        public async Task <ActionResult> FinalisePost([FromBody] Models.Payment Payment)
        {
            //INSERT TRANSACTION LOGIC HERE (THIS APP DOESN'T TAKE MONEY FROM REAL ACCOUNTS)
            if (Payment == null)
            {
                return(new StatusCodeResult(400));
            }
            try
            {
                await PostInvoice();
                await NotifyOrdering();

                foreach (BillingProduct bp in Payment.Order.Products)
                {
                    db.Products.Remove(bp);
                }
                db.Remove(Payment.Order);
                db.SaveChanges();
            }
            catch { return(new StatusCodeResult(500)); }

            return(Redirect("http://localhost:54330/Products/Index"));
        }
예제 #31
0
        public async Task<ActionResult> AccountSettings()
        {
            bool IsCompletedProfile = await isProfileCompleted();

            if (IsCompletedProfile == true)
            {
                Tutor loaddb = db.Tutors.Where(c => c.Username == User.Identity.Name).FirstOrDefault();
                Models.Payment obj = new Models.Payment();
                obj.Balance = db.Tutors.Where(c => c.Username == User.Identity.Name).FirstOrDefault().CurrentEarning.ToString();
                obj.Email = loaddb.paypalEmail;
                obj.Requested = loaddb.moneyStatus=="Requested"?true:false;
                return View(obj);
            }
            else
            {
                TempData["isValidate"] = false;
                return RedirectToAction("EditProfile");
            }

        }
예제 #32
0
        public ActionResult Receipt(string card_type, string card_name, string card_number, string security_number, string expiry_date, string customer_id, string first_name, string last_name, char gender, int age, string email, string phone_number, string address, string city, int vehicle_id, string pickupdate, string dropoffdate, string returncity, string pickupcity)
        {
            ViewData["vehicle_id"] = Request.Params["vehicle_id"];
            ViewData["customer_id"] = Request.Params["customer_id"];
            ViewData["first_name"] = Request.Params["first_name"];
            ViewData["last_name"] = Request.Params["last_name"];
            ViewData["age"] = Request.Params["age"];
            ViewData["gender"] = Request.Params["gender"];
            ViewData["email"] = Request.Params["email"];
            ViewData["phone_number"] = Request.Params["phone_number"];
            ViewData["address"] = Request.Params["address"];
            ViewData["city"] = Request.Params["city"];
            ViewData["pickupdate"] = Request.Params["pickupdate"];
            ViewData["dropoffdate"] = Request.Params["dropoffdate"];
            ViewData["pickupcity"] = Request.Params["pickupcity"];
            ViewData["returncity"] = Request.Params["returncity"];

            int cid;
            int.TryParse(customer_id, out cid);
            Customer c = new Customer
            {
                customer_id = cid,
                first_name = first_name,
                last_name = last_name,
                age = age,
                gender = gender,
                email = email,
                phone_number = phone_number,
                address = address,
                city = city
            };            


            int vid = vehicle_id;
            int.TryParse(customer_id, out cid);
            CarRentalApp.Booking b = new CarRentalApp.Booking
            {
                booking_status_code = "1",
                customer_id = cid,
                vehicle_id = vid,
                pickup_city = pickupcity,
                return_city = returncity,
                pickup_date = Convert.ToDateTime(pickupdate),
                return_date = Convert.ToDateTime(dropoffdate)
            };
           

            Models.Payment p = new Models.Payment();
            p.cardtype = card_type; p.cardnumber = card_number; p.cardname = card_name; p.expirydate = expiry_date; p.securitynumber = security_number;
            Models.ParentModel pm = new Models.ParentModel();
            pm.customer = c;
            pm.booking = b;
            DatabaseService s = new DatabaseService();
            pm.reviewmodel = s.getReview(vehicle_id);
            pm.payment = p;

            DateTime end = Convert.ToDateTime(ViewData["dropoffdate"]);
            DateTime start = Convert.ToDateTime(ViewData["pickupdate"]);
            double d = ((end - start).TotalDays + 1) * Convert.ToDouble(pm.reviewmodel.daily_rental_rate);

            ViewData["error"] = "";

            if (s.checkRestriction(pm.customer.customer_id, pm.booking.pickup_date) == false)
            {
                ViewData["error"] = "Unable to complete the booking";
            }
            else
            {
                s.SaveCustomer(c);
                b.booking_id = s.SaveBooking(b);
                CarRentalTestApp.SendEmailService ses = new CarRentalTestApp.SendEmailService();
                String aString = "<br/>Customer ID:" + pm.customer.customer_id + "<br/>Customer First Name:" + pm.customer.first_name + "<br/>Customer Last Name:" + pm.customer.last_name + "<br/>Age:" + pm.customer.age + "<br/>Gender:" + pm.customer.gender + "<br/>Email:" + pm.customer.email + "<br/>Phone Number:" + pm.customer.phone_number + "<br/>Address:" + pm.customer.address + "<br/>City:" + pm.customer.city;
                aString += "<br/>Payment Card Type:" + pm.payment.cardtype + "<br/>Payment Card Number:" + pm.payment.cardnumber + "<br/>Payment Card Name:" + pm.payment.cardname + "<br/>Expiry Date:" + pm.payment.expirydate + "<br/>Security Number:" + pm.payment.securitynumber;
                aString += "<br/>Booking ID:" + pm.booking.booking_id + "<br/>Pickup Date:" + pm.booking.pickup_date + "<br/>Return Date:" + pm.booking.return_date + "<br/>Pickup City:" + pm.booking.pickup_city + "<br/>Drop off city:" + pm.booking.return_city;
                aString += "<br/>Vehicle ID:" + pm.reviewmodel.registration_number + "<br/>Manufacturing Date:" + pm.reviewmodel.manufacturing_date + "<br/>Model:" + pm.reviewmodel.model_code + "<br/>Body style:" + pm.reviewmodel.body_style + "<br/>Passenger Capacity:" + pm.reviewmodel.passenger_capacity + "<br/>Vehicle Category Description:" + pm.reviewmodel.vehicle_category_description + "<br/> Daily Rental:" + pm.reviewmodel.daily_rental_rate + "<br/>Total Cost:" + d.ToString();
                ses.SendEmail(pm.customer.email, aString);
            }           
            return View(pm);
        }
예제 #33
0
        public async Task<ActionResult> AccountSettings()
        {
            bool IsCompletedProfile = await isProfileCompleted();

            if (IsCompletedProfile == true)
            {
                string payerId = Request.Params["PayerID"];

                if (string.IsNullOrEmpty(payerId))
                {

                }
                else
                {
                    // This section is executed when we have received all the payments parameters

                    // from the previous call to the function Create

                    // Executing a payment
                    var apiContext = Configuration.GetAPIContext();
                    var guid = Request.Params["guid"];

                    var executedPayment = ExecutePayment(apiContext, payerId, Session[guid] as string);

                    if (executedPayment.state.ToLower() != "approved")
                    {
                        return View("FailureView");
                    }
                }

                Models.Payment obj = new Models.Payment();
                obj.Amount = db.Students.Where(c => c.Username == User.Identity.Name).FirstOrDefault().CurrentBalance;
                return View();
            }
            else
            {
                TempData["isValidate"] = false;
                return RedirectToAction("EditProfile");
            }

        }
예제 #34
0
        public async Task<ActionResult> AccountSettings()
        {

            string payerId = Request.Params["PayerID"];

            if (string.IsNullOrEmpty(payerId))
            {

            }
            else
            {
                try { 

                    var apiContext = Configuration.GetAPIContext();
                    var guid = Request.Params["guid"];
                    var paymentId = Request.Params["paymentId"];

                    var executedPayment = ExecutePayment(apiContext, payerId, Session[guid] as string);

                    if (executedPayment.state.ToLower() == "approved")
                    {
                        var payments = db.payments.Where(c => c.paymentId == paymentId).FirstOrDefault();
                        payments.status = Status.Approved;

                        var user = db.Students.Where(c => c.Username == User.Identity.Name).FirstOrDefault();
                        user.CurrentBalance = user.CurrentBalance + (float)Convert.ToDouble(payments.amount);
                        db.Entry(user).State = EntityState.Modified;
                        db.Entry(payments).State = EntityState.Modified;
                        db.SaveChanges();

                    }

                    if (executedPayment.state.ToLower() != "approved")
                    {
                        return View("FailureView");
                    }
            }
             catch (Exception ex)
            {
                    Models.Payment model = new Models.Payment();
                    model.Balance = db.Students.Where(c => c.Username == User.Identity.Name).FirstOrDefault().CurrentBalance.ToString();
                    return View(model);
            }
        }
           

            Models.Payment obj = new Models.Payment();
            obj.Balance = db.Students.Where(c => c.Username == User.Identity.Name).FirstOrDefault().CurrentBalance.ToString();
           return View(obj);
           

        }