private StripeToken CreateToken(string number, int expireYear, int expireMonth, string zipCode, string name, string cvc)
        {
            var myToken = new StripeTokenCreateOptions();

            // if you need this...
            myToken.Card = new StripeCreditCardOptions()
            {
                // set these properties if passing full card details (do not
                // set these properties if you set TokenId)
                Number          = number,
                ExpirationYear  = expireYear,
                ExpirationMonth = expireMonth,
                //AddressCountry = "US",                // optional
                //AddressLine1 = "24 Beef Flank St",    // optional
                //AddressLine2 = "Apt 24",              // optional
                //AddressCity = "Biggie Smalls",        // optional
                //AddressState = state,                  // optional
                AddressZip = zipCode,      // optional
                Name       = name,         // optional
                Cvc        = cvc           // optional
            };

            // set this property if using a customer (stripe connect only)
            //if (!string.IsNullOrEmpty(customerId))
            //{
            //    myToken.CustomerId = customerId;
            //}

            var         tokenService = new StripeTokenService();
            StripeToken stripeToken  = tokenService.Create(myToken);

            return(stripeToken);
        }
        public string CreateToken(string cardNumber, int cardExpMonth, int cardExpYear, string cardCVC)
        {
            try
            {
                StripeConfiguration.SetApiKey("sk_test_70zfg67P7qQ12FiVLzET76sH");

                var tokenOptions = new StripeTokenCreateOptions()
                {
                    Card = new StripeCreditCardOptions()
                    {
                        Number          = cardNumber,
                        ExpirationYear  = cardExpYear,
                        ExpirationMonth = cardExpMonth,
                        Cvc             = cardCVC
                    }
                };

                var         tokenService = new StripeTokenService();
                StripeToken stripeToken  = tokenService.Create(tokenOptions);

                return(stripeToken.Id); // This is the token
            }
            catch (Exception ex)
            {
                return("error");
            }
        }
Exemple #3
0
        protected string getStripeToken(string cardNumber, string expirationYear, string expirationMonth, string cvc)
        {
            var myToken = new StripeTokenCreateOptions();

            // if you need this...
            myToken.Card = new StripeCreditCardOptions()
            {
                // set these properties if passing full card details (do not
                // set these properties if you set TokenId)
                Number          = cardNumber,
                ExpirationYear  = expirationYear,
                ExpirationMonth = expirationMonth,
                //AddressCountry = "US",                // optional
                //AddressLine1 = "24 Beef Flank St",    // optional
                //AddressLine2 = "Apt 24",              // optional
                //AddressCity = "Biggie Smalls",        // optional
                //AddressState = "NC",                  // optional
                //AddressZip = "27617",                 // optional
                //Name = "Joe Meatballs",               // optional
                Cvc = cvc
            };

            var         tokenService = new StripeTokenService();
            StripeToken stripeToken  = tokenService.Create(myToken);

            return(stripeToken.Id);
        }
Exemple #4
0
        /// <summary>
        /// Creates a token as per
        /// https://github.com/jaymedavis/stripe.net#creating-a-token
        /// </summary>
        /// <param name="customer"></param>
        /// <returns></returns>
        public static StripeToken CreateTestToken(ICustomerEntity customer = null)
        {
            var myToken = new StripeTokenCreateOptions();

            // if you need this...
            myToken.Card = new StripeCreditCardOptions()
            {
                // set these properties if passing full card details (do not
                // set these properties if you set TokenId)
                Number          = "4242424242424242",
                ExpirationYear  = "2063",
                ExpirationMonth = "10",
                AddressCountry  = "US",               // optional
                AddressLine1    = "24 Beef Flank St", // optional
                AddressLine2    = "Apt 24",           // optional
                AddressCity     = "Biggie Smalls",    // optional
                AddressState    = "NC",               // optional
                AddressZip      = "27617",            // optional
                Name            = "Joe Meatballs",    // optional
                Cvc             = "1223"              // optional
            };

            if (customer != null)
            {
                myToken.CustomerId = customer.PaymentSystemId;
            }

            var         tokenService = new StripeTokenService();
            StripeToken stripeToken  = tokenService.Create(myToken);

            return(stripeToken);
        }
Exemple #5
0
        public void TestCharge()
        {
            StripeToken token    = CreateTestToken();
            string      chargeId = StripeManager.Charge(token.Id, 78.90f, "Test naked charge");

            Assert.IsNotNull(chargeId);
        }
        public async Task test_payments()
        {
            StripeConfiguration.SetApiKey(ConfigurationManager.AppSettings["Stripe.SecretKey"]);

            var stripeTokenreateOptions = new StripeTokenCreateOptions();

            stripeTokenreateOptions.Card = new StripeCreditCardOptions()
            {
                Number          = "4242424242424242",
                ExpirationYear  = "2022",
                ExpirationMonth = "10",
            };

            var         tokenService = new StripeTokenService();
            StripeToken stripeToken  = tokenService.Create(stripeTokenreateOptions);

            StripeCustomerCreateOptions customerCreateOptions = new StripeCustomerCreateOptions
            {
                SourceToken = stripeToken.Id,
                Email       = $"{Guid.NewGuid()}@test.com"
            };

            var customerService = new StripeCustomerService();
            var customer        = customerService.Create(customerCreateOptions);

            var dbConnection  = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
            var stripeService = new StripeService(dbConnection);
            await stripeService.TryCharge(customer.Id, 300, "AUD");
        }
Exemple #7
0
        /// <summary>
        /// Creates the token required by Stripe in order to send credit card information to processed for a transaction
        /// </summary>
        /// <param name="t">The transaction object</param>
        /// <returns>A StripeToken object that can be associated with the charge that is sent to Stripe</returns>
        private StripeToken CreateCardToken(Transaction t)
        {
            var tokenOptions = new StripeTokenCreateOptions()
            {
                Card = new StripeCreditCardOptions()
                {
                    Number          = t.Card.CardNumber,
                    ExpirationYear  = t.Card.ExpirationYear.ToString(),
                    ExpirationMonth = t.Card.ExpirationMonthPadded,
                }
            };

            if (!string.IsNullOrEmpty(t.Card.SecurityCode))
            {
                tokenOptions.Card.Cvc = t.Card.SecurityCode; // optional
            }

            if (t.Customer.Street.Length > 0)
            {
                tokenOptions.Card.AddressLine1 = t.Customer.Street; // optional
            }
            if (t.Customer.PostalCode.Length > 0)
            {
                tokenOptions.Card.AddressZip = t.Customer.PostalCode; // optional
            }
            tokenOptions.Card.Name = t.Card.CardHolderName;

            var         tokenService = new StripeTokenService();
            StripeToken stripeToken  = tokenService.Create(tokenOptions);

            return(stripeToken);
        }
Exemple #8
0
        public bool payByCard(PaymentDetails paymentDetails, string userId)
        {
            var charge = paymentDetails.paymentCardDetails;

            // Treat the info to be ready to put into the charge object for stripe api
            int?amountTreated = Convert.ToInt32(Math.Round(Convert.ToDouble(charge.amount, new CultureInfo("en-US")) * 100), new CultureInfo("en-US"));

            // get Stripe Customer Id
            string stripeCustomerId = getStripeCustomerId(userId);
            var    user             = getUser(userId);

            // insatnce of card service
            var tokenService = new StripeTokenService();
            StripeTokenCreateOptions stripeToken = new StripeTokenCreateOptions()
            {
                Card = new StripeCreditCardOptions()
                {
                    // Capture = true,
                    Cvc = charge.cvc,
                    // Description = "",
                    ExpirationMonth = charge.month,
                    ExpirationYear  = charge.year,
                    Number          = charge.number,
                    Name            = charge.cardHolderName
                }
                //,CustomerId = stripeCustomerId
            };

            StripeToken token = tokenService.Create(stripeToken);

            // Instance of charge service
            var chargeService = new StripeChargeService();


            // Put info in the Charge object
            StripeChargeCreateOptions chargeCasted = new StripeChargeCreateOptions()
            {
                Amount = amountTreated,
                //ApplicationFee = applicationFeeTreated,
                Capture  = true,
                Currency = "EUR",
                //CustomerId = stripeCustomerId,
                Description = "",
                //Destination = "",
                SourceTokenOrExistingSourceId = token.Id,
                ReceiptEmail = user.Email,
            };

            // Send charge to stripe API
            StripeCharge response = chargeService.Create(chargeCasted);

            if (response.Status == "succeeded")
            {
                return(true);
            }

            return(false);
        }
 public async Task ChargeCustomer(Domain.Order order, StripeToken token)
 {
     var options = new StripeChargeCreateOptions {
         Amount      = (int)(order.TotalAmount * 100m),
         Currency    = "nok",
         Description = order.Registration.EventInfo.Title,
         SourceTokenOrExistingSourceId = token.Id,
         ReceiptEmail = order.CustomerEmail
     };
     var          service = new StripeChargeService();
     StripeCharge charge  = await service.CreateAsync(options);
 }
 public creating_a_bank_account_token()
 {
     Token = new StripeTokenService(Cache.ApiKey).CreateAsync(
         new StripeTokenCreateOptions
     {
         BankAccount = new BankAccountOptions
         {
             AccountNumber = "000123456789",
             Country       = "US",
             Currency      = "USD",
             RoutingNumber = "110000000",
         }
     }
         ).Result;
 }
Exemple #11
0
        public void TestChargeWithCustomer()
        {
            // Arrange
            ICustomerEntity customer = CreateMockCustomer();
            IChargeEntity   charge   = CreateMockCharge();

            StripeToken token = CreateTestToken(customer);

            StripeManager.CreateCustomer(customer, token.Id);

            // Act - charge customer
            string chargeId = StripeManager.Charge(customer, charge);

            Assert.IsNotNull(chargeId);

            chargeId = StripeManager.Charge(customer, 12.34f, "Test charge with customer");
            Assert.IsNotNull(chargeId);
        }
        private StripeSource createStripeSource(string cardNo, int?expirationYear, int?expirationMonth, string ccv, string cardHolderFullName, bool isReusable)
        {
            StripeSource source = new StripeSource();

            try
            {
                var tokenOptions = new StripeTokenCreateOptions()
                {
                    Card = new StripeCreditCardOptions()
                    {
                        Number          = cardNo,
                        ExpirationYear  = expirationYear,
                        ExpirationMonth = expirationMonth,
                        Cvc             = ccv
                    }
                };
                var         tokenService = new StripeTokenService(secretKey);
                StripeToken stripeToken  = tokenService.Create(tokenOptions);
                string      usage        = "reusable";
                if (!isReusable)
                {
                    usage = "single_use";
                }
                var sourceOptions = new StripeSourceCreateOptions()
                {
                    Type  = StripeSourceType.Card,
                    Owner = new StripeSourceOwner()
                    {
                        Name = cardHolderFullName
                    },
                    Token = stripeToken.Id,
                    Usage = usage
                };
                var sourceService = new StripeSourceService(secretKey);
                //CREATE A SOURCE
                source = sourceService.Create(sourceOptions);
            }
            catch (StripeException e)
            {
                throw new StripeException(e.HttpStatusCode, e.StripeError, e.Message);
            }
            return(source);
        }
        public string CreateToken(string cardNumber, int cardExpMonth, int cardExpYear, string cardCVC)
        {
            StripeConfiguration.SetApiKey("pltestxxxxxxx");//do not put our secrtet key in the mobile app

            var token = new StripeTokenCreateOptions()
            {
                Card = new StripeCreditCardOptions()
                {
                    Number          = cardNumber,
                    ExpirationYear  = cardExpYear,//might have to convert this to a string later ons
                    ExpirationMonth = cardExpMonth,
                    Cvc             = cardCVC
                }
            };
            var         tokenSerivce = new StripeTokenService();
            StripeToken stripeToken  = tokenSerivce.Create(token);

            return(stripeToken.Id);
        }
Exemple #14
0
        public string CreateToken(string cardNumber, string cardExpMonth, string cardExpYear, string cardCVC)
        {
            StripeConfiguration.SetApiKey("pk_test_xxxxxxxxxxxxxxxxx");

            var tokenOptions = new StripeTokenCreateOptions()
            {
                Card = new StripeCreditCardOptions()
                {
                    Number          = cardNumber,
                    ExpirationYear  = cardExpYear,
                    ExpirationMonth = cardExpMonth,
                    Cvc             = cardCVC
                }
            };

            var         tokenService = new StripeTokenService();
            StripeToken stripeToken  = tokenService.Create(tokenOptions);

            return(stripeToken.Id); // This is the token
        }
Exemple #15
0
        public string CreateToken(CardInfo card)
        {
            StripeConfiguration.SetApiKey("sk_test_fMQSO85L4eNQWH7LEESCbY71");

            var tokenOptions = new StripeTokenCreateOptions()
            {
                Card = new StripeCreditCardOptions()
                {
                    Number          = card.CardNumber,
                    ExpirationYear  = card.CardExpyear,
                    ExpirationMonth = card.CardExpMonth,
                    Cvc             = card.CardCVV
                }
            };

            var         tokenService = new StripeTokenService();
            StripeToken stripeToken  = tokenService.Create(tokenOptions);

            return(stripeToken.Id); // This is the token
        }
Exemple #16
0
        public static string CreateStripeToken(string cardNumber, string cardExpMonth, string cardExpYear, string cardCVC)
        {
            StripeConfiguration.SetApiKey("pk_test_kwCcalSyhmEyq3CmxJqfG6ZJ");

            var tokenOptions = new StripeTokenCreateOptions()
            {
                Card = new StripeCreditCardOptions()
                {
                    Number          = cardNumber,
                    ExpirationYear  = Int32.Parse(cardExpYear),
                    ExpirationMonth = Int32.Parse(cardExpMonth),
                    Cvc             = cardCVC
                }
            };

            var         tokenService = new StripeTokenService();
            StripeToken stripeToken  = tokenService.Create(tokenOptions);

            return(stripeToken.Id);
        }
Exemple #17
0
        public string CreateToken(string cardNumber, string cardExpMonth, string cardExpYear, string cardCVC)
        {
            StripeConfiguration.SetApiKey("your_stripe_live_api_key");

            var tokenOptions = new StripeTokenCreateOptions()
            {
                Card = new StripeCreditCardOptions()
                {
                    Number          = cardNumber,
                    ExpirationMonth = Int32.Parse(cardExpMonth),
                    ExpirationYear  = Int32.Parse(cardExpYear),
                    Cvc             = cardCVC
                }
            };

            var tokenService = new StripeTokenService();

            StripeToken stripeToken = tokenService.Create(tokenOptions);

            return(stripeToken.Id);
        }
Exemple #18
0
 public creating_a_card_token()
 {
     Token = new StripeTokenService(Cache.ApiKey).CreateAsync(
         new StripeTokenCreateOptions
     {
         Card = new StripeCreditCardOptions
         {
             Name            = "Jason Isbell",
             AddressCity     = "Green Hill",
             AddressState    = "AL",
             AddressLine1    = "I could ask?",
             AddressLine2    = "",
             AddressZip      = "35636",
             AddressCountry  = "US",
             Cvc             = "123",
             ExpirationMonth = "10",
             ExpirationYear  = "2025",
             Number          = "4242424242424242"
         }
     }
         ).Result;
 }
Exemple #19
0
        public string MakePayment(PaymentRequest paymentRequest)
        {
            //can't use a customer from the shared opentable account directly, need to create a one off token first
            var tokenOptions = new StripeTokenCreateOptions();

            tokenOptions.CustomerId = paymentRequest.CustomerToken;

            var         tokenService = new StripeTokenService(paymentRequest.MerchantToken);
            StripeToken stripeToken  = tokenService.Create(tokenOptions);

            //use the token to create the charge
            var chargeOptions = new StripeChargeCreateOptions();

            chargeOptions.Amount   = (int)(paymentRequest.Amount * 100);
            chargeOptions.Currency = "GBP";
            chargeOptions.TokenId  = stripeToken.Id;


            //optional properties
            chargeOptions.Description = "tasty meal";
            var metaData = new Dictionary <string, string>();

            metaData.Add("opentableBookingId", "998998924");
            chargeOptions.Metadata = metaData;

            var chargeService = new StripeChargeService(paymentRequest.MerchantToken);

            try
            {
                StripeCharge stripeCharge = chargeService.Create(chargeOptions);
                return(stripeCharge.Id);
            }
            catch (StripeException sx)
            {
                //do some logging
            }

            return("");
        }
 public creating_a_card_token()
 {
     Token = new StripeTokenService(_stripe_api_key).CreateAsync(
         new StripeTokenCreateOptions
         {
             Card = new StripeCreditCardOptions
             {
                 Name = "Jason Isbell",
                 AddressCity = "Green Hill",
                 AddressState = "AL",
                 AddressLine1 = "I could ask?",
                 AddressLine2 = "",
                 AddressZip = "35636",
                 AddressCountry = "US",
                 Cvc = "123",
                 ExpirationMonth = "10",
                 ExpirationYear = "2025",
                 Number = "4242424242424242"
             }
         }
     ).Result;
 }
Exemple #21
0
        private void CreateToken()
        {
            var myToken = new StripeTokenCreateOptions();

            // set these properties if using a card
            myToken.CardAddressCountry  = "US";
            myToken.CardAddressLine1    = "24 Portal St";
            myToken.CardAddressLine2    = "Unit B";
            myToken.CardAddressCity     = "Biggie Smalls";
            myToken.CardAddressState    = "NC";
            myToken.CardAddressZip      = "27617";
            myToken.CardCvc             = "1223";
            myToken.CardExpirationMonth = "10";
            myToken.CardExpirationYear  = "2030";
            myToken.CardName            = "Test Name";
            myToken.CardNumber          = "4242424242424242";

            var         tokenService = new StripeTokenService(LibLogic.Helpers.SiteInfo.StripeAPISecretKey);
            StripeToken stripeToken  = tokenService.Create(myToken);

            this.token = stripeToken.Id;
            System.Console.WriteLine("Token is: " + token);
        }
Exemple #22
0
        public void TestCreateForCreateDonorAccount()
        {
            var check = new CheckScannerCheck
            {
                Id            = 11111,
                DonorId       = 222,
                AccountNumber = "P/H+3ccB0ZssORkd+YyJzA==",
                Address       = new crds_angular.Models.Crossroads.Stewardship.Address
                {
                    Line1      = "1 line 1",
                    Line2      = "1 line 2",
                    City       = "1 city",
                    State      = "1 state",
                    PostalCode = "1 postal"
                },
                Amount        = 1111,
                CheckDate     = DateTime.Now.AddHours(1),
                CheckNumber   = "11111",
                Name1         = "1 name 1",
                Name2         = "1 name 2",
                RoutingNumber = "TUbiKZ/Vw1l6uyGCYIIUMg==",
                ScanDate      = DateTime.Now.AddHours(2)
            };

            var contactDonorByDonorId = new MpContactDonor
            {
                ProcessorId = "333000333",
                DonorId     = 333333,
                ContactId   = 3333
            };

            var contactDonorNew = new MpContactDonor
            {
                ProcessorId    = "222000222",
                DonorId        = 222222,
                RegisteredUser = false,
                Account        = new MpDonorAccount
                {
                    ProcessorAccountId = "py_dgsttety6737hjjhweiu3"
                }
            };
            var token = new StripeToken
            {
                Id = "12t4token"
            };
            const string encryptedKey = "PH/rty1234";
            const string decrypAcct   = "6015268542";
            const string decryptRout  = "042000314";

            _donorService.Setup(mocked => mocked.GetContactDonorForDonorId(check.DonorId.Value)).Returns(contactDonorByDonorId);
            _donorService.Setup(mocked => mocked.GetContactDonorForDonorAccount(check.AccountNumber, check.RoutingNumber)).Returns((MpContactDonor)null);
            _mpDonorService.Setup(mocked => mocked.DecryptCheckValue(check.AccountNumber)).Returns(decrypAcct);
            _mpDonorService.Setup(mocked => mocked.DecryptCheckValue(check.RoutingNumber)).Returns(decryptRout);
            _paymentService.Setup(mocked => mocked.CreateToken(decrypAcct, decryptRout, check.Name1)).Returns(token);

            _donorService.Setup(
                mocked =>
                mocked.CreateOrUpdateContactDonor(
                    It.Is <MpContactDonor>(
                        o =>
                        o.Details.DisplayName.Equals(check.Name1) && o.Details.Address.Line1.Equals(check.Address.Line1) && o.Details.Address.Line2.Equals(check.Address.Line2) &&
                        o.Details.Address.City.Equals(check.Address.City) && o.Details.Address.State.Equals(check.Address.State) && o.Details.Address.PostalCode.Equals(check.Address.PostalCode) &&
                        o.Account == null),
                    string.Empty,
                    string.Empty,
                    string.Empty,
                    string.Empty,
                    null,
                    It.IsAny <DateTime>()))
            .Returns(contactDonorNew);

            _mpDonorService.Setup(mocked => mocked.CreateHashedAccountAndRoutingNumber(decrypAcct, decryptRout)).Returns(encryptedKey);
            _mpDonorService.Setup(mocked => mocked.UpdateDonorAccount(encryptedKey, contactDonorNew.Account.ProcessorAccountId, contactDonorNew.ProcessorId));

            var result = _fixture.CreateDonor(check);

            _donorService.VerifyAll();
            Assert.NotNull(result);
            Assert.AreEqual(contactDonorNew, result);
            Assert.AreEqual(decryptRout, result.Account.RoutingNumber);
            Assert.AreEqual(decrypAcct, result.Account.AccountNumber);
            Assert.AreEqual(AccountType.Checking, result.Account.Type);
        }
Exemple #23
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>());
        }
        public int CreateSubscription(string userMail, string planName)
        {
            StripeConfiguration.SetApiKey("sk_test_YskwifolV97dD2Iu0v8YgDt5");
            var customers = new StripeCustomerService();
            var charges   = new StripeChargeService();


            var tokenOptions = new StripeTokenCreateOptions()
            {
                Card = new StripeCreditCardOptions()
                {
                    Number          = "4242424242424242",
                    ExpirationYear  = 2050,
                    ExpirationMonth = 9,
                    Cvc             = "123"
                }
            };

            var         tokenService = new StripeTokenService();
            StripeToken stripeToken  = tokenService.Create(tokenOptions);


            var customerService = new StripeCustomerService();
            StripeList <StripeCustomer> customerItems = customerService.List(
                new StripeCustomerListOptions()
            {
                Limit = 300
            }
                );
            bool found = false;

            var customer = new StripeCustomer();

            foreach (StripeCustomer cus in customerItems)
            {
                if (cus.Email == userMail)
                {
                    found    = true;
                    customer = cus;
                    break;
                }
            }



            if (!found)
            {
                customer = customers.Create(new StripeCustomerCreateOptions
                {
                    Email       = userMail,
                    SourceToken = stripeToken.Id
                });
            }



            var items = new List <StripeSubscriptionItemOption> {
                new StripeSubscriptionItemOption {
                    PlanId = planName
                }
            };
            var subscriptionOptions = new StripeSubscriptionCreateOptions
            {
                Items      = items,
                CustomerId = customer.Id
            };

            var subscriptionService = new StripeSubscriptionService();

            StripeSubscription subscription = subscriptionService.Create(subscriptionOptions);

            return(0);
        }
        public void Test1()
        {
            StripeConfiguration.SetApiKey("sk_test_YskwifolV97dD2Iu0v8YgDt5");
            //var req = this.HttpContext.Request.Form;
            var customers = new StripeCustomerService();
            var charges   = new StripeChargeService();

            try
            {
                var tokenOptions = new StripeTokenCreateOptions()
                {
                    Card = new StripeCreditCardOptions()
                    {
                        Number          = "4242424242424242",
                        ExpirationYear  = 2019,
                        ExpirationMonth = 9,
                        Cvc             = "123"
                    }
                };

                var         tokenService = new StripeTokenService();
                StripeToken stripeToken  = tokenService.Create(tokenOptions);



                var customerService = new StripeCustomerService();
                StripeList <StripeCustomer> customerItems = customerService.List(
                    new StripeCustomerListOptions()
                {
                    Limit = 300
                }
                    );
                bool found = false;

                var customer = new StripeCustomer();

                foreach (StripeCustomer cus in customerItems)
                {
                    if (cus.Email == "*****@*****.**")
                    {
                        found    = true;
                        customer = cus;
                        break;
                    }
                }



                if (!found)
                {
                    customer = customers.Create(new StripeCustomerCreateOptions
                    {
                        Email       = "*****@*****.**",
                        SourceToken = stripeToken.Id
                    });
                }

                var charge = charges.Create(new StripeChargeCreateOptions
                {
                    Amount      = 500,//charge in cents
                    Description = "Sample Charge",
                    Currency    = "usd",
                    CustomerId  = customer.Id
                });



                //  --------------------------------------------------------------------



                StripeSubscriptionService subscriptionSvc = new StripeSubscriptionService();
                //subscriptionSvc.Create(customer.Id, "EBSystems");

                var subscriptionOptions = new StripeSubscriptionUpdateOptions()
                {
                    PlanId   = "testPlan",
                    Prorate  = false,
                    TrialEnd = DateTime.Now.AddMinutes(2)
                };

                var subscriptionService         = new StripeSubscriptionService();
                StripeSubscription subscription = subscriptionService.Update("sub_DfH8fv8g0MNQau", subscriptionOptions);


                //  --------------------------------------------------------------------
            }
            catch (Exception e)
            {
                string error = e.Message;
                //throw new Exception(error);
            }
        }
        private int PurchaseGiftCard(out bool success)
        {
            // Check customer change their email
            success = true;
            bool isPayByCredit;

            if (PublicCustomerInfos == null)
            {
                PublicCustomerInfos = new CustomerInfos
                {
                    EmailAddress = email.Text.Replace(" ", ""),
                    FirstName    = FirstName.Text.Trim(),
                    LastName     = LastName.Text.Trim(),
                    ZipCode      = txtzipcode.Text.Trim()
                };

                // Create new account with email
                var response = _customerInfoRepository.GetVipAccess(email.Text.Replace(" ", ""), Constant.SearchPageDefault, FirstName.Text.Trim(), LastName.Text.Trim());
                PublicCustomerInfos.CustomerId       = response.CustomerId;
                PublicCustomerInfos.StripeCustomerId = response.StripeCustomerId;

                CacheLayer.Clear(CacheKeys.CustomerInfosCacheKey);
                CacheLayer.Clear(CacheKeys.CustomerCreditsCacheKey);

                Session["ReferralCode"] = response.ReferralCode;

                string searchPage = !string.IsNullOrEmpty((string)Session["SearchPage"])
                    ? Session["SearchPage"].ToString()
                    : Constant.SearchPageDefault;

                // Send email new account
                var responseEmail = EmailHelper.EmailNewAccount(PublicCustomerInfos.EmailAddress,
                                                                PublicCustomerInfos.FirstName,
                                                                response.Password,
                                                                Helper.ResolveRelativeToAbsoluteUrl(Request.Url,
                                                                                                    string.Format("{0}?sp={1}",
                                                                                                                  searchPage,
                                                                                                                  response.PasswordKey)), // Reset Password Url
                                                                Helper.ResolveRelativeToAbsoluteUrl(Request.Url,
                                                                                                    string.Format("{0}?c={1}",
                                                                                                                  searchPage,
                                                                                                                  response.AccessKey))); // Browse Day Pass
                PublicCustomerCredits = _customerInfoRepository.GetCustomerCredits(response.CustomerId);


                Session["UserSession"]  = response.AccessKey;
                Session["IsRegister"]   = true;
                Session["ReferralCode"] = response.ReferralCode;
            }

            Regex regex = new Regex(@"([\d]+)(\s)?/(\s)?([\d]+)");
            int   month;

            int.TryParse(regex.Match(txtexpdat.Value).Groups[1].Value, out month);
            int year;

            int.TryParse("20" + regex.Match(txtexpdat.Value).Groups[4].Value, out year);
            string fullName = string.Format("{0} {1}", FirstName.Text, LastName.Text);

            // Check customer has exists with email
            StripeCustomer stripeCustomer = null;
            //var discounts = new Discounts();
            double actualPrice;

            // update user info with exists
            if (!string.IsNullOrEmpty(PublicCustomerInfos.StripeCustomerId))
            {
                stripeCustomer = GetCustomerById(PublicCustomerInfos.StripeCustomerId);
            }

            // Use New Card
            if (MVCardInfo.ActiveViewIndex == 0)
            {
                StripeToken stripeToken = CreateToken(cctextbox.Text.Replace(" ", ""), year, month, txtzipcode.Text,
                                                      fullName,
                                                      txtseccode.Value);

                // update new card for customer
                PublicCustomerInfos.StripeTokenId    = stripeToken.Id;
                PublicCustomerInfos.StripeCardId     = stripeToken.StripeCard.Id;
                PublicCustomerInfos.BankAccountLast4 = stripeToken.StripeCard.Last4;
                PublicCustomerInfos.CardType         = Helper.GetCreditCardType(cctextbox.Text.Replace(" ", ""));
                PublicCustomerInfos.ZipCode          = txtzipcode.Text;

                if (stripeCustomer == null)
                {
                    stripeCustomer = CreateCustomer(PublicCustomerInfos.EmailAddress, fullName, stripeToken.Id);
                    PublicCustomerInfos.StripeCustomerId = stripeCustomer.Id;
                }
                else
                {
                    // Update Stripe exists customer with New Card
                    var card = CreateCard(stripeToken.Id, PublicCustomerInfos.StripeCustomerId);
                    UpdateCustomer(PublicCustomerInfos.EmailAddress, fullName,
                                   PublicCustomerInfos.StripeCustomerId, card.Id);
                }
                _customerInfoRepository.Update(PublicCustomerInfos);

                isPayByCredit = IsPayByCreditCheckBox.Checked;
            }
            else
            {
                isPayByCredit = DCreditCheckBox.Checked;
            }

            if (PublicCustomerInfos.FirstName != FirstName.Text.Trim() || PublicCustomerInfos.LastName != LastName.Text.Trim())
            {
                PublicCustomerInfos.FirstName = FirstName.Text.Trim();
                PublicCustomerInfos.LastName  = LastName.Text.Trim();
                _customerInfoRepository.Update(PublicCustomerInfos);

                // Update Stripe exists customer
                stripeCustomer = UpdateCustomer(PublicCustomerInfos.EmailAddress, fullName, PublicCustomerInfos.StripeCustomerId, string.Empty);
            }

            // Discount 100% ??
            // Price equal 0, so we should not charge with this

            double.TryParse(ValueText.Text, out actualPrice);

            double   chargePrice          = actualPrice;
            string   creditLogDescription = string.Format("eGift Cards – {0}", Helper.FormatPrice(actualPrice * -1));
            DateTime deliveryDate;
            string   stripeChargeId = string.Empty;

            // Use DayAxe Credit
            if (isPayByCredit && PublicCustomerCredits != null && PublicCustomerCredits.Amount > 0)
            {
                // Create Coupon Id because we used DayAxe Credit
                chargePrice = actualPrice - PublicCustomerCredits.Amount;
                if (chargePrice <= 0)
                {
                    chargePrice = 0;
                }
            }

            if (chargePrice > 0)
            {
                StripeCharge stripeCharge = CreateCharges(chargePrice, stripeCustomer.Id, creditLogDescription);
                stripeChargeId = stripeCharge.Id;
            }

            DateTime.TryParseExact(DeliveryDateText.Text, "MM/dd/yyyy", null, DateTimeStyles.None, out deliveryDate);

            double userBookedDate;

            double.TryParse(HidUserBookedDate.Value, out userBookedDate);

            var param = new GiftCardBookings
            {
                CustomerId      = PublicCustomerInfos.CustomerId,
                GiftCardId      = 0,
                Price           = chargePrice,
                PayByCredit     = actualPrice - chargePrice,
                TotalPrice      = actualPrice,
                StripeChargeId  = stripeChargeId,
                BookedDate      = DateTime.UtcNow,
                RecipientEmail  = ToText.Text.Trim(),
                RecipientName   = NameText.Text.Trim(),
                Message         = !string.IsNullOrEmpty(MessageText.Text) ? MessageText.Text : "Enjoy the gift of DayAxe from me!",
                DeliveryDate    = deliveryDate.Date.AddHours(9 + 5), // 9AM + EST = 5 hours
                Description     = creditLogDescription,
                LastUpdatedBy   = PublicCustomerInfos.CustomerId,
                LastUpdatedDate = DateTime.UtcNow,
                UserBookedDate  = userBookedDate
            };

            int giftCardBooking = _giftCardBookingRepository.Add(param);

            CacheLayer.Clear(CacheKeys.GiftCardCacheKey);
            CacheLayer.Clear(CacheKeys.GiftCardBookingCacheKey);

            CacheLayer.Clear(CacheKeys.CustomerCreditsCacheKey);
            CacheLayer.Clear(CacheKeys.CustomerCreditLogsCacheKey);

            return(giftCardBooking);
        }
        private int PurchaseSubscription(out bool success)
        {
            // Check customer change their email
            success = true;
            bool isPayByCredit;

            var bookingExists = _subscriptionBookingRepository.GetBookingInLast3Minutes(PublicSubscription.Id,
                                                                                        PublicCustomerInfos != null ? PublicCustomerInfos.EmailAddress : email.Text.Replace(" ", ""));

            if (bookingExists != null)
            {
                success = false;
                newBookingModal.Visible = true;
                return(bookingExists.Id);
            }

            if (PublicCustomerInfos == null)
            {
                PublicCustomerInfos = new CustomerInfos
                {
                    EmailAddress = email.Text.Replace(" ", ""),
                    FirstName    = FirstName.Text.Trim(),
                    LastName     = LastName.Text.Trim(),
                    ZipCode      = txtzipcode.Text.Trim()
                };

                // Create new account with email
                var response = _customerInfoRepository.GetVipAccess(email.Text.Replace(" ", ""), Constant.SearchPageDefault, FirstName.Text.Trim(), LastName.Text.Trim());
                PublicCustomerInfos.CustomerId       = response.CustomerId;
                PublicCustomerInfos.StripeCustomerId = response.StripeCustomerId;

                CacheLayer.Clear(CacheKeys.CustomerInfosCacheKey);
                CacheLayer.Clear(CacheKeys.CustomerCreditsCacheKey);

                Session["ReferralCode"] = response.ReferralCode;

                string searchPage = !string.IsNullOrEmpty((string)Session["SearchPage"])
                    ? Session["SearchPage"].ToString()
                    : Constant.SearchPageDefault;

                // Send email new account
                var responseEmail = EmailHelper.EmailNewAccount(PublicCustomerInfos.EmailAddress,
                                                                PublicCustomerInfos.FirstName,
                                                                response.Password,
                                                                Helper.ResolveRelativeToAbsoluteUrl(Request.Url,
                                                                                                    string.Format("{0}?sp={1}",
                                                                                                                  searchPage,
                                                                                                                  response.PasswordKey)), // Reset Password Url
                                                                Helper.ResolveRelativeToAbsoluteUrl(Request.Url,
                                                                                                    string.Format("{0}?c={1}",
                                                                                                                  searchPage,
                                                                                                                  response.AccessKey))); // Browse Day Pass
                PublicCustomerCredits = _subscriptionBookingRepository.GetCustomerCredits(response.CustomerId);


                Session["UserSession"]  = response.AccessKey;
                Session["IsRegister"]   = true;
                Session["ReferralCode"] = response.ReferralCode;
            }

            Regex regex = new Regex(@"([\d]+)(\s)?/(\s)?([\d]+)");
            int   month;
            int   year;

            int.TryParse(regex.Match(txtexpdat.Value).Groups[1].Value, out month);
            int.TryParse("20" + regex.Match(txtexpdat.Value).Groups[4].Value, out year);
            string fullName = string.Format("{0} {1}", FirstName.Text, LastName.Text);

            // Check customer has exists with email
            int            customerId     = PublicCustomerInfos.CustomerId;
            StripeCustomer stripeCustomer = null;
            Discounts      discounts      = new Discounts();
            double         actualPrice    = PublicSubscription.Price;
            double         totalPrice;
            bool           hasCoupon      = false;
            string         stripeCouponId = string.Empty;

            // update user info with exists
            if (!string.IsNullOrEmpty(PublicCustomerInfos.StripeCustomerId))
            {
                stripeCustomer = GetCustomerById(PublicCustomerInfos.StripeCustomerId);
            }

            // Use New Card
            if (MVCardInfo.ActiveViewIndex == 0)
            {
                StripeToken stripeToken = CreateToken(cctextbox.Text.Replace(" ", ""), year, month, txtzipcode.Text,
                                                      fullName,
                                                      txtseccode.Value);

                // update new card for customer
                PublicCustomerInfos.StripeTokenId    = stripeToken.Id;
                PublicCustomerInfos.StripeCardId     = stripeToken.StripeCard.Id;
                PublicCustomerInfos.BankAccountLast4 = stripeToken.StripeCard.Last4;
                PublicCustomerInfos.CardType         = Helper.GetCreditCardType(cctextbox.Text.Replace(" ", ""));
                PublicCustomerInfos.ZipCode          = txtzipcode.Text;

                if (stripeCustomer == null)
                {
                    stripeCustomer = CreateCustomer(PublicCustomerInfos.EmailAddress, fullName, stripeToken.Id);
                    PublicCustomerInfos.StripeCustomerId = stripeCustomer.Id;
                }
                else
                {
                    // Update Stripe exists customer with New Card
                    var card = CreateCard(stripeToken.Id, PublicCustomerInfos.StripeCustomerId);
                    UpdateCustomer(PublicCustomerInfos.EmailAddress, fullName,
                                   PublicCustomerInfos.StripeCustomerId, card.Id);
                }
                _customerInfoRepository.Update(PublicCustomerInfos);

                isPayByCredit = IsPayByCreditCheckBox.Checked;
            }
            else
            {
                isPayByCredit = DCreditCheckBox.Checked;
            }

            if (string.IsNullOrWhiteSpace(PromoText.Text))
            {
                Session.Remove(_discountKey);
            }

            // Not available upgrade so checkout with this hotel
            if (Session[_discountKey] != null)
            {
                discounts = JsonConvert.DeserializeObject <Discounts>(Session[_discountKey].ToString());
            }

            // Have Discount
            if (discounts != null && discounts.Id > 0)
            {
                discounts = _discountRepository.VerifyDiscountsSubscription(discounts, customerId, PublicSubscription.Id);

                // Discount Invalid
                if (discounts != null)
                {
                    actualPrice = Helper.CalculateDiscount(discounts, actualPrice, TotalTickets);
                    hasCoupon   = true;
                }
                else
                {
                    InitDefaultPromo(Message.ExceedLimit, false);
                    Session[_discountKey] = null;
                    success = false;
                    return(0);
                }

                if (discounts.BillingCycleNumber > 1)
                {
                    stripeCouponId = string.Format("{0}C{1}", PublicCustomerInfos.CustomerId,
                                                   Helper.RandomString(Constant.BookingCodeLength));
                    if (discounts.PercentOff > 0)
                    {
                        var couponPrice = PublicSubscription.Price - actualPrice;
                        //Create the Coupon
                        var coupon = new StripeCouponCreateOptions
                        {
                            Duration         = "repeating",
                            Id               = stripeCouponId,
                            MaxRedemptions   = discounts.BillingCycleNumber,
                            DurationInMonths = discounts.BillingCycleNumber
                        };


                        if (discounts.PromoType == (int)Enums.PromoType.Fixed)
                        {
                            coupon.AmountOff = (int)(couponPrice * 100);
                            coupon.Currency  = "usd";
                        }

                        if (discounts.PromoType == (int)Enums.PromoType.Percent)
                        {
                            coupon.PercentOff = (int)(discounts.PercentOff);
                        }

                        //coupon.AmountOff - AmountOff is not a property of StripeCouponCreateOptions
                        var          couponService = new StripeCouponService();
                        StripeCoupon createdCoupon = couponService.Create(coupon);

                        //Apply it to the customer
                        var customerOptions = new StripeCustomerUpdateOptions
                        {
                            Coupon = createdCoupon.Id
                        };

                        var customerService = new StripeCustomerService();
                        customerService.Update(PublicCustomerInfos.StripeCustomerId, customerOptions);
                    }
                }
            }

            if (PublicCustomerInfos.FirstName != FirstName.Text.Trim() || PublicCustomerInfos.LastName != LastName.Text.Trim())
            {
                PublicCustomerInfos.FirstName = FirstName.Text.Trim();
                PublicCustomerInfos.LastName  = LastName.Text.Trim();
                _customerInfoRepository.Update(PublicCustomerInfos);

                // Update Stripe exists customer
                UpdateCustomer(PublicCustomerInfos.EmailAddress, fullName, PublicCustomerInfos.StripeCustomerId, string.Empty);
            }

            // Discount 100% ??
            // Price equal 0, so we should not charge with this
            totalPrice = actualPrice * TotalTickets;
            double chargePrice          = totalPrice;
            string creditLogDescription = string.Empty;

            var subscriptionOptions = new StripeSubscriptionCreateOptions
            {
                PlanId = PublicSubscription.StripePlanId
            };

            // Use DayAxe Credit
            if (isPayByCredit && PublicCustomerCredits != null && PublicCustomerCredits.Amount > 0)
            {
                hasCoupon = true;

                chargePrice = totalPrice - PublicCustomerCredits.Amount;
                if (chargePrice <= 0)
                {
                    chargePrice = 0;
                }
            }

            if (hasCoupon && string.IsNullOrEmpty(stripeCouponId))
            {
                var couponPrice = PublicSubscription.Price - chargePrice;
                if (couponPrice > 0)
                {
                    // Create Coupon Id because we used DayAxe Credit
                    stripeCouponId = string.Format("{0}C{1}", PublicCustomerInfos.CustomerId,
                                                   Helper.RandomString(Constant.BookingCodeLength));
                    var couponOptions = new StripeCouponCreateOptions
                    {
                        Id        = stripeCouponId,
                        AmountOff = Convert.ToInt32(couponPrice * 100), // USD
                        Duration  = "once",
                        Currency  = "USD"
                    };

                    // Create Coupon
                    var couponService = new StripeCouponService();
                    var coupon        = couponService.Create(couponOptions);

                    subscriptionOptions.CouponId = stripeCouponId;

                    creditLogDescription = string.Format("{0} – {1}",
                                                         PublicSubscription.Name, coupon.Id);
                }
            }

            // Create Subscription on Stripe
            var subscriptionService         = new StripeSubscriptionService();
            StripeSubscription subscription = subscriptionService.Create(PublicCustomerInfos.StripeCustomerId, subscriptionOptions);

            var booking = new SubscriptionBookings
            {
                SubscriptionId       = PublicSubscription.Id,
                Quantity             = TotalTickets,
                StripeCouponId       = stripeCouponId,
                BookedDate           = DateTime.UtcNow,
                ActivedDate          = subscription.Start,
                StartDate            = subscription.CurrentPeriodStart,
                EndDate              = subscription.CurrentPeriodEnd,
                Status               = (int)Enums.SubscriptionBookingStatus.Active,
                CustomerId           = customerId,
                LastUpdatedDate      = DateTime.UtcNow,
                LastUpdatedBy        = customerId,
                StripeSubscriptionId = subscription.Id
            };

            var param = new AddSubscriptionBookingParams
            {
                SubscriptionBookingsObject = booking,
                CustomerCreditsObject      = PublicCustomerCredits,
                Description                  = creditLogDescription,
                SubscriptionName             = PublicSubscription.Name,
                FirstName                    = PublicCustomerInfos.FirstName,
                LastName                     = PublicCustomerInfos.LastName,
                SubscriptionBookingDiscounts = discounts,
                ActualPrice                  = actualPrice,
                MerchantPrice                = PublicSubscription.Price,
                PayByCredit                  = totalPrice.Equals(chargePrice) ? 0 : totalPrice - chargePrice,
                TotalPrice                   = chargePrice,
                MaxPurchases                 = PublicSubscription.MaxPurchases
            };

            int bookingId = _subscriptionBookingRepository.Add(param);

            //Session.Remove(_discountKey);

            CacheLayer.Clear(CacheKeys.SubscriptionBookingsCacheKey);
            CacheLayer.Clear(CacheKeys.CustomerInfosCacheKey);
            CacheLayer.Clear(CacheKeys.CustomerCreditsCacheKey);
            CacheLayer.Clear(CacheKeys.CustomerCreditLogsCacheKey);
            CacheLayer.Clear(CacheKeys.DiscountsCacheKey);
            CacheLayer.Clear(CacheKeys.SubscriptionBookingDiscountsCacheKey);
            CacheLayer.Clear(CacheKeys.SubsciptionDiscountUsedCacheKey);
            CacheLayer.Clear(CacheKeys.SubscriptionDiscountsCacheKey);
            CacheLayer.Clear(CacheKeys.SubscriptionCyclesCacheKey);

            return(bookingId);
        }