private StripeCard GetCardById(string customerId, string cardId) { var cardService = new StripeCardService(); StripeCard stripeCard = cardService.Get(customerId, cardId); return(stripeCard); }
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 listing_cards_on_customer() { var customerService = new StripeCustomerService(Cache.ApiKey); var bankAccountService = new BankAccountService(Cache.ApiKey); var cardService = new StripeCardService(Cache.ApiKey); var CustomerCreateOptions = new StripeCustomerCreateOptions { Email = "*****@*****.**", SourceToken = "tok_visa", }; var Customer = customerService.Create(CustomerCreateOptions); var BankAccountCreateOptions = new BankAccountCreateOptions { SourceBankAccount = new SourceBankAccount() { RoutingNumber = "110000000", AccountNumber = "000123456789", Country = "US", Currency = "usd", AccountHolderName = "Jenny Rosen", AccountHolderType = BankAccountHolderType.Individual, } }; var BankAccount = bankAccountService.Create(Customer.Id, BankAccountCreateOptions); ListCards = cardService.List(Customer.Id); }
public IHttpActionResult GetCustomerCards() { StripeConfiguration.SetApiKey(StripeKey); IEnumerable <StripeCard> response; string userId = User.Identity.GetUserId(); var query = (from u in userdb.Users where u.Id == userId select new { u.StripeCustomerId, }).First(); var StripeID = query.StripeCustomerId; try { var cardService = new StripeCardService(); response = cardService.List(StripeID); } catch (StripeException sex) { return(Content(HttpStatusCode.BadRequest, sex)); } return(CreatedAtRoute("GetCustomerCards", new { }, response.ToList())); }
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); }
// GET: Subscriptions public ActionResult Index() { var userId = User.Identity.GetUserId(); var user = UserManager.FindById(userId); if (user.SubscriptionId == 0) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } var subscription = db.Subscriptions.Find(user.SubscriptionId); if (subscription == null) { return(HttpNotFound()); } var customerService = new StripeCustomerService(); var stripeCustomer = customerService.Get(subscription.StripeCustomerId); var subscriptionview = new SubscriptionDetailsViewModel { AdminEmail = stripeCustomer.Email, CardExpiration = new DateTime(), CardLastFour = "n/a", MonthlyPrice = "n/a", SubscribedPlan = "n/a" }; var subscriptionService = new StripeSubscriptionService(); IEnumerable <StripeSubscription> stripeSubscriptions = subscriptionService.List(subscription.StripeCustomerId); if (stripeSubscriptions.Any()) { subscriptionview.SubscribedPlan = stripeSubscriptions.FirstOrDefault().StripePlan.Name; subscriptionview.MonthlyPrice = stripeSubscriptions.FirstOrDefault().StripePlan.Amount.ToString(); } var cardService = new StripeCardService(); IEnumerable <StripeCard> stripeCards = cardService.List(subscription.StripeCustomerId); if (stripeCards.Any()) { var dateString = string.Format("{1}/1/{0}", stripeCards.FirstOrDefault().ExpirationYear, stripeCards.FirstOrDefault().ExpirationMonth); subscriptionview.CardExpiration = DateTime.Parse(dateString); subscriptionview.CardLastFour = "XXXX XXXX XXXX " + stripeCards.FirstOrDefault().Last4; } return(View(subscriptionview)); }
public static StripeCard GetCardDetails(String custmId, String cardId) { var cardService = new StripeCardService(); try { return(cardService.Get(custmId, cardId)); } catch (Exception ex) { return(null); } }
public static bool DeleteCard(string cardId, string customerID) { var cardService = new StripeCardService(); try { cardService.Delete(customerID, cardId); return(true); } catch (Exception ex) { return(false); } }
//list all customer cards public StripeList <StripeCard> ListAllCards(UserSubscriptionUpdateStripeRequest model) { StripeConfiguration.SetApiKey(""); var cardService = new StripeCardService(); StripeList <StripeCard> response = cardService.List( model.CustomerId, new StripeCardListOptions() { Limit = 3 } ); return(response); }
public ActionResult ManageCards() { var loggedOnMember = Members.GetCurrentMember(); var member = new Member(Umbraco.TypedMember(loggedOnMember.Id)); IEnumerable <StripeCard> cardList = null; if (member.StripeUserId.IsNotNullOrEmpty()) { StripeCardService cardService = new StripeCardService(SensativeInformation.StripeKeys.SecretKey); cardList = cardService.List(member.StripeUserId); } var model = cardList; return(PartialView("ManageCards", model)); }
public async Task <List <RetrievedCard> > GetAllCurrentCards(string email) { var list = new List <RetrievedCard>(); using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization", $"Bearer {StripeClientConstants.ApiKey}"); var response = await client.GetStringAsync(_stripeSearchQueryUri + email + "&prefix=false"); var data = JsonConvert.DeserializeObject <RootStripeApiJsonData>(response); var customerId = data.data.Count == 0 ? string.Empty : data.data[0].id; StripeConfiguration.SetApiKey(StripeClientConstants.ApiKey); var cardService = new StripeCardService(); StripeList <StripeCard> cardlist = cardService.List(customerId, new StripeListOptions() { Limit = 5 }, false, new StripeRequestOptions() { ApiKey = _stripeSecretTestkey } ); if (cardlist.Any()) { foreach (var item in cardlist) { list.Add(new RetrievedCard() { Name = item.Name, Last4 = item.Last4, Id = item.Id }); } } else { return(list); } return(list); } }
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); }
public async Task <dynamic> Post() { try { var item = RequestContext.Principal.Identity; string value = await Request.Content.ReadAsStringAsync(); var entidad = System.Web.Helpers.Json.Decode(value); var customer = entidad.customerId; var card = entidad.cardId; var cardService = new StripeCardService("sk_test_CBdkobSnlUEOyOjsLQ8fpqof"); cardService.Delete(customer, card); return("Eliminada"); } catch (Exception ex) { return(ex); } }
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)); }
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")); }
public async Task ReplacePaymentMethodAsync(Guid organizationId, string paymentToken) { var organization = await _organizationRepository.GetByIdAsync(organizationId); if (organization == null) { throw new NotFoundException(); } var cardService = new StripeCardService(); var customerService = new StripeCustomerService(); StripeCustomer customer = null; if (!string.IsNullOrWhiteSpace(organization.StripeCustomerId)) { customer = await customerService.GetAsync(organization.StripeCustomerId); } if (customer == null) { customer = await customerService.CreateAsync(new StripeCustomerCreateOptions { Description = organization.BusinessName, Email = organization.BillingEmail, SourceToken = paymentToken }); organization.StripeCustomerId = customer.Id; await _organizationRepository.ReplaceAsync(organization); } await cardService.CreateAsync(customer.Id, new StripeCardCreateOptions { SourceToken = paymentToken }); if (!string.IsNullOrWhiteSpace(customer.DefaultSourceId)) { await cardService.DeleteAsync(customer.Id, customer.DefaultSourceId); } }
public static List <StripeCard> GetCard(string customerId) { var cardService = new StripeCardService(); try { if (customerId != null) { var response = cardService.List(customerId).ToList(); return(response); } else { return(null); } } catch (Exception ex) { return(null); } }
public string UpdateCustomer(string stripeId, string ccToken) { //remove old card var customerService = new StripeCustomerService(Constants.StripeSecretKey); Stripe.StripeCustomer stripeCustomer = customerService.Get(stripeId); if (!String.IsNullOrEmpty(stripeCustomer.DefaultSourceId)) { var cardService = new StripeCardService(Constants.StripeSecretKey); cardService.Delete(stripeId, stripeCustomer.DefaultSourceId); } var myCustomer = new StripeCustomerUpdateOptions(); myCustomer.SourceToken = ccToken; // this will set the default card to use for this customer var finalCustomer = customerService.Update(stripeId, myCustomer); return(finalCustomer.Id); }
public async Task <StripeCustomer> SetPaymentInformationAsync(string tenantDomain, SetPaymentInformationParameters parameters) { using (var session = _documentStore.OpenAsyncSession()) { try { var organization = await session.Query <Organization>().FirstOrDefaultAsync(o => o.OrganizationDomain == tenantDomain); if (organization == null) { throw new Exception(string.Format("Could not find Organization for Domain '{0}'.", tenantDomain)); } if (organization.CustomerId == null) { throw new Exception($"The customer {tenantDomain} does not have an associated Stripe customer ID."); } var stripeCustomerService = new StripeCustomerService(); var customer = await stripeCustomerService.GetAsync(organization.CustomerId); if (customer == null) { throw new Exception("Could not load customer data."); } var cardService = new StripeCardService(); if (customer.DefaultSourceId != null) { await cardService.DeleteAsync(customer.Id, customer.DefaultSourceId); } return(await stripeCustomerService.UpdateAsync(customer.Id, parameters.ToStripeCustomerUpdateOptions())); } catch (Exception) { session.Dispose(); throw; } } }
public StripeCardServiceTest() { this.service = new StripeCardService(); this.createOptions = new StripeCardCreateOptions() { SourceToken = "tok_123", }; this.updateOptions = new StripeCardUpdateOptions() { Metadata = new Dictionary <string, string>() { { "key", "value" }, }, }; this.listOptions = new StripeCardListOptions() { Limit = 1, }; }
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; } }
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)); }
// 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 async Task <IActionResult> CampaignPayment(CustomerPaymentViewModel payment) { try { var user = await GetCurrentUserAsync(); if (!ModelState.IsValid) { return(View(payment)); } var customerService = new StripeCustomerService(_stripeSettings.Value.SecretKey); var donation = _campaignService.GetById(payment.DonationId); // Construct payment if (string.IsNullOrEmpty(user.StripeCustomerId)) { StripeCustomerCreateOptions customer = GetCustomerCreateOptions(payment, user); var stripeCustomer = customerService.Create(customer); user.StripeCustomerId = stripeCustomer.Id; } else { //Check for existing credit card, if new credit card number is same as exiting credit card then we delete the existing //Credit card information so new card gets generated automatically as default card. try { var ExistingCustomer = customerService.Get(user.StripeCustomerId); if (ExistingCustomer.Sources != null && ExistingCustomer.Sources.TotalCount > 0 && ExistingCustomer.Sources.Data.Any()) { var cardService = new StripeCardService(_stripeSettings.Value.SecretKey); foreach (var cardSource in ExistingCustomer.Sources.Data) { cardService.Delete(user.StripeCustomerId, cardSource.Card.Id); } } } catch (Exception ex) { log = new EventLog() { EventId = (int)LoggingEvents.INSERT_ITEM, LogLevel = LogLevel.Error.ToString(), Message = ex.Message, StackTrace = ex.StackTrace, Source = ex.Source }; _loggerService.SaveEventLogAsync(log); return(RedirectToAction("Error", "Error500", new ErrorViewModel() { Error = ex.Message })); } StripeCustomerUpdateOptions customer = GetCustomerUpdateOption(payment); var stripeCustomer = customerService.Update(user.StripeCustomerId, customer); user.StripeCustomerId = stripeCustomer.Id; } UpdateUserEmail(payment, user); await UpdateUserDetail(payment, user); // Add customer to Stripe if (EnumInfo <PaymentCycle> .GetValue(donation.CycleId) == PaymentCycle.OneTime) { var model = (DonationViewModel)donation; var charges = new StripeChargeService(_stripeSettings.Value.SecretKey); // Charge the customer var charge = charges.Create(new StripeChargeCreateOptions { Amount = Convert.ToInt32(donation.DonationAmount * 100), Description = DonationCaption, Currency = "usd",//payment.Currency.ToLower(), CustomerId = user.StripeCustomerId, StatementDescriptor = _stripeSettings.Value.StatementDescriptor, }); if (charge.Paid) { var completedMessage = new CompletedViewModel { Message = donation.DonationAmount.ToString(), HasSubscriptions = false }; return(RedirectToAction("Thanks", completedMessage)); } return(RedirectToAction("Error", "Error", new ErrorViewModel() { Error = "Error" })); } // Add to existing subscriptions and charge donation.Currency = "usd"; //payment.Currency; var plan = _campaignService.GetOrCreatePlan(donation); var subscriptionService = new StripeSubscriptionService(_stripeSettings.Value.SecretKey); var result = subscriptionService.Create(user.StripeCustomerId, plan.Id); if (result != null) { var completedMessage = new CompletedViewModel { Message = result.StripePlan.Nickname.Split("_")[1] + result.StripePlan.Nickname.Split("_")[0], HasSubscriptions = true }; return(RedirectToAction("Thanks", completedMessage)); } } catch (StripeException ex) { log = new EventLog() { EventId = (int)LoggingEvents.INSERT_ITEM, LogLevel = LogLevel.Error.ToString(), Message = ex.Message, StackTrace = ex.StackTrace, Source = ex.Source }; _loggerService.SaveEventLogAsync(log); if (ex.Message.ToLower().Contains("customer")) { return(RedirectToAction("Error", "Error500", new ErrorViewModel() { Error = ex.Message })); } else { ModelState.AddModelError("error", ex.Message); return(View(payment)); } } catch (Exception ex) { log = new EventLog() { EventId = (int)LoggingEvents.INSERT_ITEM, LogLevel = LogLevel.Error.ToString(), Message = ex.Message, StackTrace = ex.StackTrace, Source = ex.Source }; _loggerService.SaveEventLogAsync(log); return(RedirectToAction("Error", "Error", new ErrorViewModel() { Error = ex.Message })); } return(RedirectToAction("Error", "Error", new ErrorViewModel() { Error = "Error" })); }
public StripeBillingCardService(string apiKey, IMapper mapper) { _service = new StripeCardService(apiKey); _mapper = mapper; }
public async Task <bool> UpdatePaymentMethodAsync(ISubscriber subscriber, string paymentToken) { if (subscriber == null) { throw new ArgumentNullException(nameof(subscriber)); } if (subscriber.Gateway.HasValue && subscriber.Gateway.Value != Enums.GatewayType.Stripe) { throw new GatewayException("Switching from one payment type to another is not supported. " + "Contact us for assistance."); } var updatedSubscriber = false; var cardService = new StripeCardService(); var bankSerice = new BankAccountService(); var customerService = new StripeCustomerService(); StripeCustomer customer = null; if (!string.IsNullOrWhiteSpace(subscriber.GatewayCustomerId)) { customer = await customerService.GetAsync(subscriber.GatewayCustomerId); } if (customer == null) { customer = await customerService.CreateAsync(new StripeCustomerCreateOptions { Description = subscriber.BillingName(), Email = subscriber.BillingEmailAddress(), SourceToken = paymentToken }); subscriber.Gateway = Enums.GatewayType.Stripe; subscriber.GatewayCustomerId = customer.Id; updatedSubscriber = true; } else { if (paymentToken.StartsWith("btok_")) { await bankSerice.CreateAsync(customer.Id, new BankAccountCreateOptions { SourceToken = paymentToken }); } else { await cardService.CreateAsync(customer.Id, new StripeCardCreateOptions { SourceToken = paymentToken }); } if (!string.IsNullOrWhiteSpace(customer.DefaultSourceId)) { var source = customer.Sources.FirstOrDefault(s => s.Id == customer.DefaultSourceId); if (source.BankAccount != null) { await bankSerice.DeleteAsync(customer.Id, customer.DefaultSourceId); } else if (source.Card != null) { await cardService.DeleteAsync(customer.Id, customer.DefaultSourceId); } } } return(updatedSubscriber); }
/// <summary> /// Initializes a new instance of the <see cref="CardProvider"/> class. /// </summary> /// <param name="apiKey">The API key.</param> /// <param name="cardDataService">The card data service.</param> public CardProvider(string apiKey, ICardDataService cardDataService) { this._cardDataService = cardDataService; this._cardService = new StripeCardService(apiKey); }
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)); }