public async Task AddPaymentMethod(string userName, string creditCardNumber, string cvv, string cardHolder, DateTime expirationDate) { creditCardNumber.ThrowIfNull(); cvv.ThrowIfNull(); cardHolder.ThrowIfNull(); if (expirationDate < DateTime.UtcNow) { throw new InvalidOperationException(string.Format(ServiceErrorsConstants.InvalidUserInput, nameof(creditCardNumber), nameof(cvv), nameof(expirationDate))); } var creditCardType = CreditCardHelper.GetCreditCardType(creditCardNumber); var user = await RetrieveUser(userName); if (user.CreditCards.Any(cc => cc.CreditCardNumber == creditCardNumber && cc.CVV == cvv && cc.ExpirationDate == expirationDate)) { throw new InvalidOperationException(ServiceErrorsConstants.InvalidUserCC); } var creditCard = new CreditCard { CardType = creditCardType, CreditCardNumber = CreditCardHelper.Encrypt(creditCardNumber), CVV = cvv, IsActive = true, ExpirationDate = expirationDate, CardHolderName = cardHolder, OwnerId = user.Id, }; user.CreditCards.Add(creditCard); _usersRepository.Update(user); await _usersRepository.SaveChangesAsync(); }
public ActionResult GetTransactionById(Guid transactionID) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var response = new TransactionResponseRepresenter(); var entity = _transactionService.GetTransactionById(transactionID); var currency = _currencyService.GetCurrencyByID(entity.CurrencyID); response.Currency = currency.Name; response.Amount = entity.Amount; response.BankReferenceID = entity.BankReferenceID; response.Status = entity.Status; response.SubStatus = entity.SubStatus; var card = _cardDetailsService.GetCardDetailsByID(entity.CardID); card.CardNumber = CreditCardHelper.MaskCardNumber(card.CardNumber); response.Card = card; return(Ok(response)); }
public void AValidVisaNumberShallTestAsValid() { //Exercise var isValid = CreditCardHelper.CheckIfCreditCardNumberIsValid(ValidViasCardNumber); //Verify Assert.IsTrue(isValid); }
public void Validate() { var errors = new List <FieldError>(); if (String.IsNullOrEmpty(Name)) { errors.Add(new FieldError() { Field = nameof(Name), Error = "Credit card holder name is required" }); } if (CreditCardHelper.GetCreditCardType(Number) == null) { errors.Add(new FieldError() { Field = nameof(Number), Error = $"The number {Number} is not a valid credit card number" }); } if (!(Cvc >= 1 && Cvc <= 999)) { errors.Add(new FieldError() { Field = nameof(Month), Error = "Cvc must be a three digit number" }); } if (!(Month >= 1 && Month <= 12)) { errors.Add(new FieldError() { Field = nameof(Month), Error = "Month must be an integer between 1 and 12" }); } if (Year < 1) { errors.Add(new FieldError() { Field = nameof(Month), Error = "Year must be a positive integer greater than or equals to 1" }); } if (errors.Any()) { throw new ValidationException("Credit card information is incorrect") { FieldErrors = errors }; } }
public ActionResult FullForm(FullFormVM model) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; if (!ModelState.IsValid) { model.States = LocationsManager.GetStates(); return(View(model)); } int ncid = GetNcId(); int visitId = GetVisitId(); CustomerDT customer = new CustomerDT(); customer.SiteId = model.SiteId; customer.NcId = ncid; customer.Email = model.Email; customer.FirstName = model.FirstName; customer.LastName = model.LastName; customer.Address = model.Address; customer.City = model.City; customer.StateId = model.StateId; customer.ZipCode = model.ZipCode; CreditCardDT cc = new CreditCardDT(); cc.CardNumber = model.CardNumber; cc.CVV = model.CVV; cc.ExpDate = CreditCardHelper.GetExpDate(model.ExpMonth, model.ExpYear); CCType cardType = CCType.VISA; Enum.TryParse(model.CardType.ToString(), out cardType); cc.Type = cardType; var referrer = ReferrersManagers.GetReferrer(model.Referrer); try { customer = CustomersManager.NewCustomer(((SiteDT)ViewBag.Site), customer, cc, visitId, referrer.Id, false); } catch (Exception ex) { SendExceptionEmail(ex.ToString()); CastleClub.BusinessLogic.Utils.EventViewer.Writte("CastleClub", "CastleClubFrontend", ex.Message + "\n" + ex.ToString(), System.Diagnostics.EventLogEntryType.Error); } if (customer != null) { ViewBag.Customer = customer; } else { return(View("Error")); } return(View("Welcome")); }
private void btnOK_Click(object sender, EventArgs e) { if (ValidateForm()) { btnOK.Enabled = false; panelIndicator.Visible = true; Refresh(); string cardNumber = CreditCardHelper.NormalizeCardNumber(txtCardNumber.Text.Trim()); var expirationMonth = (ExpirationMonth)cbExpireMonths.SelectedItem; var expirationYear = (int)cbExpireYear.SelectedItem; var selectPackage = (PostClPackgae)cbPackages.SelectedItem; var cardType = CreditCardHelper.GetCardType(cardNumber); _billingCustomer = new BillingCustomer() { NameOnCard = txtNameOnCard.Text.Trim(), CardNumber = txtCardNumber.Text.Trim(), ExpirationMonth = expirationMonth.Month, ExpirationYear = expirationYear, SelectedPackage = selectPackage, SecurityCode = txtSecurityCode.Text.Trim(), DealerCity = GlobalVar.CurrentDealer.City, DealerName = GlobalVar.CurrentDealer.DealershipName, DealerPhone = GlobalVar.CurrentDealer.PhoneNumber, DealerState = GlobalVar.CurrentDealer.State, DealerStreetAddress = GlobalVar.CurrentDealer.StreetAddress, DealerZipCode = GlobalVar.CurrentDealer.ZipCode, //DifferentBillingAddress = cbDiffBilling.Checked, BillingStreetAddress = txtStreetAddress.Text.Trim(), BillingCity = txtCity.Text, BillingState = cbState.SelectedText, BillingZipCode = txtZipcode.Text, QuickBookAccountName = GlobalVar.CurrentAccount.QuickBookAccountName, FirstName = GlobalVar.CurrentAccount.FirstName, LastName = GlobalVar.CurrentAccount.LastName, CustomerEmail = GlobalVar.CurrentAccount.AccountName, CreditCardType = cardType, OneTimeSetUpFeed = cbkOnetimeSetupFeed.Checked }; bgCreditCardProcessing.RunWorkerAsync(); } else { MessageBox.Show( "Please fill correct info in required fields. ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); } }
public void AnInvalidVisaNumberShallTestAsInValid() { //Setup const string creditCardNumber = "9991111111111111"; //Exercise var isValid = CreditCardHelper.CheckIfCreditCardNumberIsValid(creditCardNumber); //Verify Assert.IsFalse(isValid); }
//private void linkWhatis_Click(object sender, EventArgs e) //{ // linkWhatis.Tag = global::VinCLAPP.Properties.Resources.securitycode; // var myToolTipTemplate = new CustomizedToolTip { AutoSize = true }; // myToolTipTemplate.SetToolTip(linkWhatis, " "); //} private void txtCardNumber_Leave(object sender, EventArgs e) { if (String.IsNullOrEmpty(txtCardNumber.Text.Trim())) { errorProvider1.SetError(txtCardNumber, "Please enter the valid card number."); } else { string cardNumber = CreditCardHelper.NormalizeCardNumber(txtCardNumber.Text.Trim()); if (!CreditCardHelper.IsCardNumberValid(cardNumber)) { errorProvider1.SetError(txtCardNumber, "Please enter the valid card number."); } else { var cardType = CreditCardHelper.GetCardType(cardNumber); if (cardType.Equals(CreditCardHelper.CardType.Amex)) { errorProvider1.SetError(txtCardNumber, ""); pcBoxCreditCardType.Visible = true; pcBoxCreditCardType.Image = global::VinCLAPP.Properties.Resources.amex_48; } else if (cardType.Equals(CreditCardHelper.CardType.Discover)) { errorProvider1.SetError(txtCardNumber, ""); pcBoxCreditCardType.Visible = true; pcBoxCreditCardType.Image = global::VinCLAPP.Properties.Resources.discover_48; } else if (cardType.Equals(CreditCardHelper.CardType.MasterCard)) { errorProvider1.SetError(txtCardNumber, ""); pcBoxCreditCardType.Visible = true; pcBoxCreditCardType.Image = global::VinCLAPP.Properties.Resources.mastercard_48; } else if (cardType.Equals(CreditCardHelper.CardType.VISA)) { errorProvider1.SetError(txtCardNumber, ""); pcBoxCreditCardType.Visible = true; pcBoxCreditCardType.Image = global::VinCLAPP.Properties.Resources.visa_48; } } } }
public void TestMasterCardValidation() { var testCards = new[] { "5555555555554444", "5105105105105100" }; foreach (var testCard in testCards) { Assert.True(CreditCardHelper.IsMasterCard(testCard), $"{testCard} is not a valid MasterCard"); } }
public IHttpActionResult Get(string cardNumber) { CreditCardModels.CreditCardInquiryRequest request = new CreditCardModels.CreditCardInquiryRequest(); CreditCardModels.CreditCardInquiryRespone response = new CreditCardModels.CreditCardInquiryRespone(); request.cardNumber = cardNumber; if (cardNumber == null || cardNumber == "") { return(BadRequest()); } var context = new ValidationContext(Request, serviceProvider: null, items: null); var validationResults = new List <ValidationResult>(); var authHeader = Request.Headers.Authorization; string featureCode = ""; request.instiutionCode = InstitutionCredentials.InstitutionCode(authHeader); request.instiutionKey = InstitutionCredentials.InstitutionKey(authHeader); var isValid = Validator.TryValidateObject(Request, context, validationResults); if (!isValid) { foreach (var validationResult in validationResults) { response.responseCode = "01"; response.responseDescription += validationResult.ErrorMessage; } return(Ok(response)); } featureCode = ConstantModels.FeatureCode_CC; string rc = CreditCardValidation.ValidateInputInquiryCC(ref request, featureCode);//telkomHelper.ValidateInputInquiryTelkom(ref request, IP); if (rc.Equals("0005")) { response = CreditCardHelper.InquiryCC(ref request, featureCode); //accountOnline.inquiryAccountOnline(ref request, IP); } else { response.responseCode = rc; response.responseDescription = ResponseCodeModels.GetResponseDescription(response.responseCode); } return(Ok(response)); }
public void GetTypeTests() { Assert.AreEqual(CreditCardType.AmericanExpress, CreditCardHelper.GetType("378282246310005")); Assert.AreEqual(CreditCardType.AmericanExpress, CreditCardHelper.GetType("371449635398431")); Assert.AreEqual(CreditCardType.AmericanExpress, CreditCardHelper.GetType("378734493671000")); Assert.AreEqual(CreditCardType.Discover, CreditCardHelper.GetType("6011111111111117")); Assert.AreEqual(CreditCardType.Discover, CreditCardHelper.GetType("6011000990139424")); Assert.AreEqual(CreditCardType.MasterCard, CreditCardHelper.GetType("5555555555554444")); Assert.AreEqual(CreditCardType.Visa, CreditCardHelper.GetType("4111111111111111")); Assert.AreEqual(CreditCardType.Visa, CreditCardHelper.GetType("4012888888881881")); Assert.AreEqual(CreditCardType.Visa, CreditCardHelper.GetType("4222222222222")); }
public void TestVisaValidation() { var testCards = new[] { "4111111111111111", "4012888888881881", "4222222222222" }; foreach (var testCard in testCards) { Assert.True(CreditCardHelper.IsVisa(testCard), $"{testCard} is not a valid Visa"); } }
public void AreCorrectBrands() { // AMEX: 342955624318368 // Discover: 6011624665174125 // MasterCard: 5120939736834980 // Visa: 4116509050569147 Assert.AreEqual(CreditCardBrand.AmericanExpress, CreditCardHelper.GetBrand("342955624318368")); Assert.AreEqual(CreditCardBrand.Discover, CreditCardHelper.GetBrand("6011624665174125")); Assert.AreEqual(CreditCardBrand.MasterCard, CreditCardHelper.GetBrand("5120939736834980")); Assert.AreEqual(CreditCardBrand.Visa, CreditCardHelper.GetBrand("4116509050569147")); // Some made up invalid credit card numbers Assert.AreEqual(CreditCardBrand.Unknown, CreditCardHelper.GetBrand("9116509050569147")); }
public void IdentificationTests() { Assert.AreEqual(CreditCardType.AmericanExpress, CreditCardHelper.IdentifyType("371449635398431"), "Failed to identify AmericanExpress"); Assert.AreEqual(CreditCardType.AmericanExpress, CreditCardHelper.IdentifyType("371449635XXxX31"), "Failed to identify AmericanExpress X"); Assert.AreEqual(CreditCardType.DinersClub, CreditCardHelper.IdentifyType("30569309025904"), "Failed to identify DinersClub"); Assert.AreEqual(CreditCardType.DinersClub, CreditCardHelper.IdentifyType("305693XXXX59xX"), "Failed to identify DinersClub X"); Assert.AreEqual(CreditCardType.Mastercard, CreditCardHelper.IdentifyType("5555555555554444"), "Failed to identify Mastercard"); Assert.AreEqual(CreditCardType.Mastercard, CreditCardHelper.IdentifyType("5555555555XxX444"), "Failed to identify Mastercard X"); Assert.AreEqual(CreditCardType.VISA, CreditCardHelper.IdentifyType("4111111111111111"), "Failed to identify VISA"); Assert.AreEqual(CreditCardType.VISA, CreditCardHelper.IdentifyType("41111111111XxXXX"), "Failed to identify VISA X16"); Assert.AreEqual(CreditCardType.VISA, CreditCardHelper.IdentifyType("41111111XXxxX"), "Failed to identify VISA X13"); Assert.AreEqual(CreditCardType.VISA, CreditCardHelper.IdentifyType("4111 1111 1111 1111"), "Failed to identify VISA spaced"); Assert.AreEqual(CreditCardType.Unknown, CreditCardHelper.IdentifyType("000000000000XXxx"), "Failed to identify Unknown X"); }
private LogModel Capture(LogModel log) { // Convert to Json string for Filter purpose var logJsonStr = log.ToJsonString(); // Filter Credit Card logJsonStr = CreditCardHelper.Filter(logJsonStr); // Update log by filtered info log = JsonConvert.DeserializeObject <LogModel>(logJsonStr); Push(log); return(log); }
public async Task <IActionResult> GetTransactionsByMerchantID(Guid merchantID) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var transactions = await _transactionService.GetTransactionsByMerchantID(merchantID).ConfigureAwait(false); transactions.ForEach(x => x.Card.CardNumber = CreditCardHelper.MaskCardNumber(x.Card.CardNumber)); if (!transactions.Any()) { return(NotFound()); } return(Ok(transactions)); }
private bool ValidateForm() { bool finalFlag = false; bool flag1 = String.IsNullOrEmpty(txtCardNumber.Text.Trim()); errorProvider1.SetError(txtCardNumber, flag1 ? "Please enter a valid card number" : ""); bool flag17 = false; if (!flag1) { string cardNumber = CreditCardHelper.NormalizeCardNumber(txtCardNumber.Text.Trim()); flag17 = !CreditCardHelper.IsCardNumberValid(cardNumber); errorProvider8.SetError(txtCardNumber, flag17 ? "Please enter a valid card number" : ""); } bool flag2 = String.IsNullOrEmpty(txtNameOnCard.Text.Trim()); errorProvider2.SetError(txtNameOnCard, flag2 ? "Please enter a valid name on the card" : ""); bool flag3 = String.IsNullOrEmpty(txtSecurityCode.Text.Trim()); errorProvider3.SetError(txtSecurityCode, flag3 ? "Please enter a valid security code" : ""); bool flag9 = String.IsNullOrEmpty(txtStreetAddress.Text.Trim()); errorProvider5.SetError(txtStreetAddress, flag9 ? "Please enter dealership street address" : ""); bool flag10 = String.IsNullOrEmpty(txtZipcode.Text.Trim()); errorProvider6.SetError(txtZipcode, flag10 ? "Please enter zip code" : ""); bool flag11 = String.IsNullOrEmpty(txtCity.Text.Trim()); errorProvider7.SetError(txtCity, flag11 ? "Please enter city" : ""); bool flag12 = cbState.SelectedItem == null; finalFlag = !flag1 && !flag2 && !flag3 && !flag9 && !flag10 && !flag11 && !flag12 && !flag17; return(finalFlag); }
private void btnOK_Click(object sender, EventArgs e) { if (ValidateForm()) { btnOK.Enabled = false; panelIndicator.Visible = true; Refresh(); string cardNumber = CreditCardHelper.NormalizeCardNumber(txtCardNumber.Text.Trim()); var expirationMonth = (ExpirationMonth)cbExpireMonths.SelectedItem; var expirationYear = (int)cbExpireYear.SelectedItem; var selectedState = (UsState)cbState.SelectedItem; //if(cardNumber.Length>=15) Properties.Settings.Default.cardnumber = cardNumber; Properties.Settings.Default.securitycode = txtSecurityCode.Text; Properties.Settings.Default.expirationmonth = expirationMonth.Month; Properties.Settings.Default.expirationyear = expirationYear; Properties.Settings.Default.cardfirstname = txtFirstName.Text; Properties.Settings.Default.cardlastname = txtLastName.Text; Properties.Settings.Default.cardaddress = txtStreetAddress.Text; Properties.Settings.Default.cardcity = txtCity.Text; Properties.Settings.Default.cardstate = selectedState.StateAbbr; Properties.Settings.Default.cardzipcode = txtZipcode.Text; Properties.Settings.Default.cardcontactname = txtContactName.Text; Properties.Settings.Default.cardcontactphone = txtPhoneNumber.Text; Properties.Settings.Default.cardcontactemail = txtContactEmailAddress.Text; Properties.Settings.Default.Save(); this.Close(); if (_frmMain != null) { _frmMain.RunFirstExecuteNewVersion(); } } }
public override bool IsValid(object value) { string text = value as string; if (String.IsNullOrEmpty(text)) { return(true); } if (ValidationHelper.IsValidCreditCardNumber(text)) { var brand = CreditCardHelper.GetType(text); return(types.Any(b => b == brand)); } return(false); }
public LogModel Capture(LogModel log) { // Convert to Json string for Filter purpose var logJsonStr = log.ToJsonString(); // Filter Credit Card logJsonStr = CreditCardHelper.Filter(logJsonStr); // Update log by filtered info log = JsonConvert.DeserializeObject <LogModel>(logJsonStr); // To Console if (_options.IsEnableLogToConsole) { WriteConsole(log); } Push(log); return(log); }
public async Task <IActionResult> Checkout() { var creditCards = (await _userService.PaymentMethods(User.Identity.Name)) .Select(u => new SelectListItem { Text = CreditCardHelper.ReplaceCreditCardUI(u.CreditCardNumber), Value = u.Id.ToString(), }) .ToList(); var cartProducts = await GetCurrentUserCartItems(); var user = await _userManager.FindByNameAsync(User.Identity.Name); var model = new UserCheckoutCartViewModel { CartProducts = cartProducts, CreditCards = creditCards, TotalCost = cartProducts.Sum(p => p.Price), PhoneNumber = user.PhoneNumber, }; return(View(model)); }
public async Task <IActionResult> Index() { var user = await _userManager.GetUserAsync(User); if (user == null) { throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } var creditCards = await _userService.PaymentMethods(User.Identity.Name); List <SelectListItem> modelCreditCards = null; if (creditCards.Any()) { modelCreditCards = creditCards .Select(c => new SelectListItem { Text = CreditCardHelper.ReplaceCreditCardUI(c.CreditCardNumber), Value = c.Id.ToString(), }) .ToList(); } var model = new IndexViewModel { Username = user.UserName, CurrentBalance = user.AccountBalance, Email = user.Email, PhoneNumber = user.PhoneNumber, IsEmailConfirmed = user.EmailConfirmed, StatusMessage = StatusMessage, CreditCards = modelCreditCards ?? new List <SelectListItem>(), }; return(View(model)); }
public async Task <IActionResult> ProcessTransaction([FromBody] TransactionRepresenter transaction) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (transaction == null) { return(BadRequest("Transaction data not found")); } if (await _transactionDetailsValidatorService.ValidateAsync(transaction).ConfigureAwait(false)) { return(BadRequest(_transactionDetailsValidatorService.GetErrors())); } var creditCardValidationResult = CreditCardHelper.IsCreditCardInfoValid(transaction); if (!creditCardValidationResult) { return(BadRequest("Invalid Credit Card data")); } var transactionDetails = _transactionDetailsValidatorService.GetTransactionDetails(); var cardEntity = await _cardDetailsService.CreateCardDetailsAsync(transaction).ConfigureAwait(false); BankResponseDto bankResponse = await _bankService.ProcessTransactionAsync(transaction, transactionDetails.Bank.BankURL).ConfigureAwait(false); Transaction transactionEntity = GetTransactionEntity(bankResponse, transaction, transactionDetails, cardEntity); await _transactionService.CreateTransactionAsync(transactionEntity).ConfigureAwait(false); return(Ok(transactionEntity)); }
public IActionResult Checkout(CreditCardViewModel creditcard) { var orderId = Guid.NewGuid(); var OrderMain = orderId.ToString(); try { // Validate card type. CardType expectedCardType = CreditCardHelper.GetCardType(creditcard.CreditCardNumber); if (expectedCardType == CardType.Unknown || expectedCardType != creditcard.CreditCardType) { ModelState.AddModelError("CreditCardType", "The Credit Card Type field does not match against the credit card number."); } if (!ModelState.IsValid) { throw new Exception("Creditcard is invalid"); } var user = _userManager.GetUserId(User); var cart = HttpClientHelper.GetCollection <Assignment2WebAPI.REST.RESTCart>($"cart/{user}"); if (cart.data.Count() == 0) { throw new Exception("No items in cart"); } //create the order _context.Add(new OrderHeader { OrderMain = orderId.ToString() }); foreach (var item in cart.data) { // add the order _context.Add( new Assignment2.Models.Order { ProductID = item.ProductID, OrderMain = orderId.ToString(), StoreID = item.StoreID, CustomerID = item.CustomerID, Quantity = item.Quantity } ); // clear the cart var cartitem = _context.Carts.Where(c => c.ProductID == item.ProductID) .Where(c => c.StoreID == item.StoreID).First(); _context.Remove(cartitem); // reduce the stock var storeInventory = _context.StoreInventories.Where(c => c.StoreID == item.StoreID) .Where(c => c.ProductID == item.ProductID).First(); storeInventory.StockLevel = storeInventory.StockLevel - item.Quantity; _context.Update(storeInventory); } _context.SaveChanges(); ViewBag.OrderMain = OrderMain; var orders = _context.Orders.Include(o => o.Product).Include(o => o.Store).Where(o => o.OrderMain == OrderMain).ToList(); return(View("~/Views/Customer/Receipt.cshtml", orders)); } catch (Exception e) { ViewBag.ErrorMsg = e.Message; return(View("~/Views/Common/Error.cshtml")); } }
public async Task <dynamic> ProcessRequest(Request request) { request.isValid = true; var errorModel = new ErrorModel(); try { var val = await _messageService.GetErrorMessage("ECord1"); Logger.InformationLog($"In TransactionService.ProcessRequest, Process Request Start"); var merchantInfoResult = await _paymentService.GetMerchantInfo(errorModel, request.MerchantInfo.MerchantKey, request.MerchantInfo.IpAddress, Convert.ToInt32(request.MerchantInfo.ProcessorId)); if (errorModel.validationFailedMsg.Count > 0 || (errorModel.errors != null && errorModel.errors.Count > 0)) { GatewayResult Result = BuildValidationOrErrorFailedStatusReturnObject(errorModel, request.MerchantInfo.TransactionType); return(Result); } Logger.InformationLog($"In TransactionController.ProcessRequest, GetMerchantInfo: " + JsonConvert.SerializeObject(merchantInfoResult)); //If creditCardCryptogram is Not Null if (!string.IsNullOrEmpty(request.CreditCardCryptogram) && string.IsNullOrEmpty(request.CardNumber)) { var creditCardFromCryptogramResult = await _paymentService.GetCreditCardFromCryptogram(new PaymentDataFromCryptogramInput() { Cryptogram = request.CreditCardCryptogram, TransactionType = Convert.ToString(request.MerchantInfo.TransactionType) }); if (creditCardFromCryptogramResult.Message != null) { request.CardNumber = creditCardFromCryptogramResult.CardNumber; request.CardExpMonth = Convert.ToInt32(creditCardFromCryptogramResult.CardExpMonth); request.CardExpYear = Convert.ToInt32(creditCardFromCryptogramResult.CardExpYear); request.CVV = Convert.ToInt32(creditCardFromCryptogramResult.CardSecurityCode); request.ConvFeeAmount = Convert.ToDecimal(creditCardFromCryptogramResult.FeeAmount); } } //If token number is null then call tokenizer to generate token number if (string.IsNullOrEmpty(request.CreditCardToken) && !string.IsNullOrEmpty(request.CardNumber)) { request.CreditCardToken = _paymentService.GetTokenFromCreditCard(request.CardNumber); } var oldToken = request.CreditCardToken; //Check null values and MagData is empty var isNullProperties = (!string.IsNullOrEmpty(request.CreditCardToken) && request.CardExpMonth != null && request.CardExpYear != null && string.IsNullOrEmpty(request.MagData)); var process = new Process(); if (isNullProperties) { request.isValid = false; process.ExpMonth = request.CardExpMonth; process.ExpYear = request.CardExpYear; process.CardType = CreditCardHelper.GetCreditCardType(request.CardNumber ?? _paymentService.GetCreditCardNumberFromToken(request.CreditCardToken)); process.Token = request.CreditCardToken; //GetUpdatedCardDetails process = await _paymentService.GetUpdatedCardDetails(process); //Re asign the expMonth, expYear and token request.CardExpMonth = process.ExpMonth; request.CardExpYear = process.ExpYear; request.CreditCardToken = process.Token; } process = ValidateExpMonthAndYear(errorModel, process); if (errorModel.validationFailedMsg.Count > 0 || (errorModel.errors != null && errorModel.errors.Count > 0)) { GatewayResult Result = BuildValidationOrErrorFailedStatusReturnObject(errorModel, request.MerchantInfo.TransactionType); return(Result); } ValidateExtensions.ValidateIpAddress(merchantInfoResult.IpAddress, errorModel); if (merchantInfoResult.AccountType == IndustryTypesEnum.ach.ToString()) { errorModel.errors.Add(string.Format("Invalid Account Type For Transaction ('{0}')", merchantInfoResult.AccountType)); return(null); } var ValidateHelper = new ValidateHelper(); var orderId = new ValidateHelper().ValidateOrderIdAndGenerateNewOrderIdIfNeededAsync(request, merchantInfoResult, errorModel); process = await _paymentService.ValidateInitAndBuildProcessObject(request, merchantInfoResult, errorModel, process); if (!request.isValid) { errorModel.validationFailedMsg.Add(new ValidationFailedMsg() { Key = "", Message = "" }); //On Hold } if (errorModel.errors.Count > 0 || errorModel.validationFailedMsg.Count > 0) { GatewayResult Result = BuildValidationOrErrorFailedStatusReturnObject(errorModel, request.MerchantInfo.TransactionType); return(Result); } if (!string.IsNullOrWhiteSpace(oldToken) && !string.IsNullOrWhiteSpace(process.Token)) { if (!oldToken.Equals(process.Token)) { process.CardNumber = _paymentService.GenerateCardNumberUsingToken(process.Token.Trim()); } } if (process != null && request.OtherFields != null && request.OtherFields.Count > 0) { _paymentService.ValidateAndAddCustomFields(process, request.OtherFields /*, info.processor*/);// On Hold } if (!string.IsNullOrWhiteSpace(request.CreditCardCryptogram)) { request.expireCryptogram = CryptogramHelper.ForceExpireCryptogramAsync(_config.GetSection("CryptogramApi").Value, request); } IndustryTypesEnum industryType = request.MerchantInfo.accountType.ParseEnum <IndustryTypesEnum>(); return(process); } catch (Exception ex) { Logger.ErrorLog($"Exception In TransactionService.ProcessRequest. exception={ex.Message}, Trace={ex.StackTrace}"); throw ex; } finally { Logger.InformationLog($"Out TransactionService.ProcessRequest, Process Request End"); } }
public void ConfigureMapping(Profile profile) { profile.CreateMap <CreditCard, UserPaymentMethodsModel>() .ForMember(c => c.CreditCardNumber, opts => opts.MapFrom(c => CreditCardHelper.Decrypt(c.CreditCardNumber))); }
public static string CreateCustomer(string data, bool sendEmail) { try { var hash = EncryptionHelper.Unpack(EncryptionHelper.Decrypt(data, cryptKey)); GCDSite site = new GCDSite(hash); GCDCustomer customer = new GCDCustomer(hash); customer.CreatedAt = DateTime.Now; customer.Success = false; if (!string.IsNullOrEmpty(site.GroupID) && !string.IsNullOrEmpty(customer.CreditCardNumber) && !string.IsNullOrEmpty(customer.Email)) { CustomerDT customerDT = new CustomerDT() { Address = customer.Address1, BadLoginCount = 0, CancelledDate = null, City = customer.City, ClearPassword = customer.Password, CreatedAt = customer.CreatedAt, Email = customer.Email, FirstName = customer.FirstName, LastName = customer.LastName, MemberId = customer.MemberID, NcId = 0, NextBillDate = DateTime.Now.AddDays(30), Phone = customer.Phone, StateId = CastleClub.BusinessLogic.Managers.LocationsManager.GetStates().FirstOrDefault(x => x.Name.ToLower() == customer.State.ToLower()).Id, Status = CustomerStatus.ACTIVE, ZipCode = customer.Zip }; //var siteDT = CastleClub.BusinessLogic.Managers.SitesManager.GetSite(customerDT.SiteId); customerDT = CastleClub.BusinessLogic.Managers.CustomersManager.NewCustomer(site.GroupID, customerDT, customer.CreditCardNumber, CreditCardHelper.GetExpDate(customer.CreditCardMonthExpired, customer.CreditCardYearExpired)); if (customerDT != null) { customer.Success = true; //if (sendEmail) /**** * if ((siteDT.SendWelcomeEmail) && (siteDT.WelcomeEmailDelay != null) && (siteDT.WelcomeEmailDelay == 0)) * //send welcome email if it hasn't a delay * { * string smtpAddress = siteDT.SmtpAddress;//CastleClub.BusinessLogic.Data.GlobalParameters.Smtp; * //var siteDT = CastleClub.BusinessLogic.Managers.SitesManager.GetSite(customerDT.SiteId); * * string emailFrom = siteDT.Email; * string passwordEmail = siteDT.PasswordEmail;//CastleClub.BusinessLogic.Data.GlobalParameters.EmailPassword; * string subject = string.Format(Properties.Resources.WelcomeSubjectEmail, siteDT.Name); * // + " " + customer.LastName * string body = string.Format(Properties.Resources.WelcomeBodyEmail, customer.FirstName, * customer.Email, customer.Password, siteDT.Name, siteDT.Name, "PartsGeek", * siteDT.Price, siteDT.PricePerQuarter, siteDT.Phone, siteDT.Email, siteDT.OfferDomain); * * Utils.Email.SendEmail(emailFrom, passwordEmail, smtpAddress, subject, body, new List<string>() { customer.Email }, true); * } * **/ } } else { customer.Messages = "Credit card and email are necessary."; } return(EncryptionHelper.Encrypt(customer.ToString(), cryptKey)); }catch (Exception e) { Utils.EventViewer.Writte("WEBSERVICE", "Create Customers", e.Message + " " + e.StackTrace, System.Diagnostics.EventLogEntryType.Error); throw e; } }
public bool UpdateUserCard(UserCardDetailModel model) { var userCardDetailsByUserId = _userRepository.GetUserCardDetailsByUserId(model.UserId.Value); if (userCardDetailsByUserId != null) { try { var trimCard = model.CardNumber.Replace(" ", ""); if (trimCard.Contains("XXXXXX")) { userCardDetailsByUserId.ExpiredMonth = model.ExpiredMonth; userCardDetailsByUserId.ExpiredYear = model.ExpiredYear; userCardDetailsByUserId.CVC = model.CVC; userCardDetailsByUserId.PhoneNumber = model.PhoneNumber; userCardDetailsByUserId.ModifiedDate = DateTime.Now; return(_userRepository.UpdateUserCardData(userCardDetailsByUserId)); } else { var customers = new StripeCustomerService(); StripeConfiguration.SetApiKey(ConfigurationManager.AppSettings["StripPublishKey"]); var tokenService = new StripeTokenService(); var token = tokenService.Create(new StripeTokenCreateOptions { Card = new StripeCreditCardOptions { Cvc = model.CVC.ToString(), Number = model.CardNumber.Replace(" ", ""), ExpirationMonth = model.ExpiredMonth, ExpirationYear = model.ExpiredYear } }); StripeConfiguration.SetApiKey(ConfigurationManager.AppSettings["StripSecretKey"]); var customerId = customers.Create(new StripeCustomerCreateOptions { SourceToken = token.Id }); var cardType = CreditCardHelper.GetCardType(model.CardNumber); StripeCardService card = new StripeCardService(); var cardToken = CreditCardHelper.GetCardTokens(token.StripeCard.Brand); var response = card.Create(customerId.Id, new StripeCardCreateOptions { SourceToken = cardToken }); userCardDetailsByUserId.CardNumber = _cryptoGraphy.EncryptString(model.CardNumber); userCardDetailsByUserId.CardType = cardType.ToString(); userCardDetailsByUserId.ExpiredMonth = model.ExpiredMonth; userCardDetailsByUserId.ExpiredYear = model.ExpiredYear; userCardDetailsByUserId.CVC = model.CVC; userCardDetailsByUserId.CreditCardId = customerId.Id; userCardDetailsByUserId.PhoneNumber = model.PhoneNumber; userCardDetailsByUserId.ModifiedDate = DateTime.Now; return(_userRepository.UpdateUserCardDetails(userCardDetailsByUserId)); } } catch (StripeException ex) { switch (ex.StripeError.ErrorType) { case "card_error": throw _exception.ThrowException(System.Net.HttpStatusCode.BadRequest, "", ex.StripeError.Message); case "api_connection_error": break; case "api_error": break; case "authentication_error": break; case "invalid_request_error": break; case "rate_limit_error": break; case "validation_error": break; default: // Unknown Error Type break; } } } else { return(false); } return(false); }
private async Task ExecuteAddCardCommand() { if (string.IsNullOrEmpty(CardName.DefaultString())) { await DisplayAlert("Information", "Enter the name!", "OK"); return; } if (string.IsNullOrEmpty(CardNumber.DefaultString())) { await DisplayAlert("Information", "Enter the card number!", "OK"); return; } if (CardNumber.DefaultString().Length < 16 || CardNumber.DefaultString().Length < 15) { await DisplayAlert("Information", "Incomplete card number!", "OK"); return; } if (!CreditCardHelper.IsValidCreditCardNumber(CardNumber)) { await DisplayAlert("Information", "Card number is invalid!", "OK"); return; } if (string.IsNullOrEmpty(CardExpirationDate.DefaultString())) { await DisplayAlert("Information", "Enter the expiration date!", "OK"); return; } if (string.IsNullOrEmpty(CardCVV.DefaultString())) { await DisplayAlert("Information", "Enter the secuity code!", "OK"); return; } var confirm = await DisplayAlert("Confirmation", "Confirm registration?", "YES", "NO"); if (confirm) { var card = new Card() { cardName = CardName, cardNumber = CardNumber.RemoveNonNumbers(), cardExpirationDate = CardExpirationDate, cardCVV = CardCVV, cardFlag = CardFlag }; card.cardFlag = CreditCardHelper.FindFlagCard(card.cardNumber); MessagingCenter.Send(this, "addCard", card); await PopupNavigation.Instance.PopAsync(true); } }
public bool AddUserCardDetails(UserCardDetailModel model) { try { _userCardDetailValidators.Validate(model); var errorMessage = string.Empty; var userCardDetailModel = new UserCardDetailModel(); var user = _accessTokenRepository.GetUser(model.UserId.Value); if (user == null) { throw _exception.ThrowException(System.Net.HttpStatusCode.BadRequest, "", "Användare finns inte."); } //var cardExist = _userRepository.GetUserCardDetailByCardNumber(model.CardNumber, model.UserId.Value); //if (cardExist != null) // throw _exception.ThrowException(System.Net.HttpStatusCode.BadRequest, "", "Kortnummer finns redan."); //if (response.CvcCheck.ToLower() != "pass") // throw _exception.ThrowException(System.Net.HttpStatusCode.BadRequest, "", "Card is not valid."); //var isValidCard = CreditCardHelper.IsCardNumberValid(model.CardNumber, out errorMessage); //if (!isValidCard) // throw _exception.ThrowException(System.Net.HttpStatusCode.BadRequest, "", errorMessage); var updateCard = UpdateUserCard(model); if (!updateCard) { var customers = new StripeCustomerService(); StripeConfiguration.SetApiKey(ConfigurationManager.AppSettings["StripPublishKey"]); var tokenService = new StripeTokenService(); var token = tokenService.Create(new StripeTokenCreateOptions { Card = new StripeCreditCardOptions { Cvc = model.CVC.ToString(), Number = model.CardNumber.Replace(" ", ""), ExpirationMonth = model.ExpiredMonth, ExpirationYear = model.ExpiredYear } }); StripeConfiguration.SetApiKey(ConfigurationManager.AppSettings["StripSecretKey"]); var customerId = customers.Create(new StripeCustomerCreateOptions { SourceToken = token.Id }); var cardType = CreditCardHelper.GetCardType(model.CardNumber); StripeCardService card = new StripeCardService(); var cardToken = CreditCardHelper.GetCardTokens(token.StripeCard.Brand); var response = card.Create(customerId.Id, new StripeCardCreateOptions { SourceToken = cardToken }); var userCardDetails = new UserCardDetails { UserId = model.UserId, CardNumber = _cryptoGraphy.EncryptString(model.CardNumber), CardType = cardType.ToString(), ExpiredMonth = model.ExpiredMonth, ExpiredYear = model.ExpiredYear, CVC = model.CVC, CreditCardId = customerId.Id, PhoneNumber = model.PhoneNumber, CreatedDate = DateTime.Now, ModifiedDate = DateTime.Now }; var userCardDetailId = _userRepository.AddUserCardDetails(userCardDetails); } } catch (StripeException ex) { switch (ex.StripeError.ErrorType) { case "card_error": throw _exception.ThrowException(System.Net.HttpStatusCode.BadRequest, "", ex.StripeError.Message); case "api_connection_error": break; case "api_error": break; case "authentication_error": break; case "invalid_request_error": break; case "rate_limit_error": break; case "validation_error": break; default: // Unknown Error Type break; } } return(true); }