Beispiel #1
0
        public async Task <IActionResult> Checkout([Bind("Number, ExpDate")] CreditCardViewModel ccvm)
        {
            Cart cart = await _cart.GetCartAsync(User.Identity.Name);

            // Get cart total
            int amount = 0;

            foreach (Order o in cart.Orders)
            {
                amount += o.ExtPrice;
            }

            createTransactionResponse response = _payment.RunCard(amount, ccvm.ExpDate, ccvm.Number);

            if (response.messages.resultCode == messageTypeEnum.Ok)
            {
                await _cart.CloseCartAsync(cart);

                return(RedirectToAction("Receipt", "Cart", cart));
            }
            else
            {
                TempData["paymentResponse"] = response.messages.resultCode;
                return(RedirectToAction("Index", "Cart"));
            }
        }
Beispiel #2
0
        /// <summary>
        /// Add/Edit Credit card of current customer or current organization
        /// </summary>
        /// <param name="currentPage">Current credit card page</param>
        /// <param name="creditCardId">Credit card id</param>
        /// <returns></returns>
        private IActionResult CreditCardEditView(CreditCardPage currentPage, string creditCardId)
        {
            var viewModel = new CreditCardViewModel(currentPage)
            {
                CreditCard = new CreditCardModel
                {
                    CreditCardId = creditCardId
                },
                CurrentContent = currentPage,
                IsB2B          = currentPage.B2B
            };

            if (currentPage.B2B)
            {
                viewModel.Organizations = viewModel.GetAllOrganizationAndSub(_organizationService.GetCurrentFoundationOrganization());
            }

            if (_creditCardService.IsValid(viewModel.CreditCard.CreditCardId, out var errorMessage))
            {
                _creditCardService.LoadCreditCard(viewModel.CreditCard);
            }
            else
            {
                viewModel.ErrorMessage = errorMessage;
            }
            ViewData["IsReadOnly"] = false;

            return(View("EditForm", viewModel));
        }
Beispiel #3
0
        public void DeleteConfirmed(int id)
        {
            CreditCardViewModel ccvm = new CreditCardViewModel();

            ccvm.DeleteCreditCard(id);
            //return RedirectToAction("Index");
        }
 public CreditCardViewModel CreateNew()
 {
     var customerCreditCard = new IACustomerCreditCard {MPUserID = _customerMemberProtectUserId};
      _dataContext.IACustomerCreditCards.InsertOnSubmit(customerCreditCard);
      var vm = new CreditCardViewModel(_customerMemberProtectUserId, customerCreditCard);
      return vm;
 }
Beispiel #5
0
        public async Task <IActionResult> EditCreditCard([Bind(creditProperties)] CreditCardViewModel c)
        {
            if (!ModelState.IsValid)
            {
                return(View("EditCreditCard", c));
            }
            var o = await payments.GetObject(c.ID) as CreditCardObject;

            o.DbRecord.Payer = c.Payer;
            o.DbRecord.PayerAccountNumber = c.PayerAccountNumber;
            o.DbRecord.Payee = c.Payee;
            o.DbRecord.PayeeAccountNumber   = c.PayeeAccountNumber;
            o.DbRecord.Amount               = c.Amount;
            o.DbRecord.Currency             = c.Currency;
            o.DbRecord.CardAssociationName  = c.CardAssociationName;
            o.DbRecord.CardNumber           = c.CardNumber;
            o.DbRecord.DailyWithDrawalLimit = c.DailyWithdrawalLimit;
            o.DbRecord.Memo        = c.Memo;
            o.DbRecord.CreditLimit = c.CreditLimit;
            o.DbRecord.ValidFrom   = c.ValidFrom ?? DateTime.MinValue;
            o.DbRecord.ValidTo     = c.ValidTo ?? DateTime.MaxValue;
            await payments.UpdateObject(o);

            return(RedirectToAction("Index"));
        }
Beispiel #6
0
        public ActionResult EditAccountNumber(CreditCardViewModel cc)
        {
            var usId = Convert.ToInt32(Session["UserId"]);

            var not = db.Notifications.Where(u => u.NOT_U_Id == usId && u.NOT_Leido == false);

            ViewBag.noti     = not;
            ViewBag.CC_CT_Id = new SelectList(db.UserData, "CT_Id", "CT_Type");

            var number = cc.CC_Entity + cc.CC_Office + cc.CC_ControlDigit + cc.CC_ANumber;

            var ccUser = db.CreditCard.Find(cc.CC_Id);

            ccUser.CC_AccountNumber = number;

            if (ModelState.IsValid)
            {
                try
                {
                    db.Entry(ccUser).State = EntityState.Modified;
                    db.SaveChanges();
                    return(RedirectToAction("CreditCardInfo"));
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    RedirectToAction("ErrorPage", "Error");
                }
            }
            return(View());
        }
Beispiel #7
0
        public void AddUserCard(int userId, CreditCardViewModel cardViewModel, int purpose)
        {
            _creditCardRepository.AddOrUpdateCreditCard(CreditCardMapper.ModelToEntity(cardViewModel));
            var card = _creditCardRepository.FindCreditCard(cardViewModel.Number);

            _userRepository.AddUserCard(userId, card.id, purpose);
        }
        public PartialViewResult RechargeCredit(RechargeViewModel model)
        {
            ApplicationUser user = db.Users.Find(User.Identity.GetUserId());

            try
            {
                /*
                 * Payment Process
                 */

                if (model.NewCredit > 0)
                {
                    user.Credit += model.NewCredit;
                }
                db.SaveChanges();
                ViewBag.Message      = Resource.CreditRechargeSuccess + user.Credit + " $";
                ViewBag.AlertSuccess = "alert alert-success";
                ViewBag.Success      = true;
                return(PartialView("_RechargeCreditPartial"));
            }
            catch
            {
            }

            CreditCardViewModel credit    = new CreditCardViewModel();
            List <string>       cardsList = new List <string>();

            cardsList.Add("Visa");
            cardsList.Add("Master Card");
            cardsList.Add("American Express");
            cardsList.Add("Discover Network");

            ViewBag.CardTypes = new SelectList(cardsList);

            List <int> months = new List <int>();

            for (int i = 01; i <= 12; i++)
            {
                months.Add(i);
            }

            List <int> years = new List <int>();

            for (int i = DateTime.Now.Year; i <= DateTime.Now.AddYears(10).Year; i++)
            {
                years.Add(i);
            }

            ViewBag.Month = new SelectList(months);
            ViewBag.Year  = new SelectList(years);

            RechargeViewModel rvm = new RechargeViewModel()
            {
                CurrentCredit = user.Credit,
                CreditCard    = credit
            };

            return(PartialView("_RechargeCreditPartial", rvm));
        }
Beispiel #9
0
        public async Task <IActionResult> Edit(int customerID, [FromForm] CreditCardViewModel vm)
        {
            var creditCard = _context.Customers.Where(c => c.ID == customerID).SelectMany(c => c.CreditCards).Where(cc => cc.ID == vm.ID).SingleOrDefault();

            _context.Remove(creditCard);
            _context.SaveChanges();
            return(RedirectToAction(nameof(Index)));
        }
 public bool CreditCardPayment(CreditCardViewModel creditCard)
 {
     if (creditCard == null || creditCard.CardNumber.Length != 16 || creditCard.CVV.Length != 3 || creditCard.CardExpiryDate < DateTime.Now)
     {
         return(false);
     }
     return(true);
 }
 public FlightPaymentViewModel(int referenceNumber, CreditCardViewModel creditCard, MvcApplication1.BookingService.PassengerModel[] passengers, MvcApplication1.AirportService.FlightModel flight, char travelClass)
 {
     this.ReferenceNumber = referenceNumber;
     this.CreditCard = creditCard;
     this.Passengers = passengers;
     this.Flight = flight;
     this.TravelClass = travelClass;
 }
Beispiel #12
0
 public void Finish()
 {
     var model = new CreditCardViewModel
     {
         CardNumber = "Test Credit Card",
         Addresses  = new string[] { "Address1", "Address2" }
     };
     //return View(model);
 }
        public static string Render(CreditCardViewModel viewModel)
        {
            var r = new StringBuilder();

            r.Append("Kredittkortnummer: " + viewModel.CreditCardNumber);
            r.Append("<br/>Utløpsdato: " + viewModel.ExpirationDate);
            r.Append("<br/>Sikkerhetskode: " + viewModel.CardSecurityCode);
            return(r.ToString());
        }
Beispiel #14
0
        public IActionResult Confirmation()
        {
            var model = new CreditCardViewModel
            {
                CardNumber = "Test Credit Card",
                Addresses  = new string[] { "Address1", "Address2" }
            };

            return(View(model));
        }
 public HotelPaymentViewModel(int referenceNumber, CreditCardViewModel creditCard, MvcApplication1.BookingService.PassengerModel[] passengers, MvcApplication1.HotelService.HotelModel hotel, String roomTypeCode, DateTime checkIn, DateTime checkOut, int roomsRequested)
 {
     this.ReferenceNumber = referenceNumber;
     this.CreditCard = creditCard;
     this.Passengers = passengers;
     this.Hotel = hotel;
     this.RoomTypeCode = roomTypeCode;
     this.CheckIn = checkIn;
     this.CheckOut = checkOut;
     this.RoomsRequested = roomsRequested;
 }
Beispiel #16
0
        public void TestMethodAddCard_ShouldAddCard()
        {
            CreditCardViewModel value = new CreditCardViewModel()
            {
                CardNumber = 55555555555, ExpiryDate = DateTime.UtcNow
            };

            var controller = new CreditCardController(_creditCardService);
            var result     = ((System.Web.Http.Results.OkNegotiatedContentResult <int>)controller.Post(value));

            Assert.IsTrue(result.Content.Equals(1));
        }
Beispiel #17
0
        public async Task <JsonResult> Subscribe(CreditCardViewModel creditCardViewModel)
        {
            HttpResponseMessage paymentResult = await new BankPaymentProcessor()
                                                .PayNowAsync(new CreditCard
            {
                Number = creditCardViewModel.Number,
                Date   = creditCardViewModel.Date,
                Cvv    = creditCardViewModel.Cvv
            });

            return(Json(paymentResult.Content.ReadAsAsync <PaymentResult>().Result));
        }
Beispiel #18
0
 public static CreditCard ModelToEntity(CreditCardViewModel creditCardViewModel)
 {
     return(creditCardViewModel == null
         ? null
         : new CreditCard()
     {
         id = creditCardViewModel.Id,
         number = creditCardViewModel.Number,
         CVV = creditCardViewModel.CVV,
         finish_date = creditCardViewModel.FinishDate
     });
 }
Beispiel #19
0
        CreateCreditCard([Bind(creditProperties)] CreditCardViewModel c)
        {
            if (!ModelState.IsValid)
            {
                return(View(c));
            }
            c.ID = Guid.NewGuid().ToString();
            var o = PaymentObjectFactory.CreateCredit(c.ID, c.Amount, c.Currency, c.Memo, c.Payer, c.PayerAccountNumber,
                                                      c.CardAssociationName, c.CardNumber, c.DailyWithdrawalLimit, c.Payee, c.PayeeAccountNumber,
                                                      c.CreditLimit, c.ValidFrom, c.ValidTo);
            await payments.AddObject(o);

            return(RedirectToAction("Index"));
        }
Beispiel #20
0
        public ActionResult AddAccount(CreditCardViewModel cc)
        {
            var usId = Convert.ToInt32(Session["UserId"]);

            var not = db.Notifications.Where(u => u.NOT_U_Id == usId && u.NOT_Leido == false);

            ViewBag.noti = not;

            var numero = cc.CC_Entity + cc.CC_Office + cc.CC_ControlDigit + cc.CC_ANumber;

            var findCC = db.CreditCard.Where(u => u.CC_U_Id == usId);

            if (findCC.Count() > 1)
            {
                findCC.Single();
                try
                {
                    db.Entry(findCC).State = EntityState.Modified;
                    db.SaveChanges();
                    return(RedirectToAction("CreditCardInfo"));
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    RedirectToAction("ErrorPage", "Error");
                }
            }
            else
            {
                CreditCard newCC = new CreditCard();
                newCC.CC_AccountNumber = numero;
                newCC.CC_U_Id          = usId;

                try
                {
                    db.CreditCard.Add(newCC);
                    db.SaveChanges();
                    return(RedirectToAction("CreditCardInfo"));
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    RedirectToAction("ErrorPage", "Error");
                }
            }



            return(View());
        }
Beispiel #21
0
        public void TestInitialize()
        {
            CreditCardService service   = new CreditCardService(new InMemoryCreditCardService());
            CreditCardModel   cardModel = new CreditCardModel
            {
                CardNumber = "12345678902137",
                CardType   = "MasterCard",
                ExpMonth   = 12,
                ExpYear    = 23
            };

            _creditCardViewModel     = new CreditCardViewModel(cardModel, service);
            _creditCardListViewModel = new CreditCardListViewModel(service);
        }
Beispiel #22
0
        public ActionResult CreditCard(CreditCardViewModel model)
        {
            ViewBag.Cards = new List <SelectListItem>()
            {
                new SelectListItem()
                {
                    Text = "MasterCard", Value = "mastercard"
                },
                new SelectListItem()
                {
                    Text = "Visa", Value = "visa"
                },
                new SelectListItem()
                {
                    Text = "Discover", Value = "discover"
                },
                new SelectListItem()
                {
                    Text = "Amex", Value = "amex"
                }
            };
            ViewBag.NoOrders = false; // OM: because GET /Checkout uses these Viewbag bool/list for a check, so they cant be null

            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var order = new Order();

            TryUpdateModel(order);

            try
            {
                var cart = ShoppingCart.GetCart(this.HttpContext);
                order.UserName   = User.Identity.GetUserName();
                order.OrderDate  = DateTime.Now;
                order.TotalPrice = cart.GetTotal();

                // OM: Pass order info to PayPal payment and add the order only after payment has gone through
                TempData["Order"] = order;
                TempData["model"] = model;
                return(RedirectToAction("PaymentWithCreditCard", "PayPal"));
            }
            catch
            {
                return(View(model));
            }
        }
Beispiel #23
0
        public ActionResult SaveCcBorrowPrivilege(int id)
        {
            CreditCardViewModel ccVm;

            if (id > 0)
            {
                ccVm = new CreditCardViewModel(id);
            }
            else
            {
                ccVm = new CreditCardViewModel();
            }
            ViewBag.BankId = new SelectList(db.Banks, "BankId", "Name");
            return(View(ccVm));
        }
Beispiel #24
0
        // GET: Admin/CreditCards/Create
        public ActionResult Create(int id = 1)
        {
            CreditCardViewModel Card;

            if (id > 0)
            {
                Card = new CreditCardViewModel(id);
            }
            else
            {
                Card = new CreditCardViewModel();
            }
            ViewBag.BankId = new SelectList(db.Banks, "BankId", "Name");
            return(View("CreateOld", Card));
        }
        public void DeleteCreditCard(CreditCardViewModel creditCard)
        {
            if (creditCard.CustomerCreditCard == null)
            throw new ApplicationException("Expected creditCard.CustomerCreditCard to be populated.");

             var gateway = GetCardGateway();
             var result = gateway.DeletePaymentProfile(creditCard.CIMProfileId, creditCard.CIMPaymentProfileId);
             LogResults(gateway);

             if (!result) LogError("Unable to remove credit card from CIM storage");

             _dataContext.IACustomerCreditCards.DeleteOnSubmit(creditCard.CustomerCreditCard);

             // assumed to be the same application level DataContext used to load the card
             _dataContext.SubmitChanges();
        }
Beispiel #26
0
        public string VerifyCreditCard([FromBody] CreditCardViewModel cardData)
        {
            string            verifiedResult = string.Empty;
            CreditCardService service        = new CreditCardService();

            if (service.IsVerified(cardData))
            {
                verifiedResult = "授權成功";
            }
            else
            {
                verifiedResult = "授權失敗";
            }

            return(verifiedResult);
        }
        public async Task <Guid> Insert(CreditCardViewModel creditCardViewModel)
        {
            if (creditCardViewModel == null)
            {
                return(Guid.Empty);
            }

            var creditCardDto = new CreditCardDto()
            {
                Name       = _tokenisationService.Encrypt(creditCardViewModel.Name),
                CardNumber = _tokenisationService.Encrypt(creditCardViewModel.CardNumber),
                CVC        = _tokenisationService.Encrypt(creditCardViewModel.CVC.ToString()),
                ExpiryDate = creditCardViewModel.ExpiryDate
            };

            return(await _creditCardRepository.Insert(creditCardDto));
        }
        /// <summary>
        /// Mapper from Dto to ViewModel with decryption.
        /// </summary>
        private CreditCardViewModel ConvertToCreditCardViewModel(CreditCardDto creditCardDto)
        {
            if (creditCardDto == null)
            {
                return(null);
            }

            var creditCardViewModel = new CreditCardViewModel()
            {
                Name       = _tokenisationService.Decrypt(creditCardDto.Name),
                CardNumber = _tokenisationService.Decrypt(creditCardDto.CardNumber),
                CVC        = Int32.Parse(_tokenisationService.Decrypt(creditCardDto.CVC)),
                ExpiryDate = creditCardDto.ExpiryDate
            };

            return(creditCardViewModel);
        }
Beispiel #29
0
        public async Task <IViewComponentResult> InvokeAsync()
        {
            CreditCardViewModel ccvm = new CreditCardViewModel();

            ccvm.Cart = await _cart.GetCartAsync(User.Identity.Name);

            List <string> creditCardNumbers = new List <string>();

            creditCardNumbers.Add("370000000000002");
            creditCardNumbers.Add("6011000000000012");
            creditCardNumbers.Add("4007000000027");
            creditCardNumbers.Add("4111111111111111");

            ViewData["CreditCardNumbers"] = new SelectList(creditCardNumbers);

            return(View(ccvm));
        }
Beispiel #30
0
        public ActionResult SaveCcEligibilityCriteria(int id)
        {
            CreditCardViewModel ccVm;

            if (id > 0)
            {
                ccVm = new CreditCardViewModel(id);
            }
            else
            {
                ccVm = new CreditCardViewModel();
            }
            ViewBag.BankId     = new SelectList(db.Banks, "BankId", "Name");
            ViewBag.CityGroups = db.CityGroups.ToList();

            return(View(ccVm));
        }
Beispiel #31
0
        public async Task <IActionResult> Create([FromForm] CreditCardViewModel creditCardViewModel, string returnUrl = null)
        {
            if (!ModelState.IsValid)
            {
                return(View(creditCardViewModel));
            }

            User user = await _userManager.GetUserAsync(User);

            int customerID = user.CustomerID.Value;

            var creditCard = new CreditCard();

            creditCard.CreditCardNumber = creditCardViewModel.CreditCardNumber;
            creditCard.FirstName        = creditCardViewModel.FirstName;
            creditCard.LastName         = creditCardViewModel.LastName;
            creditCard.Address          = creditCardViewModel.Address;
            creditCard.City             = creditCardViewModel.City;
            creditCard.Provice          = creditCardViewModel.Provice;
            creditCard.PostalCode       = creditCardViewModel.PostalCode;
            creditCard.Country          = creditCardViewModel.Country;
            creditCard.CustomerID       = customerID;


            // TODO: put info from creditCardViewModel to CreditCard model
            _context.Add(creditCard);
            _context.SaveChanges();

            var page = (string)TempData["previousPage"];

            if (page.Equals("checkoutFromCart", StringComparison.OrdinalIgnoreCase))
            {
                returnUrl = returnUrl ?? Url.Content("~/Checkout/Create");
                TempData["previousPage"] = "cart";
                return(LocalRedirect(returnUrl));
            }
            else if (page.Equals("creditIndexPage", StringComparison.OrdinalIgnoreCase))
            {
                return(RedirectToAction("Index"));
            }
            else
            {
                return(View("Error", new ErrorViewModel()));
            }
        }
Beispiel #32
0
        public static IList <CreditCardViewModel> MapToViewModelsList(this IList <CreditCard> creditCards)
        {
            List <CreditCardViewModel> viewModels = new List <CreditCardViewModel>();

            if (creditCards != null && creditCards.Count > 0)
            {
                foreach (CreditCard c in creditCards)
                {
                    CreditCardViewModel viewModel = c.MapToViewModel();
                    if (viewModel != null)
                    {
                        viewModels.Add(viewModel);
                    }
                }
            }

            return(viewModels);
        }
Beispiel #33
0
        public ActionResult SaveCcBorrowPrivilege(CreditCardViewModel ccVm, FormCollection fc)
        {
            ccVm = new CreditCardViewModel(ccVm.CardId);
            ccVm._BorrowPrivilege = new List <BorrowPrivilege>()
            {
            };
            foreach (var key in fc.AllKeys)
            {
                if (key.Equals("CardId"))
                {
                    continue;
                }
                if (key.Contains("Key") || key.Contains("Value"))
                {
                    if (ccVm._BorrowPrivilege.Last().Points == null)
                    {
                        ccVm._BorrowPrivilege.Last().Points = new List <KeyValuePair <string, string> > {
                        }
                    }
                    ;
                    if (key.Contains("Key"))
                    {
                        int keyValueOrPointId = GetkeyValueOrPointId(key);
                        int HeadingId         = GetHeadingId(key, keyValueOrPointId.ToString().Length);
                        ccVm._BorrowPrivilege.Last().Points.Add(new KeyValuePair <string, string>(fc[key], fc["Heading" + HeadingId + "Value" + keyValueOrPointId]));
                    }
                }
                else
                {
                    ccVm._BorrowPrivilege.Add(new BorrowPrivilege()
                    {
                        HeadingText = fc[key]
                    });
                }
            }

            //            if (ccVm.SaveCcBorrowPrivilege())
            if (ccVm.SaveCcDetails(CcInfoSection.BorrowPriviledges))
            {
                return(RedirectToAction("Details", new { id = ccVm.CardId }));
            }
            return(View(ccVm));
        }
Beispiel #34
0
        // GET: api/Cards/5
        public IHttpActionResult GetCard(int cardId)
        {
            Models.Domain.CreditCard card = DbContext.CreditCards.FirstOrDefault(p => p.Id == cardId);

            if (card != null)
            {
                CreditCardViewModel viewModel = new CreditCardViewModel
                {
                    Id = card.Id,
                    IdentificationNumber = card.IdentificationNumber,
                    Brand = card.Brand
                };

                return(Ok(viewModel));
            }
            else
            {
                return(NotFound());
            }
        }
        private void InformBillingThatCustomerPaid(CreditCardViewModel paymentDetails, PaymentGatewayResponse paymentGatewayResponse,
                                                 Func<string, string> urlBuilder,
                                                 IARequest request, DateTime approved, decimal chargeAmount)
        {
            string subject;
             string customerType;

             var mpOrg = _dataContext.MPOrgUsers.FirstOrDefault(row => row.MPUserID == _customerMemberProtectUserId);
             var mpOrgId = mpOrg == null ? Guid.Empty : mpOrg.MPOrgID;

             if (_memberProtect.Utility.YesNoToBool(_memberProtect.Organization.GetDataItem(mpOrgId, "IsVerified")))
             {
            subject = "Estimate Payment made (verified)";
            customerType = "a verified";
             }
             else
             {
            subject = "Estimate Payment made (unverified)";
            customerType = "an unverified";
             }

             var paidEmail = new StringBuilder();
             paidEmail.AppendFormat("An estimate payment was made by {0} customer:<br/>", customerType);
             paidEmail.Append("<br/>");
             paidEmail.AppendFormat("Company: <a href='{0}?id={1}'>{2}</a><br/>", urlBuilder("company-modify.aspx"),
                                mpOrgId.ToString().Replace("-", string.Empty), _memberProtect.Organization.GetName(mpOrgId));
             paidEmail.AppendFormat("Customer: <a href='{0}?id={1}'>{2} {3}</a><br/>", urlBuilder("user-account.aspx"),
                                _customerMemberProtectUserId.ToString().Replace("-", string.Empty),
                                _memberProtect.User.GetDataItem(_customerMemberProtectUserId, "FirstName"),
                                _memberProtect.User.GetDataItem(_customerMemberProtectUserId, "LastName"));
             paidEmail.AppendFormat("Email Receipt: {0}<br/>", paymentDetails.ReceiptEmailAddressCsv);
             paidEmail.AppendFormat("Request: <a href='{0}?rid={1}'>{2}</a><br/>", urlBuilder("create-job.aspx"), request.IARequestID, request.RequestIdForDisplay);
             paidEmail.AppendFormat("Amount: {0:c}<br/>", chargeAmount);
             paidEmail.AppendFormat("Card: {0} ending in {1}<br/>", paymentDetails.CardType, _memberProtect.Utility.Right(paymentDetails.CreditCardNumber, 4));
             paidEmail.AppendFormat("Name on Card: {0} {1}<br/>", paymentDetails.FirstName, paymentDetails.LastName);
             paidEmail.AppendFormat("When: {0:g}<br/>", approved);
             paidEmail.AppendFormat("Authorize Receipt: {0}<br/>", paymentGatewayResponse.GetValue(PaymentGatewayResponse.FieldNames.TransactionId));

             EmailCommunicationService.EstimatePaymentBillingNoticeSend(paidEmail, subject);
        }
        public CreditCardServiceResponse PayEstimate(CreditCardViewModel cardProfile, Func<string, string> urlBuilder, IARequest request, IARequestEstimate estimate)
        {
            var response = new CreditCardServiceResponse {SuccessfulCharge = true};

             var transaction = new AuthorizeNETTransactionInformation(cardProfile.CreditCardNumber, estimate.Charge, cardProfile.ExpirationDate)
             {
            FirstName = cardProfile.FirstName,
            LastName = cardProfile.LastName,
            CreditCardCode = cardProfile.CardVerificationCode,
            Email = cardProfile.ReceiptEmailAddressCsv,
            InvoiceNumber = string.Format("Est-{0}", request.RequestIdForDisplay),
            Description = "Request Estimate",
            Company = cardProfile.CompanyName.PadRight(50).Substring(0, 50).Trim(),
            Zip = ""
             };

             var paymentGatewayResponse = new PaymentGatewayResponse(string.Empty);

             if (cardProfile.CreditCardId == 0)
             {
            var authorizeNetDirect = new AuthorizeNET(_enableDebug, _loginId, _transactionKey);

            if (!authorizeNetDirect.ProcessAuthorizationAndCapture(transaction))
            {
               response.SuccessfulCharge = false;
               response.ErrorMessage = authorizeNetDirect.Error;
            }

            response.PaymentGatewayResponse = authorizeNetDirect.PaymentGatewayResponse;
             }
             else
             {
            // go through CIM to process transaction
            paymentGatewayResponse = CIMAuthorizationAndCapture(transaction,
                                                                cardProfile.CIMProfileId,
                                                                cardProfile.CIMPaymentProfileId);
            if (paymentGatewayResponse.Errors.Any() || paymentGatewayResponse.GetValue(PaymentGatewayResponse.FieldNames.ResponseCode) != "1")
            {
               var message = paymentGatewayResponse.Errors.Any()
                                ? paymentGatewayResponse.Errors.Aggregate((messages, error) => messages + ", " + error)
                                : paymentGatewayResponse.GetValue(PaymentGatewayResponse.FieldNames.ResponseReasonText);

               response.SuccessfulCharge = false;
               response.ErrorMessage = message;
            }
             }

             if (!response.SuccessfulCharge) return response;

             RecordOrder(cardProfile, paymentGatewayResponse, estimate);

             var requestStatusLookup = new RequestStatusLookup(_dataContext);
             request.IARequestStatusID = requestStatusLookup.GetRequestStatus(RequestStatus.Processing).IARequestStatusID;
             _dataContext.SubmitChanges();

             var approved = DateTime.Now;
             MarkEstimateAsPaid(request, estimate, approved);

             SendCustomerReceipt(cardProfile, request, estimate);

             InformBillingThatCustomerPaid(cardProfile, paymentGatewayResponse, urlBuilder, request, approved, estimate.Charge);

             return response;
        }
        public List<string> SaveCreditCard(CreditCardViewModel creditCard)
        {
            // assure a customer profile exists with AuthorizeNet CIM storage
             creditCard.CIMProfileId = CreateProfileIfNeeded();

             var orgUser = _dataContext.MPOrgUsers.FirstOrDefault(row => row.MPUserID == _customerMemberProtectUserId);
             var company = orgUser == null ? string.Empty : _memberProtect.Organization.GetName(orgUser.MPOrgID);

             // assumes customer profile is already created
             // create new CIM payment profile
             if (creditCard.CIMPaymentProfileId == 0)
             {
            var gateway = GetCardGateway();
            var result = gateway.CreatePaymentProfile(creditCard.CIMProfileId, creditCard.CardType, creditCard.CreditCardNumber,
                                                      string.Format("{0}-{1}", creditCard.ExpirationYear, creditCard.ExpirationMonth),
                                                      creditCard.CardVerificationCode, creditCard.Address, creditCard.City, creditCard.State,
                                                      "", creditCard.FirstName, creditCard.LastName, company);
            LogResults(gateway);

            if (!result.Item1)
            {
               // handle duplicate payment profiles with a friendly error message to the user
               // [E00039] A duplicate customer payment profile already exists.
               //if (gateway.Errors.Any(e => e.Contains("E00039")))
               //{
               //}

               // log it, and ka-boom it
               // can't really recover at this point...
               // throw new ApplicationException("Unable to create AuthorizeNET CIM Payment Profile");
               // not a seam to throw exceptions at, beyond that now.

               return gateway.Errors;
            }
            creditCard.CIMPaymentProfileId = result.Item2;
             }
             else
             {
            var gateway = GetCardGateway();
            var result = gateway.UpdatePaymentProfile(creditCard.CIMProfileId, creditCard.CIMPaymentProfileId, creditCard.CardType, creditCard.CreditCardNumber,
                                                      string.Format("{0}-{1}", creditCard.ExpirationYear, creditCard.ExpirationMonth),
                                                      creditCard.CardVerificationCode, creditCard.Address, creditCard.City, creditCard.State,
                                                      "", creditCard.FirstName, creditCard.LastName);
            LogResults(gateway);
            if (!result)
            {
               return gateway.Errors;
            }
             }

             if (_siteProperties.EnableCreditCardShadowCopy)
             {
            creditCard.CustomerCreditCard.CreditCardNumber = _memberProtect.Cryptography.Encrypt(creditCard.CreditCardNumber);
             }

             creditCard.CustomerCreditCard.Name = creditCard.Alias;
             creditCard.CustomerCreditCard.CIMPaymentProfileId = creditCard.CIMPaymentProfileId;
             creditCard.CustomerCreditCard.CreditCardType = _memberProtect.Cryptography.Encrypt(creditCard.CardType);
             creditCard.CustomerCreditCard.CreditCardExpirationMonth = _memberProtect.Cryptography.Encrypt(creditCard.ExpirationMonth);
             creditCard.CustomerCreditCard.CreditCardExpirationYear = _memberProtect.Cryptography.Encrypt(creditCard.ExpirationYear);
             creditCard.CustomerCreditCard.CreditCardFirstName = _memberProtect.Cryptography.Encrypt(creditCard.FirstName ?? "");
             creditCard.CustomerCreditCard.CreditCardLastName = _memberProtect.Cryptography.Encrypt(creditCard.LastName ?? "");
             creditCard.CustomerCreditCard.CreditCardCompanyName = _memberProtect.Cryptography.Encrypt(creditCard.CompanyName ?? "");
             creditCard.CustomerCreditCard.CreditCardAddress1 = _memberProtect.Cryptography.Encrypt(creditCard.Address ?? "");
             creditCard.CustomerCreditCard.CreditCardAddress2 = string.Empty;
             creditCard.CustomerCreditCard.CreditCardCity = _memberProtect.Cryptography.Encrypt(creditCard.City ?? "");
             creditCard.CustomerCreditCard.CreditCardState = _memberProtect.Cryptography.Encrypt(creditCard.State ?? "");
             creditCard.CustomerCreditCard.CreditCardZip = string.Empty;
             creditCard.CustomerCreditCard.CreditCardEmailReceipt = creditCard.ReceiptEmailAddressCsv;

             // assumed to be the same application level DataContext used to load the card
             _dataContext.SubmitChanges();

             return new List<string>();
        }
        private void PopulateViewModel(CreditCardViewModel viewModel, customerPaymentProfileMaskedType paymentProfile)
        {
            if (paymentProfile.billTo != null)
             {
            viewModel.Address = paymentProfile.billTo.address;
            viewModel.City = paymentProfile.billTo.city;
            viewModel.FirstName = paymentProfile.billTo.firstName;
            viewModel.LastName = paymentProfile.billTo.lastName;
            viewModel.State = paymentProfile.billTo.state;
             }

             var creditCard = paymentProfile.payment.Item as creditCardMaskedType;
             if (creditCard == null) return;

             viewModel.CreditCardNumber = creditCard.cardNumber;
        }
        private void RecordOrder(CreditCardViewModel paymentDetails, PaymentGatewayResponse response, IARequestEstimate estimate)
        {
            var iaOrder = new IAOrder
             {
            MPUserID = _customerMemberProtectUserId,
            CreditCardType = _memberProtect.Cryptography.Encrypt(paymentDetails.CardType),
            CreditCardNumber = _memberProtect.Cryptography.Encrypt(paymentDetails.CreditCardNumber),
            CreditCardExpirationMonth = _memberProtect.Cryptography.Encrypt(paymentDetails.ExpirationMonth),
            CreditCardExpirationYear = _memberProtect.Cryptography.Encrypt(paymentDetails.ExpirationYear),
            CreditCardFirstName = _memberProtect.Cryptography.Encrypt(paymentDetails.FirstName),
            CreditCardLastName = _memberProtect.Cryptography.Encrypt(paymentDetails.LastName),
            CreditCardZip = "",
            AuthorizeNetResponse = string.Empty,
            AuthorizeNetTransactionID = response.GetValue(PaymentGatewayResponse.FieldNames.TransactionId),
            AuthorizeNetProcessDatetime = DateTime.Now,
            AuthorizeNetProcessResponse = response.GetValue(PaymentGatewayResponse.FieldNames.ResponseCode),
            AuthorizeNetProcessUsername = _dataContext.MPUsers.First(u => u.MPUserID == _customerMemberProtectUserId).Username,
            AuthorizeNetProcessCaptureAmount = estimate.Charge,
            AuthorizeNetProcessCaptureAmountChangeReason = string.Empty,
            AuthorizeNetProcessStatus = "Captured",
            CreatedDateTime = DateTime.Now
             };
             _dataContext.IAOrders.InsertOnSubmit(iaOrder);
             _dataContext.SubmitChanges();

             var iaOrderLineItem = new IAOrderLineItem
             {
            IAOrderID = iaOrder.IAOrderID,
            Description = "Request Estimate",
            Quantity = 1,
            Price = estimate.Charge,
            IsSynched = false
             };
             _dataContext.IAOrderLineItems.InsertOnSubmit(iaOrderLineItem);

             estimate.IAOrderID = iaOrder.IAOrderID;
             _dataContext.SubmitChanges();
        }
        private void SendCustomerReceipt(CreditCardViewModel cardProfile, IARequest request, IARequestEstimate estimate)
        {
            var thankYouEmail = new StringBuilder();
             thankYouEmail.AppendLine(string.Format("Thank you for making your estimate payment for request # {0} requested by {1} {2}.<br/>",
                                                request.RequestIdForDisplay, _memberProtect.User.GetDataItem(request.MPUserID, "FirstName"),
                                                _memberProtect.User.GetDataItem(request.MPUserID, "LastName")));
             thankYouEmail.AppendLine("<br/>");
             thankYouEmail.AppendLine("Payment Details<br/>");
             foreach (var job in request.IAJobs)
             {
            thankYouEmail.AppendLine(string.Format("Job: {0}<br />", job.Name));
             }
             thankYouEmail.AppendLine(string.Format("Amount: {0:c}<br/>", estimate.Charge));
             thankYouEmail.AppendLine(string.Format("When: {0:g}<br/>", DateTime.Now));
             thankYouEmail.AppendLine(string.Format("Card: {0} ending in {1}<br/>", cardProfile.CardType,
                                                _memberProtect.Utility.Right(cardProfile.CreditCardNumber, 4)));
             thankYouEmail.AppendLine("<br/>");
             thankYouEmail.AppendLine("Thank you,<br/>");
             thankYouEmail.AppendLine("<a href='http://www.speedyspots.com'>SpeedySpots.com</a><br/>");
             thankYouEmail.AppendLine("<a href='mailto:[email protected]'>[email protected]</a><br/>");
             thankYouEmail.AppendLine("(734) 475-9327<br/>");
             thankYouEmail.AppendLine("Customer Email: " + cardProfile.ReceiptEmailAddressCsv); //ADDED THIS LINE FOR EMAIL FIx

             var subject = string.Format("Estimate payment received for request {0}.", request.RequestIdForDisplay);
             EmailCommunicationService.EstimatePaymentCustomerReceiptSend(subject, thankYouEmail, cardProfile.ReceiptEmailAddressCsv);
        }
Beispiel #41
0
        private void SendBillingEmail(CreditCardViewModel viewModel, bool bIsPaymentAutoImported, StringBuilder oSpeedySpotsLineItems,
                                    IAPayment oIAPayment)
        {
            StringBuilder oBody;
             // Email SpeedySpots
             oBody = new StringBuilder();
             if (!bIsPaymentAutoImported)
             {
            oBody.AppendLine("** This payment will NOT be auto-imported **");
            oBody.AppendLine();
             }
             oBody.AppendLine("Payments:");
             oBody.Append(oSpeedySpotsLineItems);
             oBody.AppendLine();
             oBody.AppendLine(string.Format("Customer Name: {0} {1}", viewModel.FirstName, viewModel.LastName));
             oBody.AppendLine(string.Format("Company Name: {0}", viewModel.CompanyName));
             oBody.AppendLine(string.Format("Customer Email(s): {0}", viewModel.ReceiptEmailAddressCsv));
             oBody.AppendLine();
             oBody.AppendLine(string.Format("Amount: {0:c}", oIAPayment.Total));

             if (m_txtInstructions.Text.Length > 0)
             {
            oBody.AppendLine(String.Format("Special Instructions: {0}", m_txtInstructions.Text));
             }
             oBody.AppendLine();
             oBody.AppendLine(string.Format("Card: {0}", viewModel.CardType));
             oBody.AppendLine(string.Format("Card Number: xxxx-xxxx-xxxx-{0}", viewModel.LastFourOfCardNumber));
             oBody.AppendLine(string.Format("Paid On: {0:MMMM dd, yyyy} at {0:h:mm tt}", DateTime.Now));

             EmailCommunicationService.PaymentBillingNoticeSend(oBody);
        }
Beispiel #42
0
        private void SendPaymentReceiptEmail(CreditCardViewModel viewModel, StringBuilder oLineItems, IAPayment oIAPayment)
        {
            // Email receipt to payer
             var sGreeting = string.Empty;
             if (_transientCardEntry && m_txtFirstName.Text == string.Empty && m_txtLastName.Text == string.Empty)
             {
            sGreeting = "Hello,";
             }
             else if (viewModel.FirstName == string.Empty)
             {
            sGreeting = "Hello,";
             }
             else
             {
            sGreeting = string.Format("{0} {1},", viewModel.FirstName, viewModel.LastName);
             }

             var oBody = new StringBuilder();
             oBody.AppendLine(sGreeting);
             oBody.AppendLine();
             oBody.AppendLine("Thank you for making a payment on SpeedySpots.com.");
             oBody.AppendLine();
             oBody.AppendLine("Payments:");
             oBody.Append(oLineItems);
             oBody.AppendLine();
             oBody.AppendLine(string.Format("Amount: {0:c}", oIAPayment.Total));
             oBody.AppendLine(string.Format("Card: {0}", viewModel.CardType));
             oBody.AppendLine(string.Format("Card Number: xxxx-xxxx-xxxx-{0}", viewModel.LastFourOfCardNumber));
             oBody.AppendLine(string.Format("Paid On: {0:MMMM dd, yyyy} at {0:h:mm tt}", DateTime.Now));
             if (m_txtInstructions.Text.Length > 0)
             {
            oBody.AppendLine(String.Format("Special Instructions: {0}", m_txtInstructions.Text));
             }
             oBody.AppendLine();
             oBody.AppendLine("Thank you again for using SpeedySpots.com");

             EmailCommunicationService.PaymentCustomerReceiptSend(oBody, viewModel.ReceiptEmailAddressCsv);
        }
Beispiel #43
0
        protected void OnPay(object sender, EventArgs e)
        {
            if (!Page.IsValid) return;

             var service = GetCardService();
             CardProfile = SetCreditCardViewModel(service);

             var cardExpiresOnDate =
            new DateTime(MemberProtect.Utility.ValidateInteger(CardProfile.ExpirationYear),
                         MemberProtect.Utility.ValidateInteger(CardProfile.ExpirationMonth), 1)
               .AddMonths(1).AddDays(-1);

             if (cardExpiresOnDate.CompareTo(DateTime.Today) <= 0)
             {
            SetMessage(
               _transientCardEntry
                  ? "Please choose a valid credit card expiration date in the future."
                  : "This card is expired please choose or add another card.",
               MessageTone.Negative);
            return;
             }

             var sErrors = string.Empty;

             if (_transientCardEntry)
             {
            if (CardProfile.CardType == "American Express")
            {
               var oRegex = new Regex("^\\d{15}$");
               if (!oRegex.Match(CardProfile.CreditCardNumber).Success)
               {
                  sErrors += "Credit Card Number must be a valid American Express number (123123412341234).<br/>";
               }

               if (CardProfile.CardVerificationCode.Length != 4)
               {
                  sErrors += "Please enter your 4 digit security code.<br/>";
               }
            }
            else
            {
               var oRegex = new Regex("^\\d{16}$");
               if (!oRegex.Match(CardProfile.CreditCardNumber).Success)
               {
                  sErrors += "Credit Card Number must be a valid credit card number (1234123412341234).<br/>";
               }

               if (CardProfile.CardVerificationCode.Length != 3)
               {
                  sErrors += "Please enter your 3 digit security code.<br/>";
               }
            }

            if (!m_chkAgree.Checked)
            {
               sErrors += "You must accept the Terms & Conditions.";
            }

            if (sErrors != string.Empty)
            {
               SetMessage(sErrors, MessageTone.Negative);
               return;
            }
             }

             var oExpirationDateTime =
            new DateTime(MemberProtect.Utility.ValidateInteger(m_cboCreditCardExpireYear.SelectedValue),
                         MemberProtect.Utility.ValidateInteger(m_cboCreditCardExpireMonth.SelectedValue), 1).AddMonths(1).AddDays(-1);

             var oTransactionInformation = new AuthorizeNETTransactionInformation(CardProfile.CreditCardNumber, GetTotal(), oExpirationDateTime)
             {
            FirstName = CardProfile.FirstName,
            LastName = CardProfile.LastName,
            CreditCardCode = CardProfile.CardVerificationCode,
            Email = CardProfile.ReceiptEmailAddressCsv,
            Description = "Invoice Payment",
            Company = (m_txtCompany.Text.Length > 50) ? m_txtCompany.Text.Substring(0, 49) : m_txtCompany.Text,
            InvoiceNumber = GetListOfInvoiceNumbers()
             };

             if (_transientCardEntry && m_chkSavePaymentInformation.Checked)
             {
            var errors = service.SaveCreditCard(CardProfile);
            if (errors.Any())
            {
               SetMessage(errors.Aggregate((msg, error) => msg + error + "<br />"), MessageTone.Negative);
               return;
            }

            // just flip the bit?  hope the state is all proper
            _transientCardEntry = false;
             }

             var paymentGatewayResponse = new PaymentGatewayResponse(string.Empty);

             if (_transientCardEntry)
             {
            var oAuthorizeNet = new AuthorizeNET(ApplicationContext.SiteProperites.AuthorizeNetIsDebug,
                                                 MemberProtect.Cryptography.Decrypt(ApplicationContext.SiteProperites.AuthorizeNetLoginID),
                                                 MemberProtect.Cryptography.Decrypt(ApplicationContext.SiteProperites.AuthorizeNetTransactionKey));

            if (!oAuthorizeNet.ProcessAuthorizationAndCapture(oTransactionInformation))
            {
               var message = "Your payment could not be processed, please double-check all information and try again.";
               if (ApplicationContext.SiteProperites.AuthorizeNetIsDebug)
               {
                  var response = CreditCards.ParseAuthorizeNetResponse(oAuthorizeNet.Response);
                  message += string.Format(" (Response: {0}, Reason: {1})", response.ResponseCode, response.ResponseReasonCode);
               }

               SetMessage(message, MessageTone.Negative);
               return;
            }

            paymentGatewayResponse = oAuthorizeNet.PaymentGatewayResponse;
             }
             else
             {
            // go through CIM to process transaction
            paymentGatewayResponse = service.CIMAuthorizationAndCapture(oTransactionInformation,
                                                                        CardProfile.CIMProfileId,
                                                                        CardProfile.CIMPaymentProfileId);
            if (paymentGatewayResponse.Errors.Any() || paymentGatewayResponse.GetValue(PaymentGatewayResponse.FieldNames.ResponseCode) != "1")
            {
               var message = paymentGatewayResponse.Errors.Any()
                                ? paymentGatewayResponse.Errors.Aggregate((messages, error) => messages + ", " + error)
                                : paymentGatewayResponse.GetValue(PaymentGatewayResponse.FieldNames.ResponseReasonText);
               ShowMessage(message, MessageTone.Negative);
               return;
            }
             }

             var oIAPayment = SavePayment(paymentGatewayResponse);

             StringBuilder oSpeedySpotsLineItems;
             var oLineItems = SaveLineItems(oIAPayment, out oSpeedySpotsLineItems);

             // QB Import Payment Rule
             // - All of the line items within a payment MUST associate with an actual QB Invoice and the amount on the individual line items must match up with the invoice, otherwise
             var bIsPaymentAutoImported = QuickBooksInvoiceMatching(oIAPayment);

             // Clear the invoice in memory
             Session["InvoicePayments"] = null;

             SendPaymentReceiptEmail(CardProfile, oLineItems, oIAPayment);

             SendBillingEmail(CardProfile, bIsPaymentAutoImported, oSpeedySpotsLineItems, oIAPayment);

             // Clear the invoice in memory
             Session["InvoicePayments"] = null;

             // Display the receipt
             m_divPayment.Visible = false;
             m_divReceipt.Visible = true;
        }
 private void PoorMansUIBind(CreditCardViewModel customerCreditCardViewModel)
 {
     if (customerCreditCardViewModel != null)
      {
     CreditCardId.Value = customerCreditCardViewModel.CreditCardId.ToString();
     AliasTextBox.Text = customerCreditCardViewModel.Alias;
     CreditCardTypeCombo.SelectedValue = customerCreditCardViewModel.CardType;
     LastFourOfCardLabel.Text = customerCreditCardViewModel.LastFourOfCardNumber;
     FirstNameTextBox.Text = customerCreditCardViewModel.FirstName;
     LastNameTextBox.Text = customerCreditCardViewModel.LastName;
     CompanyName.Text = customerCreditCardViewModel.CompanyName;
     ExpirationMonthCombo.SelectedValue = customerCreditCardViewModel.ExpirationMonth;
     ExpirationYearCombo.SelectedValue = customerCreditCardViewModel.ExpirationYear;
     Address1TextBox.Text = customerCreditCardViewModel.Address;
     CityTextBox.Text = customerCreditCardViewModel.City;
     StateComboBox.SelectedValue = customerCreditCardViewModel.State;
     ReceiptEmailTextBox.Text = customerCreditCardViewModel.ReceiptEmailAddressCsv;
      }
      else
      {
     RedirectMessage("~/user-creditcards.aspx", "Credit card not found.");
      }
 }