private StripeCard GetCardById(string customerId, string cardId)
        {
            var        cardService = new StripeCardService();
            StripeCard stripeCard  = cardService.Get(customerId, cardId);

            return(stripeCard);
        }
Ejemplo n.º 2
0
        public async Task ExecuteGetCardDetailsCommand()
        {
            if (IsBusy)
            {
                return;
            }
            IsBusy = true;
            try
            {
                string  id;
                var     loginProvider = DependencyService.Get <ILoginProvider>();
                Account acc           = loginProvider.RetreiveAccountFromSecureStore();
                acc.Properties.TryGetValue(Constants.stripeAccountIdPropertyName, out id);

                var stripeService = (StripeService)ServiceLocator.Instance.Resolve <IStripeProvider>();

                StripeCard response = await stripeService.RetreiveCreditCard(id);

                CardNumber      = "XXXX XXXX XXXX " + response.Number;
                CVC             = response.CVC;
                ExpirationDateM = response.ExpiryMonth.ToString();
                ExpirationDateY = response.ExpiryYear.ToString();
            }
            catch (Exception ex)
            {
                await Application.Current.MainPage.DisplayAlert("Items Not Loaded", ex.Message, "OK");
            }
            finally
            {
                IsBusy = false;
            }
        }
        public static PaymentInformationReturn ToPaymentInformationReturn(this StripeCard card, StripeCustomer customer)
        {
            return(new PaymentInformationReturn
            {
                Email = customer?.Email,

                Name = card?.Name,
                Brand = card?.Brand,
                Last4 = card?.Last4,

                ExpirationMonth = card?.ExpirationMonth,
                ExpirationYear = card?.ExpirationYear,
                Country = card?.Country,
                CvcCheck = card?.CvcCheck,

                AddressCity = card?.AddressCity,
                AddressCountry = card?.AddressCountry,
                AddressLine1 = card?.AddressLine1,
                AddressLine1Check = card?.AddressLine1Check,
                AddressLine2 = card?.AddressLine2,
                AddressState = card?.AddressState,
                AddressZip = card?.AddressZip,
                AddressZipCheck = card?.AddressZipCheck
            });
        }
        public async Task <IActionResult> Payment(int id)
        {
            var user = await GetCurrentUserAsync();

            try
            {
                var donation = _donationService.GetById(id);
                var detail   = (DonationViewModel)donation;
                List <CountryViewModel> countryList = GetCountryList();

                // Check for existing customer
                // edit = 1 means user wants to edit the credit card information
                if (!string.IsNullOrEmpty(user.StripeCustomerId))
                {
                    try
                    {
                        var            CustomerService   = new StripeCustomerService(_stripeSettings.Value.SecretKey);
                        StripeCustomer objStripeCustomer = CustomerService.Get(user.StripeCustomerId);
                        StripeCard     objStripeCard     = null;

                        if (objStripeCustomer.Sources != null && objStripeCustomer.Sources.TotalCount > 0 && objStripeCustomer.Sources.Data.Any())
                        {
                            objStripeCard = objStripeCustomer.Sources.Data.FirstOrDefault().Card;
                        }

                        if (objStripeCard != null && !string.IsNullOrEmpty(objStripeCard.Id))
                        {
                            CustomerRePaymentViewModel customerRePaymentViewModel = CustomerRepaymentModelData(user, donation, detail, countryList, objStripeCustomer, objStripeCard);
                            return(View("RePayment", customerRePaymentViewModel));
                        }
                    }
                    catch (StripeException ex)
                    {
                        log = new EventLog()
                        {
                            EventId = (int)LoggingEvents.GET_ITEM, LogLevel = LogLevel.Error.ToString(), Message = ex.Message, StackTrace = ex.StackTrace, Source = ex.Source, EmailId = user.Email
                        };
                        _loggerService.SaveEventLogAsync(log);
                        ModelState.AddModelError("CustomerNotFound", ex.Message);
                    }
                }

                CustomerPaymentViewModel customerPaymentViewModel = GetCustomerPaymentModel(user, donation, detail, countryList);
                return(View("Payment", customerPaymentViewModel));
            }
            catch (Exception ex)
            {
                log = new EventLog()
                {
                    EventId = (int)LoggingEvents.GET_ITEM, LogLevel = LogLevel.Error.ToString(), Message = ex.Message, StackTrace = ex.StackTrace, Source = ex.Source, EmailId = user.Email
                };
                _loggerService.SaveEventLogAsync(log);
                return(RedirectToAction("Error", "Error500", new ErrorViewModel()
                {
                    Error = ex.Message
                }));
            }
        }
        public void CreateCard(string customerId, string tokenId)
        {
            var myCard = new StripeCardCreateOptions();

            myCard.SourceToken = tokenId;

            var        cardService = new StripeCardService();
            StripeCard stripeCard  = cardService.Create(customerId, myCard); // optional isRecipient
        }
Ejemplo n.º 6
0
        public async Task <StripeResponse> ChargeCustomer(StripeCharge charge)
        {
            //Dictionary<string, string> parameters = new Dictionary<string, string>();
            //parameters.Add("customerId", customerId);

            StripeResponse temp = await cloudService.client.InvokeApiAsync <StripeCharge, StripeResponse>("StripeCharge", charge);

            StripeCard card = JsonConvert.DeserializeObject <StripeCard>(temp.ObjectJson);

            return(temp);
        }
        private StripeCard CreateCard(string tokenId, string customerId)
        {
            var myCard = new StripeCardCreateOptions
            {
                SourceToken = tokenId
            };

            var        cardService = new StripeCardService();
            StripeCard stripeCard  = cardService.Create(customerId, myCard); // optional isRecipient

            return(stripeCard);
        }
Ejemplo n.º 8
0
        public async Task <StripeCard> RetreiveCreditCard(string customerId)
        {
            Dictionary <string, string> parameters = new Dictionary <string, string>();

            parameters.Add("customerId", customerId);

            StripeResponse temp = await cloudService.client.InvokeApiAsync <StripeResponse>("Stripe", HttpMethod.Get, parameters);

            StripeCard card = JsonConvert.DeserializeObject <StripeCard>(temp.ObjectJson);

            return(card);
        }
Ejemplo n.º 9
0
        public IHttpActionResult AddCustomerPaymentMethod(PaymentRequestModel oPaymentRequest)
        {
            string sIPAddress = Request.GetOwinContext().Request.RemoteIpAddress;

            try
            {
                string             sStripeCustomerId   = oUserRepo.GetStripeCustomerId(oPaymentRequest.UserId);
                StripeCard         oStripeCard         = oStripeCustomerHandler.AddCustomerPaymentMethod(sStripeCustomerId, oPaymentRequest.Token);
                StripeSubscription oStripeSubscription = oStripeCustomerHandler.CreateNewSubscription(sStripeCustomerId);
                oLogger.LogData("ROUTE: api/Payments/{UserId}/CancelSubscription; METHOD: POST; IP_ADDRESS: " + sIPAddress);
                return(Json(oStripeCard.Id));
            }
            catch (Exception ex)
            {
                oLogger.LogData("ROUTE: api/Payments/PaymentMethod; METHOD: POST; IP_ADDRESS: " + sIPAddress + "; EXCEPTION: " + ex.Message + "; INNER EXCEPTION: " + ex.InnerException);
                return(InternalServerError());
            }
        }
        public Task <DomainCard> AddAsync(DomainCardCreateOptions options)
        {
            return(Task.Run(() =>
            {
                try
                {
                    StripeCardCreateOptions createOptions =
                        _mapper.Map <DomainCardCreateOptions, StripeCardCreateOptions>(options);

                    StripeCard card = _service.Create(options.CustomerId, createOptions);
                    return Task.FromResult(_mapper.Map <StripeCard, DomainCard>(card));
                }
                catch (StripeException e)
                {
                    throw new BillingException(string.Format("Failed to register card in billing system for customer {0}: {1}", options.CustomerId, e));
                }
            }));
        }
Ejemplo n.º 11
0
        public ActionResult CancelSubscription(long userID)
        {
            string         customerID      = Convert.ToString(SessionController.UserSession.CustomerID);
            var            customerService = new StripeCustomerService();
            StripeCustomer stripeCustomer  = customerService.Get(customerID);

            var subscriptionID = stripeCustomer.Subscriptions.Data[0].Id;

            var subscriptionService = new StripeSubscriptionService();
            var status = subscriptionService.Cancel(subscriptionID, true); // optional cancelAtPeriodEnd flag

            SessionController.UserSession.IsPaid = false;

            //Delete the customer's card from stripe
            var           cardService = new StripeCardService();
            StripeCard    stripeCard  = cardService.Get(customerID, stripeCustomer.DefaultSourceId);
            StripeDeleted card        = cardService.Delete(customerID, stripeCard.Id);

            return(Json(status, JsonRequestBehavior.AllowGet));
        }
Ejemplo n.º 12
0
        public ActionResult AddCustomer(string stripeEmail, string stripeToken)
        {
            //create customer with stripeToken
            var myCustomer = new StripeCustomerCreateOptions();

            myCustomer.Email       = stripeEmail;
            myCustomer.SourceToken = stripeToken;

            //get customerID
            var            customerService = new StripeCustomerService();
            StripeCustomer stripeCustomer  = customerService.Create(myCustomer);

            stripeCustomerId = stripeCustomer.Id;

            //get cardId from stripeCustomer
            cardId = stripeCustomer.DefaultSourceId;

            //get card information from cardId
            var myCard = new StripeCardCreateOptions();

            myCard.SourceToken = cardId;

            var        cardService = new StripeCardService();
            StripeCard stripeCard  = cardService.Get(stripeCustomerId, cardId);


            //save the customerID, cardID, CC4, company name, expiry object into the database
            string   customerID = stripeCustomer.Id;
            string   cardID     = stripeCustomer.DefaultSourceId;
            string   cc4        = stripeCard.Last4;
            string   company    = stripeCard.Brand;
            int      month      = Convert.ToInt32(stripeCard.ExpirationMonth);
            int      year       = Convert.ToInt32(stripeCard.ExpirationYear);
            DateTime expiry     = new DateTime(year, month, 1);

            var currentUserID = User.Identity.GetUserId();

            this.Edit((String)currentUserID, customerID, cardID, cc4, company, expiry);
            TempData["notice"] = "Card successfully added!";
            return(RedirectToAction("Index", "Manage"));
        }
Ejemplo n.º 13
0
        public StripeCard AddCustomerPaymentMethod(string sStripeCustomerId, string sStripeToken)
        {
            try
            {
                StripeConfiguration.SetApiKey(ConfigurationManager.AppSettings["stripeApi_LiveKey"]);

                var cardOptions = new StripeCardCreateOptions()
                {
                    SourceToken = sStripeToken
                };

                var        cardService = new StripeCardService();
                StripeCard card        = cardService.Create(sStripeCustomerId, cardOptions);

                return(card);
            }
            catch (Exception ex)
            {
                oLogger.LogData("METHOD: AddCustomerPaymentMethod; ERROR: TRUE; EXCEPTION: " + ex.Message + "; INNER EXCEPTION: " + ex.InnerException + "; STACKTRACE: " + ex.StackTrace);
                throw;
            }
        }
Ejemplo n.º 14
0
        public ActionResult GetSubscriptionPopup(SubscriptionOption model)
        {
            var subscriptionModel = new SubscriptionModel();

            subscriptionModel.subscriptionOption  = model;
            subscriptionModel.CardType            = GetPaymentCardType();
            subscriptionModel.ExpirationYearList  = GetExpirationYear();
            subscriptionModel.ExpirationMonthList = GetExpirationMonth();
            var customerID = SessionController.UserSession.CustomerID;           //Check whether the user already has credit card details or not

            if (customerID != null && customerID != "")
            {
                var            customerService = new StripeCustomerService();
                StripeCustomer stripeCustomer  = customerService.Get(customerID);
                var            cardService     = new StripeCardService();
                StripeCard     stripeCard      = cardService.Get(customerID, stripeCustomer.DefaultSourceId); // optional isRecipient
                foreach (var card in subscriptionModel.CardType)
                {
                    stripeCard.Brand             = subscriptionModel.CardType[0].Name;
                    subscriptionModel.CardTypeID = Convert.ToInt32(subscriptionModel.CardType[0].ID);
                }
                subscriptionModel.ExpirationMonth = stripeCard.ExpirationMonth;
                subscriptionModel.ExpirationYear  = stripeCard.ExpirationYear;
                subscriptionModel.CardTypeID      = subscriptionModel.CardTypeID;
                subscriptionModel.CardNumber      = "************" + stripeCard.Last4;
                subscriptionModel.NameOnCard      = stripeCard.Name;
            }
            //----------------------
            if (model.RoleId == 2)
            {
                ViewBag.SubscriptionTitle = "Find unlimited investment opportunities for " + model.AmountPerMonth + " per month.";
            }
            else if (model.RoleId == 3)
            {
                ViewBag.SubscriptionTitle = "List unlimited investment opportunities for " + model.AmountPerMonth + " per month.";
            }
            return(PartialView("_PaymentSubscriptionPopup", subscriptionModel));
        }
Ejemplo n.º 15
0
        public async Task WhenStripeModeIsTest_ItShouldCreateACustomer()
        {
            this.apiKeyRepository.Setup(v => v.GetApiKey(UserType.TestUser)).Returns(TestKey);

            var expectedCardCreateOptions = new StripeCardCreateOptions {
                Source = new StripeSourceOptions {
                    TokenId = TokenId
                }
            };
            var card = new StripeCard {
                Id = CardId
            };

            this.stripeService.Setup(v => v.CreateCardAsync(
                                         CustomerId,
                                         It.Is <StripeCardCreateOptions>(
                                             x => JsonConvert.SerializeObject(x, Formatting.None) == JsonConvert.SerializeObject(expectedCardCreateOptions, Formatting.None)),
                                         TestKey))
            .ReturnsAsync(card);


            var expectedCustomerUpdateOptions = new StripeCustomerUpdateOptions {
                DefaultSource = CardId
            };

            this.stripeService.Setup(v => v.UpdateCustomerAsync(
                                         CustomerId,
                                         It.Is <StripeCustomerUpdateOptions>(
                                             x => JsonConvert.SerializeObject(x, Formatting.None) == JsonConvert.SerializeObject(expectedCustomerUpdateOptions, Formatting.None)),
                                         TestKey))
            .Returns(Task.FromResult(0))
            .Verifiable();

            await this.target.ExecuteAsync(UserId, CustomerId, TokenId, UserType.TestUser);

            this.stripeService.Verify();
        }
 private string GetStripeChargeString(StripeCard card)
 {
     return(String.Format("source={0}", card.SourceToken));
 }
        public async Task <PaymentOutput> MakePaymentAsync(StripeCreditCardPaymentInput input, CancellationToken cancellationToken = default)
        {
            var output = new PaymentOutput();

            if (!input.IsBankProcess)
            {
                var isoCurrencyCode = input.IsoCurrencyCode;

                var baseStipeRepository = new BaseStipeRepository(this.httpClient);
                var secretKey           = input.ServiceKey;
                StripeConfiguration.SetApiKey(secretKey);

                var custName  = input.FirstName + " " + input.LastName;
                var custEmail = input.EmailAddress;

                var repository     = new CustomerServiceBaseStipeRepository(this.httpClient);
                var stripeCustomer = await repository.GetStripeCustomerAsync(custName, custEmail, secretKey, cancellationToken);

                var myToken = new StripeTokenCreateOptions();
                var expMMYY = input.CcExpMmYy;
                myToken.Card = new StripeCreditCardOptions()
                {
                    Number          = input.CreditCardNo,
                    ExpirationYear  = expMMYY.Substring(expMMYY.Length - 2),
                    ExpirationMonth = expMMYY.Substring(0, expMMYY.Length - 2),
                    Cvc             = input.Cvc
                };
                var tokenService     = new StripeTokenService();
                var stripeTokenFinal = await tokenService.CreateAsync(myToken);

                var stripeCardObj = new StripeCard();
                stripeCardObj.SourceToken = stripeTokenFinal.Id;
                var url        = String.Format("https://api.stripe.com/v1/customers/{0}/sources", stripeCustomer.Id);
                var stripeCard = await baseStipeRepository.CreateAsync(stripeCardObj, url, secretKey, cancellationToken);

                if (String.IsNullOrEmpty(stripeCard.Id))
                {
                    throw new Exception("Unable to add card to customer");
                }

                var cardId = stripeCard.Id;

                var chargeAmount = (input.Amount * 100).ToString().Split('.')[0];
                var stripeObject = new StripeCharge();
                stripeObject.Amount   = Convert.ToInt32(chargeAmount);
                stripeObject.Currency = isoCurrencyCode;
                stripeObject.Customer = stripeCustomer;
                var source = new Source();
                source.Id                = cardId;
                stripeObject.Source      = source;
                stripeObject.Description = Guid.NewGuid().ToString();

                var stripePayment = await baseStipeRepository.CreateAsync(stripeObject, "https://api.stripe.com/v1/charges", secretKey, cancellationToken);

                if (stripePayment != null)
                {
                    if (String.Equals(stripePayment.Status, "succeeded", StringComparison.OrdinalIgnoreCase))
                    {
                        output.IsSuccessful      = true;
                        output.TransactionResult = stripePayment.Status;
                    }
                    else
                    {
                        //fail transaction
                        output.IsSuccessful      = false;
                        output.TransactionResult = stripePayment.Status;
                    }

                    output.TransactionIdentifier = stripePayment.Id;
                    output.InvoiceNumber         = stripePayment.Description;
                    output.AuthToken             = stripePayment.Source.Id;
                    output.StripeCustomerId      = stripePayment.CustomerId;
                    output.CardType = stripeCard.Brand;
                }
            }
            else
            {
                output.IsSuccessful      = false;
                output.TransactionResult = "422";
            }

            return(output);
        }
Ejemplo n.º 18
0
        public ActionResult UserProfile(bool passwordIfCorrect = true)
        {
            var serialization         = new Serialization();
            var userRegistration      = new UserRegistration();
            var HashCriteria          = new Hashtable();
            var actualCriteria        = string.Empty;
            var objUserProfileDetails = new List <UserProfileEditModel>();

            HashCriteria.Add("UserID", userID);
            actualCriteria = serialization.SerializeBinary((object)HashCriteria);
            var result = userRegistration.GetUserSpecificDetails(actualCriteria);

            objUserProfileDetails = (List <UserProfileEditModel>)(serialization.DeSerializeBinary(Convert.ToString(result)));
            var UserProfileDetails = objUserProfileDetails.FirstOrDefault();

            //UserProfileDetails.ProfileImage = CheckFileExists(UserProfileDetails.ProfileImage, "ProfileImagePath", Convert.ToString(UserProfileDetails.ID), "UserProfile");
            UserProfileDetails.ProfileImage      = CheckFileExistsGender(UserProfileDetails.ProfileImage, UserProfileDetails.Gender, "ProfileImagePath", Convert.ToString(UserProfileDetails.ID), "UserProfile");
            UserProfileDetails.SubscriptionModel = new SubscriptionModel();
            var subscriptionController = new SubscriptionController();

            UserProfileDetails.SubscriptionModel.CardType            = subscriptionController.GetPaymentCardType();
            UserProfileDetails.SubscriptionModel.ExpirationYearList  = subscriptionController.GetExpirationYear();
            UserProfileDetails.SubscriptionModel.ExpirationMonthList = subscriptionController.GetExpirationMonth();
            Session["ProfileImage"] = null;
            if (!passwordIfCorrect)
            {
                ViewBag.Error = "Please enter correct password";
            }
            else
            {
                //To get the customer credit card information for this user
                string customerID = UserProfileDetails.CustomerID;
                if (customerID != null && customerID != "")
                {
                    var            customerService = new StripeCustomerService();
                    StripeCustomer stripeCustomer  = customerService.Get(customerID);
                    var            cardService     = new StripeCardService();
                    StripeCard     stripeCard      = cardService.Get(customerID, stripeCustomer.DefaultSourceId); // optional isRecipient
                    foreach (var card in UserProfileDetails.SubscriptionModel.CardType)
                    {
                        //stripeCard.Brand = UserProfileDetails.SubscriptionModel.CardType[0].Name;
                        UserProfileDetails.SubscriptionModel.CardType[0].Name = stripeCard.Brand;
                        UserProfileDetails.SubscriptionModel.CardTypeID       = Convert.ToInt32(UserProfileDetails.SubscriptionModel.CardType[0].ID);
                    }
                    if (stripeCard.AddressCity != null)
                    {
                        UserProfileDetails.SubscriptionModel.BillingAddress = stripeCard.AddressCity;
                    }
                    UserProfileDetails.SubscriptionModel.ExpirationMonth = stripeCard.ExpirationMonth;
                    UserProfileDetails.SubscriptionModel.ExpirationYear  = stripeCard.ExpirationYear;
                    UserProfileDetails.SubscriptionModel.CardTypeID      = UserProfileDetails.SubscriptionModel.CardTypeID;
                    UserProfileDetails.SubscriptionModel.CardNumber      = "********" + stripeCard.Last4;
                    UserProfileDetails.SubscriptionModel.NameOnCard      = stripeCard.Name;
                    UserProfileDetails.SubscriptionModel.BillingAddress  = stripeCard.AddressLine1;
                    UserProfileDetails.SubscriptionModel.City            = stripeCard.AddressCity;
                    if (stripeCard.AddressState != null)
                    {
                        UserProfileDetails.SubscriptionModel.State = stripeCard.AddressState;
                    }
                    if (stripeCard.AddressZip != null)
                    {
                        UserProfileDetails.SubscriptionModel.Zip = stripeCard.AddressZip;
                    }
                }
            }
            return(View(UserProfileDetails));
        }
Ejemplo n.º 19
0
        public async Task <ActionResult> ChargeSaveCustomer(SubscriptionModel model)
        {
            var subscriptionBA     = new Subscription();
            var serialization      = new Serialization();
            var status             = false;
            var HashCriteria       = new Hashtable();
            var actualCriteria     = string.Empty;
            var HashCriteriaPlan   = new Hashtable();
            var actualCriteriaPlan = string.Empty;
            var userID             = Convert.ToString(SessionController.UserSession.UserId);
            var subscriptionModel  = new SubscriptionModel();

            subscriptionModel.CardType            = GetPaymentCardType();
            subscriptionModel.ExpirationYearList  = GetExpirationYear();
            subscriptionModel.ExpirationMonthList = GetExpirationMonth();
            if (model.RoleID == 2)
            {
                ViewBag.SubscriptionTitle = "Find unlimited investment opportunities for $399 per month.";
            }
            else if (model.RoleID == 3)
            {
                ViewBag.SubscriptionTitle = "List unlimited investment opportunities for $399 per month.";
            }

            //Remove fields form model because these are required fieldsand we are not using these fields on paywall
            ModelState.Remove("State");
            ModelState.Remove("BillingAddress");
            ModelState.Remove("Zip");
            ModelState.Remove("City");
            if (!ModelState.IsValid)
            {
                return(PartialView("_PaymentSubscriptionPopup", subscriptionModel));
            }
            //Check if the user is already a custome ron stripe or not?
            var customer_ID = Convert.ToString(SessionController.UserSession.CustomerID);

            if (customer_ID != null && customer_ID != "")
            {
                if (model.Token != null)
                {
                    //For existing customer create new card
                    var cardOptions = new StripeCardCreateOptions()
                    {
                        SourceToken = model.Token
                    };

                    var        cardService = new StripeCardService();
                    StripeCard card        = cardService.Create(customer_ID, cardOptions);
                }
                else
                {
                    return(PartialView("_PaymentSubscriptionPopup", subscriptionModel));
                }
                model.CustomerID = customer_ID;
            }
            else
            {
                // 1. Create customer in stripe
                if (model.Token != null)
                {
                    var customerID = await CreateCustomer(model.Token);

                    model.CustomerID = customerID;
                    SessionController.UserSession.CustomerID = model.CustomerID;
                }
                else
                {
                    return(PartialView("_PaymentSubscriptionPopup", subscriptionModel));
                }
            }
            // 2. Get the plans from the Plans table
            HashCriteriaPlan.Add("ID", model.subscriptionOption.ID.ToString());
            actualCriteriaPlan = serialization.SerializeBinary((object)HashCriteriaPlan);

            var result              = subscriptionBA.GetPlanDetails(actualCriteriaPlan);
            var subscriptionPlans   = (SubscriptionPlans)(serialization.DeSerializeBinary(Convert.ToString(result)));
            var planID              = model.subscriptionOption.ID;
            var subscription_PlanID = subscriptionPlans.SubscriptionPlanID;
            var amount              = subscriptionPlans.Amount;

            // 3. subscription aginst that plan
            var subscriptionService = new StripeSubscriptionService();
            var stripeSubscription  = subscriptionService.Create(model.CustomerID, subscription_PlanID);

            //4. Make the payment
            model.Amount = amount;

            var chargeId = await ProcessPayment(model);

            if (chargeId != null)
            {
                DateTime billingDate = DateTime.Now;
                // 5. Save detals in the subscription table with amount and token of charge
                HashCriteria.Add("Token", model.Token);
                HashCriteria.Add("UserID", userID);
                HashCriteria.Add("Amount", model.Amount);
                HashCriteria.Add("BillingDate", Convert.ToString(billingDate.ToString("dd/MM/yyyy")));
                HashCriteria.Add("CustomerID", model.CustomerID);
                HashCriteria.Add("PlanID", planID);
                HashCriteria.Add("SubscriptionID", stripeSubscription.Id);
                HashCriteria.Add("ChargeID", chargeId);

                actualCriteria = serialization.SerializeBinary((object)HashCriteria);

                var subscriptionstatus = subscriptionBA.SaveSubscriptionData(actualCriteria);
                var subscriptionID     = Convert.ToInt64(serialization.DeSerializeBinary(Convert.ToString(subscriptionstatus)));

                if (subscriptionID > 0)
                {
                    // 6. Update the user role as Investor/Broker
                    status = UpdateUserRole(model.RoleID);
                    //Make the user flag as paid
                    SessionController.UserSession.IsPaid = true;
                    if (model.RoleID == 2)
                    {
                        Synoptek.SessionController.UserSession.RoleType = "Investor";
                    }
                    else if (model.RoleID == 3)
                    {
                        Synoptek.SessionController.UserSession.RoleType = "Broker";
                    }

                    //initialize userAuthModel
                    LoginController loginController = new LoginController();
                    var             loginBA         = new Login();
                    LoginModel      loginModel      = new LoginModel();
                    HashCriteria.Add("UserName", SessionController.UserSession.EmailAddress);
                    actualCriteria = serialization.SerializeBinary((object)HashCriteria);
                    var rec = loginBA.ValidateLogin(actualCriteria);
                    var loginModelDetails = (LoginModel)(serialization.DeSerializeBinary(Convert.ToString(rec)));

                    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie, DefaultAuthenticationTypes.ExternalCookie);

                    var userSession = loginController.Authenticate(loginModelDetails);
                    if (userSession != null)
                    {
                        var identity = new ClaimsIdentity(AuthenticationHelper.CreateClaim(userSession,
                                                                                           userSession.UserRole),
                                                          DefaultAuthenticationTypes.ApplicationCookie
                                                          );
                        AuthenticationManager.SignIn(new AuthenticationProperties()
                        {
                            AllowRefresh = true,
                            IsPersistent = true,
                            ExpiresUtc   = DateTime.UtcNow.AddHours(1)
                        }, identity);
                    }

                    if (model.RoleID == 2)
                    {
                        return(RedirectToAction("Investor", "Dashboard"));
                    }
                    if (model.RoleID == 3)
                    {
                        return(RedirectToAction("Broker", "Dashboard"));
                    }
                }
            }
            return(PartialView("_PaymentSubscriptionPopup", subscriptionModel));
        }
Ejemplo n.º 20
0
 private string GetStripeChargeString(StripeCard card)
 {
     return($"source={card.SourceToken}");
 }
Ejemplo n.º 21
0
 private CustomerRePaymentViewModel CustomerRepaymentModelData(ApplicationUser user, Donation donation, DonationViewModel detail, List <CountryViewModel> countryList, StripeCustomer objStripeCustomer, StripeCard objStripeCard)
 {
     return(new CustomerRePaymentViewModel()
     {
         Name = user.FullName,
         AddressLine1 = user.AddressLine1,
         AddressLine2 = user.AddressLine2,
         City = user.City,
         State = user.State,
         Country = string.IsNullOrEmpty(user.Country) ? _currencySettings.Value.ServerLocation == "China" ? "CN" : "" : user.Country,
         Zip = user.Zip,
         DonationId = donation.Id,
         Description = donation.Reason,
         Frequency = _localizer[detail.GetCycle(donation.CycleId.ToString())],
         Amount = (decimal)donation.DonationAmount,
         IsCustom = donation.IsCustom,
         countries = countryList,
         Last4Digit = objStripeCard.Last4,
         CardId = objStripeCard.Id,
         DisableCurrencySelection = string.IsNullOrEmpty(objStripeCustomer.Currency) ? "0" : "1"
     });
 }
Ejemplo n.º 22
0
        // sk_test_E01Kh96YOzRtkhD5wItn8CDd portal api

        public async Task <Dictionary <bool, string> > ProcessCustomerCard(Models.Card card, int amount, string email)
        {
            Dictionary <bool, string> result;
            var customerId = await CheckCustomerHasStripeAccnt(email);

            if (!string.IsNullOrEmpty(customerId))
            {
                StripeToken stripeToken = new StripeToken();

                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
                StripeConfiguration.SetApiKey(StripeClientConstants.ApiKey);

                var tokenOptions = new StripeTokenCreateOptions()
                {
                    Card = new StripeCreditCardOptions()
                    {
                        Number          = card.Number,
                        ExpirationYear  = card.ExpiryYear,
                        ExpirationMonth = card.ExpiryMonth,
                        Cvc             = card.CVC,
                        Name            = card.Name
                    }
                };
                var tokenService = new StripeTokenService();
                try
                {
                    stripeToken = tokenService.Create(tokenOptions, new StripeRequestOptions()
                    {
                        ApiKey = Stripe.StripeClient.DefaultPublishableKey
                    });
                    var cardOptions = new StripeCardCreateOptions()
                    {
                        SourceToken = stripeToken.Id,
                    };

                    var        cardService = new StripeCardService();
                    StripeCard newCard     = cardService.Create(customerId, cardOptions, new StripeRequestOptions()
                    {
                        ApiKey = _stripeSecretTestkey
                    });
                    return(result = await ChargeCustomerCard(customerId, amount, newCard.Id));
                }
                catch (StripeException e)
                {
                    return(result = new Dictionary <bool, string>()
                    {
                        { false, e.Message }
                    });
                }
            }
            else
            {
                StripeToken stripeToken = new StripeToken();

                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
                StripeConfiguration.SetApiKey(StripeClientConstants.ApiKey);

                var tokenOptions = new StripeTokenCreateOptions()
                {
                    Card = new StripeCreditCardOptions()
                    {
                        Number          = card.Number,
                        ExpirationYear  = card.ExpiryYear,
                        ExpirationMonth = card.ExpiryMonth,
                        Cvc             = card.CVC,
                        Name            = card.Name
                    }
                };
                var tokenService = new StripeTokenService();
                try
                {
                    stripeToken = tokenService.Create(tokenOptions, new StripeRequestOptions()
                    {
                        ApiKey = Stripe.StripeClient.DefaultPublishableKey
                    });
                }
                catch (StripeException e)
                {
                    return(result = new Dictionary <bool, string>()
                    {
                        { false, e.Message }
                    });
                }
                try
                {
                    var customerOptions = new StripeCustomerCreateOptions()
                    {
                        Email       = email,
                        SourceToken = stripeToken.Id,
                    };

                    var            customerService = new StripeCustomerService();
                    StripeCustomer customer        = customerService.Create(customerOptions, new StripeRequestOptions()
                    {
                        ApiKey = _stripeSecretTestkey
                    });
                    return(result = await ChargeCustomerCard(customer.Id, amount, stripeToken.StripeCard.Id));
                }
                catch (StripeException e)
                {
                    return(result = new Dictionary <bool, string>()
                    {
                        { false, e.Message }
                    });
                }
            }
            return(result = new Dictionary <bool, string>());
        }
        private void CancelBookingClick(object sender, CommandEventArgs e)
        {
            var bookingId = int.Parse(e.CommandArgument.ToString());
            var bookings  = _bookingRepository.GetById(bookingId);
            var products  = _bookingRepository.ProductList.First(x => x.ProductId == bookings.ProductId);
            var hotels    = _bookingRepository.HotelList.First(x => x.HotelId == products.HotelId);
            var market    = (from mh in _bookingRepository.MarketHotelList
                             join m in _bookingRepository.MarketList on mh.MarketId equals m.Id
                             where mh.HotelId == hotels.HotelId
                             select m).FirstOrDefault();

            var dateNow  = DateTime.UtcNow.ToLosAngerlesTimeWithTimeZone(hotels.TimeZoneId).AddDays(2).AddHours(9);
            var bookDate = bookings.BookedDate.ToLosAngerlesTimeWithTimeZone(hotels.TimeZoneId).AddDays(14);

            if ((products.IsCheckedInRequired && bookings.CheckinDate <= dateNow) ||
                (!products.IsCheckedInRequired && bookDate.Date < DateTime.UtcNow.ToLosAngerlesTimeWithTimeZone(hotels.TimeZoneId).Date))
            {
                ClientScript.RegisterStartupScript(GetType(), "Cancel_Not_Available", "$(function(){$('#updateNotPossible').modal('show');});", true);
                return;
            }

            if (!string.IsNullOrEmpty(bookings.StripeChargeId))
            {
                MaintainOldInvoices(bookings);
            }

            var    logs      = new CustomerCreditLogs();
            double payByCard = bookings.TotalPrice - bookings.PayByCredit;

            if (bookings.PayByCredit > 0)
            {
                logs = new CustomerCreditLogs
                {
                    CustomerId  = bookings.CustomerId,
                    ProductId   = bookings.ProductId,
                    Description = string.Format("{0} – {1} – {2} – {3}",
                                                products.ProductName,
                                                hotels.HotelName,
                                                market != null ? market.LocationName : "",
                                                bookings.BookingIdString),
                    Amount      = Math.Abs(bookings.PayByCredit),
                    CreatedBy   = PublicCustomerInfos != null ? PublicCustomerInfos.CustomerId : 0,
                    CreatedDate = DateTime.UtcNow,
                    CreditType  = payByCard >= 0 ? (byte)Enums.CreditType.FullPurchaseRefund : (byte)Enums.CreditType.PartialPuchaseRefund,
                    ReferralId  = 0,
                    BookingId   = bookings.BookingId,
                    Status      = true,
                    GiftCardId  = 0
                };
                bookings.PaymentType        = (byte)Enums.PaymentType.DayAxeCredit;
                bookings.RefundCreditAmount = bookings.PayByCredit;
            }

            if (payByCard > 0)
            {
                Refund(bookings, PublicCustomerInfos, payByCard, bookings.MerchantPrice, bookings.HotelPrice);

                bookings.PaymentType = (byte)Enums.PaymentType.Stripe;
                var        cardService = new StripeCardService();
                StripeCard stripeCard  = cardService.Get(PublicCustomerInfos.StripeCustomerId, PublicCustomerInfos.StripeCardId);
                StripeCardString            = string.Format("{0} {1}", stripeCard.Brand, stripeCard.Last4);
                bookings.StripeRefundAmount = payByCard;
            }

            bookings.TotalRefundAmount = bookings.TotalPrice;
            bookings.StripeCardString  = StripeCardString;
            bookings.CancelDated       = DateTime.UtcNow;
            bookings.PassStatus        = (int)Enums.BookingStatus.Refunded;
            _bookingRepository.RefundBooking(bookings, logs);
            CacheLayer.Clear(CacheKeys.CustomerCreditsCacheKey);
            CacheLayer.Clear(CacheKeys.CustomerCreditLogsCacheKey);

            BindMyDayPassInfo();
        }
Ejemplo n.º 24
0
        public ActionResult UpdateUserDetails(UserProfileEditModel userProfileModel)
        {
            if (ModelState.ContainsKey("SubscriptionModel.CardNumber"))
            {
                ModelState["SubscriptionModel.CardNumber"].Errors.Clear();
            }

            var serialization          = new Serialization();
            var userRegistration       = new UserRegistration();
            var objUserProfileDetails  = new List <UserProfileEditModel>();
            var userProfileEditModel   = new UserProfileEditModel();
            var subscriptionController = new SubscriptionController();
            var subscriptionModel      = userProfileModel.SubscriptionModel; //new SubscriptionModel();
            var HashCriteria           = new Hashtable();
            var HashCriteriaPassword   = new Hashtable();
            var actualCriteria         = string.Empty;
            var actualCriteriaPassword = string.Empty;
            var passwordIfCorrect      = false;

            HashCriteria.Add("ID", userProfileModel.ID);
            HashCriteria.Add("Name", userProfileModel.Name);
            HashCriteria.Add("Address", userProfileModel.Address);
            HashCriteria.Add("City", userProfileModel.City);
            HashCriteria.Add("StateName", userProfileModel.StateName);
            HashCriteria.Add("ZipCode", userProfileModel.ZipCode);
            HashCriteria.Add("CompanyName", userProfileModel.CompanyName);
            HashCriteria.Add("LicenceNumber", userProfileModel.LicenceNumber);
            HashCriteria.Add("PhoneNumber", userProfileModel.PhoneNumber);
            HashCriteria.Add("UserID", userID);
            userProfileEditModel.ProfileImage = userProfileModel.ProfileImage;
            userProfileEditModel.PhoneNumber  = userProfileModel.PhoneNumber;
            userProfileEditModel.Email        = userProfileModel.Email;
            userProfileEditModel.CompanyName  = userProfileModel.CompanyName;

            if (subscriptionModel != null)
            {
                subscriptionModel.ExpirationYearList  = new List <ExpirationYear>();
                subscriptionModel.CardType            = new List <PaymentCardTypes>();
                subscriptionModel.ExpirationMonthList = new List <ExpirationMonth>();
                subscriptionModel.ExpirationYearList  = subscriptionController.GetExpirationYear();
                subscriptionModel.CardType            = subscriptionController.GetPaymentCardType();
                subscriptionModel.ExpirationMonthList = subscriptionController.GetExpirationMonth();
            }

            userProfileEditModel.SubscriptionModel = subscriptionModel;
            ModelState.Remove("SecurityCode");

            if (string.IsNullOrWhiteSpace(userProfileModel.CurrentPassword) && !string.IsNullOrWhiteSpace(userProfileModel.Password) && !string.IsNullOrWhiteSpace(userProfileModel.ConfirmPassword))
            {
                ModelState.AddModelError("CurrentPassword", "Please Enter valid current password");
                return(View("UserProfile", userProfileModel));
            }

            if (ModelState.IsValid)
            {
                if (SessionController.UserSession.RoleType == "Admin")
                {
                    actualCriteria = serialization.SerializeBinary((object)HashCriteria);
                    var  result        = userRegistration.UpdateUserProfile(actualCriteria);
                    long updatedUserID = Convert.ToInt64(serialization.DeSerializeBinary(Convert.ToString(result)));
                    SaveProfileImage(userProfileModel.ID);
                    TempData["UserSuccess"] = "User details has been modified successfully..!";
                    return(View("UserProfile", userProfileModel));
                }
                //Check if entered password is exists or not
                HashCriteriaPassword.Add("UserID", userProfileModel.ID);
                actualCriteriaPassword = serialization.SerializeBinary((object)HashCriteriaPassword);
                var userResult = userRegistration.GetUserSpecificDetails(actualCriteriaPassword);
                objUserProfileDetails = (List <UserProfileEditModel>)(serialization.DeSerializeBinary(Convert.ToString(userResult)));
                var  UserProfileDetails = objUserProfileDetails.FirstOrDefault();
                bool isValidPassword    = false;
                if (!string.IsNullOrWhiteSpace(userProfileModel.CurrentPassword))
                {
                    isValidPassword = CipherTool.Verify(userProfileModel.CurrentPassword, Convert.ToString(UserProfileDetails.Password));
                }

                passwordIfCorrect = true;
                if (passwordIfCorrect)
                {
                    if (isValidPassword)
                    {
                        string newPassword = CipherTool.Encrypt(Convert.ToString(userProfileModel.Password));
                        HashCriteria.Add("Password", newPassword);
                    }

                    if (!string.IsNullOrWhiteSpace(userProfileModel.CurrentPassword) && !isValidPassword)
                    {
                        ModelState.AddModelError("CurrentPassword", "Current password is not correct, Please Enter valid current password");
                        return(View("UserProfile", userProfileModel));
                    }

                    actualCriteria = serialization.SerializeBinary((object)HashCriteria);
                    var result = userRegistration.UpdateUserProfile(actualCriteria);
                    SaveProfileImage(Convert.ToInt64(userProfileModel.ID));   // user id
                    int year = 0;
                    if (userProfileModel.SubscriptionModel != null)
                    {
                        if (userProfileModel.SubscriptionModel.ExpirationYear != 0)
                        {
                            var selectedItem = subscriptionModel.ExpirationYearList.Find(p => p.ID == userProfileModel.SubscriptionModel.ExpirationYear);
                            year = Convert.ToInt32(selectedItem.Year);
                        }
                    }

                    //Update the user Credit card details
                    string customerID = Convert.ToString(SessionController.UserSession.CustomerID);
                    if (customerID != null && customerID != "" && (SessionController.UserSession.IsPaid = true))
                    {
                        try
                        {
                            var            customerService = new StripeCustomerService();
                            StripeCustomer stripeCustomer  = customerService.Get(customerID);
                            var            myCard          = new StripeCardUpdateOptions();
                            if (userProfileModel.SubscriptionModel.NameOnCard != null)
                            {
                                myCard.Name = userProfileModel.SubscriptionModel.NameOnCard;
                            }
                            myCard.ExpirationYear  = year;
                            myCard.ExpirationMonth = userProfileModel.SubscriptionModel.ExpirationMonth;
                            myCard.AddressState    = userProfileModel.SubscriptionModel.State;
                            myCard.AddressCity     = userProfileModel.SubscriptionModel.City;
                            myCard.AddressZip      = userProfileModel.SubscriptionModel.Zip;
                            myCard.AddressLine1    = userProfileModel.SubscriptionModel.BillingAddress;
                            var        cardService = new StripeCardService();
                            StripeCard stripeCard  = cardService.Update(customerID, stripeCustomer.DefaultSourceId, myCard); // optional isRecipient
                        }
                        catch (Exception ex)
                        {
                            ModelState.AddModelError("", ex.Message);
                            return(View("UserProfile", userProfileModel));
                        }
                    }
                    TempData["UserSuccess"] = "User details has been modified successfully..!";
                    return(RedirectToAction("UserProfile", new
                    {
                        passwordIfCorrect = passwordIfCorrect
                    }));
                }
                else
                {
                    passwordIfCorrect = false;
                }
            }

            return(View("UserProfile", userProfileModel));
        }
        protected void CheckInDateLink_OnClick(object sender, EventArgs e)
        {
            int  ticketAvailable;
            bool availableProduct = PublicBooking.CheckinDate == null ||
                                    DateTime.UtcNow.ToLosAngerlesTimeWithTimeZone(PublicHotel.TimeZoneId).AddDays(2).Date <= PublicBooking.CheckinDate.Value;
            var param = new CheckAvailableProductParams
            {
                ProductId   = PublicProduct.ProductId,
                CheckInDate = _selectedCheckInDate,
                TotalTicket = PublicBooking.Quantity,
                BookingId   = PublicBooking.BookingId,
                IsAdmin     = false,
                TimezoneId  = PublicHotel.TimeZoneId
            };

            availableProduct &= _productRepository.CheckAvailableProduct(param, out ticketAvailable);

            if (!availableProduct)
            {
                Session.Remove("CheckInDate" + PublicBooking.BookingId);
                CheckInDateLink.Text     = "SELECT<br/>CHECK-IN DATE";
                CheckInDateLink.CssClass = "select-checkin-date";
                ScriptManager.RegisterStartupScript(CheckInDateChangePanel, CheckInDateChangePanel.GetType(), "Update_Not_Available", "$(function(){$('#updateFail').modal('show');});", true);
                return;
            }

            var  logs     = new CustomerCreditLogs();
            bool isRefund = false;

            try
            {
                if (!PublicBooking.HasInvoice)
                {
                    MaintainOldInvoices();
                }

                var newPrice = _productRepository.GetById(PublicProduct.ProductId, _selectedCheckInDate).ActualPriceWithDate;

                double actualPrice = GetActualPrice(newPrice);

                double diffPrice = actualPrice * PublicBooking.Quantity - PublicBooking.TotalPrice;

                // Charge
                if (diffPrice > 0)
                {
                    Charges(diffPrice, newPrice, actualPrice);

                    PublicBooking.TotalPrice   += diffPrice;
                    PublicBooking.HotelPrice    = actualPrice;
                    PublicBooking.MerchantPrice = newPrice.Price;
                }
                else if (diffPrice < 0) //Refund
                {
                    double payByCard = Math.Abs(diffPrice) - PublicBooking.PayByCredit;
                    if (PublicBooking.PayByCredit > 0)
                    {
                        var market = (from mh in _productRepository.MarketHotelList
                                      join m in _productRepository.MarketList on mh.MarketId equals m.Id
                                      where mh.HotelId == PublicHotel.HotelId
                                      select m).FirstOrDefault();
                        logs = new CustomerCreditLogs
                        {
                            CustomerId = PublicCustomerInfos != null
                                ? PublicCustomerInfos.CustomerId
                                : PublicBooking.CustomerId,
                            ProductId   = PublicBooking.ProductId,
                            Description = string.Format("{0} – {1} – {2} – {3}",
                                                        PublicProduct.ProductName,
                                                        PublicHotel.HotelName,
                                                        market != null ? market.LocationName : "",
                                                        PublicBooking.BookingIdString),
                            CreatedBy   = PublicCustomerInfos != null ? PublicCustomerInfos.CustomerId : 0,
                            CreatedDate = DateTime.UtcNow,
                            CreditType  = payByCard >= 0
                                ? (byte)Enums.CreditType.FullPurchaseRefund
                                : (byte)Enums.CreditType.PartialPuchaseRefund,
                            ReferralId = 0,
                            BookingId  = PublicBooking.BookingId,
                            Status     = true,
                            GiftCardId = 0
                        };
                        PublicBooking.PaymentType = (byte)Enums.PaymentType.DayAxeCredit;

                        // Refund All of Credit Used
                        if (payByCard >= 0)
                        {
                            PublicBooking.PayByCredit = 0;
                        }
                        else
                        {
                            PublicBooking.PayByCredit -= Math.Abs(diffPrice);
                        }
                    }

                    // Refund More with Stripe
                    if (payByCard > 0)
                    {
                        Refund(payByCard, new KeyValuePair <double, double>(PublicBooking.MerchantPrice, 0),
                               PublicBooking.HotelPrice);

                        PublicBooking.PaymentType = (byte)Enums.PaymentType.Stripe;

                        var        cardService = new StripeCardService();
                        StripeCard stripeCard  = cardService.Get(PublicCustomerInfos.StripeCustomerId,
                                                                 PublicCustomerInfos.StripeCardId);
                        StripeCardString = string.Format("{0} {1}", stripeCard.Brand, stripeCard.Last4);
                    }

                    PublicBooking.TotalPrice   += diffPrice;
                    PublicBooking.HotelPrice    = actualPrice;
                    PublicBooking.MerchantPrice = newPrice.Price;
                    isRefund = true;

                    PublicBooking.StripeCardString = StripeCardString;
                    _bookingRepository.RefundBooking(PublicBooking, logs);
                }
                else
                {
                    PublicBooking.TotalPrice   += diffPrice;
                    PublicBooking.HotelPrice    = actualPrice;
                    PublicBooking.MerchantPrice = newPrice.Price;
                }
            }
            catch (Exception ex)
            {
                UpdateNotPossibleLit.Text = ex.Message;
                ScriptManager.RegisterStartupScript(CheckInDateChangePanel, CheckInDateChangePanel.GetType(), "UpdateFail", "$(function(){$('#updateFail').modal('show');});", true);
                return;
            }

            PublicBooking.CheckinDate = _selectedCheckInDate.AddHours(Math.Abs(PublicHotel.TimeZoneOffset));
            PublicBooking.ExpiredDate = _selectedCheckInDate.AddDays(1).AddHours(Math.Abs(PublicHotel.TimeZoneOffset));
            if (isRefund)
            {
                _bookingRepository.Update(PublicBooking);
            }
            else
            {
                _bookingRepository.Update(PublicBooking, 0, logs);
            }

            Session.Remove("CheckInDate" + PublicBooking.BookingId);
            BindExpiredDate();
            CacheLayer.ClearAll();
            updateSuccess.Visible    = true;
            CheckInDateLink.Text     = "SELECT<br/>CHECK-IN DATE";
            CheckInDateLink.CssClass = "select-checkin-date";
            ScriptManager.RegisterStartupScript(CheckInDateChangePanel, CheckInDateChangePanel.GetType(), "ConfirmUpdate", "$(function(){$('#updateSuccess').modal('show');});", true);
        }