Exemple #1
0
        public bool CreateCardDetails()
        {
            try
            {
                SourceCard card = new SourceCard();
                card.Number          = this.Number;
                card.ExpirationYear  = this.ExpirationYear;
                card.ExpirationMonth = this.ExpirationMonth;
                card.Cvc             = this.Cvv;
                card.Name            = this.Name;
                StripeCardService       cardService = new StripeCardService(Params.stripeApiKey);
                StripeCardCreateOptions cardoption  = new StripeCardCreateOptions();
                cardoption.SourceCard = card;
                var cardinfo = cardService.Create(this.CustomerId, cardoption);
                if (!string.IsNullOrEmpty(cardinfo.Id))
                {
                    this.CardId = cardinfo.Id;
                    return(true);
                }
            }
            catch (Exception ex)
            {
                return(false);
            }

            return(false);
        }
        public async Task <StripeCard> CreateCardAsync(string customerId, StripeCardCreateOptions options, string apiKey)
        {
            var cardService = new StripeCardService(apiKey);
            var card        = cardService.Create(customerId, options);

            return(card);
        }
        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
        }
        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);
        }
Exemple #5
0
        private StripeCard AddCardToStripe(CreditCard card, string stripeCustomerId)
        {
            var options = new StripeCardCreateOptions
            {
                Card = new StripeCreditCardOptions
                {
                    TokenId = card.StripeToken
                }
            };

            return(_cardService.Create(stripeCustomerId, options));
        }
        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));
                }
            }));
        }
Exemple #7
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;
            }
        }
        private StripeCard AddCardToStripe(CreditCard card, string stripeCustomerId)
        {
            var options = new StripeCardCreateOptions
            {
                SourceCard = new SourceCard
                {
                    Number          = card.CardNumber,
                    ExpirationMonth = card.ExpirationMonth,
                    ExpirationYear  = card.ExpirationYear,
                    AddressCountry  = card.AddressCountry,
                    AddressLine1    = card.AddressLine1,
                    AddressLine2    = card.AddressLine2,
                    AddressCity     = card.AddressCity,
                    AddressState    = card.AddressState,
                    AddressZip      = card.AddressZip,
                    Name            = card.Name,
                    Cvc             = card.Cvc,
                }
            };

            return(_cardService.Create(stripeCustomerId, options));
        }
Exemple #9
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>());
        }
Exemple #10
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));
        }
Exemple #11
0
        private String ProcessStripePayment(ValidationCollectedInfo info)
        {
            if (Request["stripetoken"].HasNoText())
            {
                throw new CartException("Stripe Token is required.");
            }

            var            stripeToken           = Request["stripeToken"];
            var            stripeCustomerService = new StripeCustomerService();
            StripeCustomer stripeCustomer        = null;
            String         existingSourceId      = null;

            try
            {
                stripeCustomer = stripeCustomerService.Get(Profile.StripeCustomerId);

                if (stripeCustomer.Deleted == true)
                {
                    stripeCustomer = null;
                }
                else
                {
                    try
                    {
                        var stripeCardService = new StripeCardService();
                        var stripeCard        = stripeCardService.Create(stripeCustomer.Id, new StripeCardCreateOptions
                        {
                            SourceToken = stripeToken
                        });
                        var scOld = stripeCustomer.SourceList.Data.FirstOrDefault(c => String.Compare(c.Fingerprint, stripeCard.Fingerprint, false) == 0);

                        if (scOld != null)
                        {
                            try
                            {
                                stripeCardService.Delete(stripeCustomer.Id, stripeCard.Id);
                            }
                            catch
                            {
                            }

                            existingSourceId = scOld.Id;
                        }
                        else
                        {
                            existingSourceId = stripeCard.Id;
                        }
                    }
                    catch
                    {
                    }
                }
            }
            catch (StripeException)
            {
            }

            if (stripeCustomer == null)
            {
                stripeCustomer = stripeCustomerService.Create(new StripeCustomerCreateOptions
                {
                    Email       = User.Identity.Name,
                    Description = Profile.FirstName + " " + Profile.LastName,
                    SourceToken = stripeToken
                });
                Profile.StripeCustomerId = stripeCustomer.Id;
                Profile.Save();
                existingSourceId = stripeCustomer.DefaultSourceId;
            }

            var stripeChargeService = new StripeChargeService();
            var stripeChargeOptions = new StripeChargeCreateOptions()
            {
                Amount      = (Int32)(info.TotalPrice * 100),
                Currency    = "USD",
                Description = info.Orders.Count == 1 ? String.Format("1 flyer (ID {0})", info.Orders[0].order_id.ToString()) : String.Format("{0} flyers (IDs {1})", info.Orders.Count.ToString(), String.Join(", ", info.OrderIds)),
                Capture     = true,
                CustomerId  = stripeCustomer.Id,
                SourceTokenOrExistingSourceId = existingSourceId
            };
            var stripeCharge = stripeChargeService.Create(stripeChargeOptions);
            var result       = stripeCharge.Id;

            return(result);
        }
Exemple #12
0
        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);
        }
Exemple #13
0
        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);
        }
Exemple #14
0
        public void PassingTest()
        {
            var configuration = new ConfigurationBuilder().AddUserSecrets().Build();

            StripeConfiguration.SetApiKey(configuration["stripe-api-key"]);

            var planService     = new StripePlanService();
            var customerService = new StripeCustomerService();
            var cardService     = new StripeCardService();

            var testPlan = planService.Get("UnitTestPlan") ?? planService.Create(new StripePlanCreateOptions
            {
                Id            = "UnitTestPlan",
                Amount        = 31,
                Currency      = "usd",
                Interval      = "month",
                IntervalCount = 1,
                Name          = "Test plan created from unit test"
            });
            var customer = customerService.Get("cus_8OFUUhfJqfAdm9") ?? customerService.Create(new StripeCustomerCreateOptions
            {
                Email       = "*****@*****.**",
                Description = "test customer description",
                PlanId      = testPlan.Id,
                SourceCard  = new SourceCard()
            });
            var card = cardService.Get(customer.Id, "card_187T8ILiuPyBUDeGL5nbR4PP") ?? cardService.Create(customer.Id, new StripeCardCreateOptions
            {
                SourceCard = new SourceCard
                {
                    Number          = "4242424242424242",
                    ExpirationYear  = "2022",
                    ExpirationMonth = "10",
                    AddressCountry  = "US",
                    AddressLine1    = "24 Beef Flank St",
                    AddressLine2    = "Apt 24",
                    AddressCity     = "Biggie Smalls",
                    AddressState    = "NC",
                    AddressZip      = "27617",
                    Name            = "Joe Meatballs",
                    Cvc             = "1223"
                }
            });

            Assert.NotNull(card);
        }