public async Task <StripeCustomer> CreateCustomerAsync(StripeCustomerCreateOptions options, string apiKey) { var customerService = new StripeCustomerService(apiKey); var customer = customerService.Create(options); return(customer); }
public IHttpActionResult PostPaymentAccount(StripeBindingModel stripeBindingModel) { int accountId = this.GetAccountId(); Account account = db.Accounts.Find(accountId); if (!ModelState.IsValid) { return(BadRequest(ModelState)); } // Use stripe to get the customer token string stripeCustomerToken = ""; var myCustomer = new StripeCustomerCreateOptions(); myCustomer.SourceToken = stripeBindingModel.CardToken; var customerService = new StripeCustomerService(); var stripeCustomer = customerService.Create(myCustomer); PaymentAccount paymentAccount = new PaymentAccount(PaymentMethod.Stripe, stripeCustomerToken); paymentAccount.AccountId = accountId; // updae the default payment account as the new account account.DefaultPaymentAccount = paymentAccount; db.SetModified(account); db.SaveChanges(); return(CreatedAtRoute("DefaultApi", new { id = paymentAccount.Id }, paymentAccount)); }
private static string CreateStripeCustomer(string userId, string stripeToken) { var customerService = new StripeCustomerService(); var getStripeCustomer = _context.StripeCustomers.FirstOrDefault(c => c.UserId == userId); if (getStripeCustomer != null) { return(getStripeCustomer.StripeCustomerID); } var getUser = _context.Users.FirstOrDefault(c => c.Id == userId); var customerOptions = new StripeCustomerCreateOptions() { Description = "Veme Customer", SourceToken = stripeToken, Email = getUser.Email }; Stripe.StripeCustomer customer = customerService.Create(customerOptions); _context.StripeCustomers.Add(new POCO.StripeCustomer { CreationDate = DateTime.Now.Date, StripeCustomerID = customer.Id, UserId = userId }); _context.SaveChanges(); return(customer.Id); }
public ActionResult AddCard(CustomerUnsecureAddCardViewModel model) { if (!ModelState.IsValid) { return(View(model)); } var options = new StripeCustomerUpdateOptions { Source = new StripeSourceOptions() { Object = "card", Number = model.CardNumber, AddressCity = model.City, AddressLine1 = model.Address, AddressLine2 = model.Address2, AddressState = model.State.ToString(), AddressZip = model.Zip, Cvc = model.Cvc, Name = model.CardholderName, ExpirationMonth = model.ExpirationMonth.ToString(), ExpirationYear = model.ExpirationYear.ToString() } }; var customerService = new StripeCustomerService(); customerService.Update(model.CustomerId, options); return(RedirectToAction("Details", new { id = model.CustomerId })); }
public GetCustomerResponse GetCustomerInformation(string customerId) { var response = new GetCustomerResponse(); var customerService = new StripeCustomerService(); try { StripeCustomer stripeCustomer = customerService.Get(customerId); MapStripeCustomerTo(stripeCustomer, response); response.Success = true; } catch (StripeException ex) { response.Success = false; response.Message = ex.Message; return(response); } catch (Exception ex) { response.Success = false; response.Message = ex.Message; } return(response); }
public ActionResult Index(string jsonCardInformation) { JObject jObject = JObject.Parse(jsonCardInformation); string key = ConfigurationManager.AppSettings["StripeSecretKey"]; var myCustomer = new StripeCustomerCreateOptions(); myCustomer.Email = System.Web.HttpContext.Current.User.Identity.Name; myCustomer.Description = "Testing a Card"; myCustomer.SourceToken = jObject["tokenId"].ToString(); var customerService = new StripeCustomerService(); StripeRequestOptions requestOption = new StripeRequestOptions() { ApiKey = key }; StripeCustomer stripeCustomer = new StripeCustomer(); stripeCustomer = customerService.Create(myCustomer, requestOption); CardInfo newCustomer = new CardInfo() { CustomerId = stripeCustomer.Id, Email = System.Web.HttpContext.Current.User.Identity.Name, Name = jObject["name"].ToString(), CardType = jObject["cardBrand"].ToString(), LastFour = jObject["lastFour"].ToString() }; ctx.Cards.Add(newCustomer); ctx.SaveChanges(); var x = ctx.Cards.Where(y => y.Email == System.Web.HttpContext.Current.User.Identity.Name); return(View(x)); }
public ActionResult Edit(CustomerCreateViewModel model) { if (!ModelState.IsValid) { return(View(model)); } var customerService = new StripeCustomerService(); var stripeCustomer = customerService.Get(model.Id); var applicationUser = UserManager.FindByEmail(stripeCustomer.Email); var updateOptions = new StripeCustomerUpdateOptions { Description = model.Description }; customerService.Update(model.Id, updateOptions); applicationUser.FirstName = model.FirstName; applicationUser.LastName = model.LastName; applicationUser.PhoneNumber = model.PhoneNumber; applicationUser.Address = model.Address; applicationUser.Address2 = model.Address2; applicationUser.City = model.City; applicationUser.State = model.State; applicationUser.Zip = model.Zip; UserManager.Update(applicationUser); return(RedirectToAction("Details", new { id = model.Id })); }
public void Create(string userName, Plan plan, string stripeToken) { //get User var user = UserManager.FindByName(userName); if (string.IsNullOrEmpty(user.StripeCustomerId)) //First Time customer { //create customer which will create subscription if plan is set and cc info via token is provided var customer = new StripeCustomerCreateOptions() { Email = user.Email, Source = new StripeSourceOptions() { TokenId = stripeToken }, PlanId = plan.ExternalId //external id is Stripe plan id }; StripeCustomer stripeCustomer = StripeCustomerService.Create(customer); //update user user.StripeCustomerId = stripeCustomer.Id; user.ActiveUntil = DateTime.Now.AddDays((double)plan.TrialPeriodDays); UserManager.Update(user); } else { //customer already exists, add subscription to customer var stripeSubscription = StripeSubscriptionService.Create(user.StripeCustomerId, plan.ExternalId); user.ActiveUntil = DateTime.Now.AddDays((double)plan.TrialPeriodDays); UserManager.Update(user); } }
public ActionResult CreateClient(string clientName, int numberOfMonths, string stripeEmail, string stripeToken) { var customers = new StripeCustomerService(); var charges = new StripeChargeService(); var customer = customers.Create(new StripeCustomerCreateOptions { Email = stripeEmail, SourceToken = stripeToken }); var charge = charges.Create(new StripeChargeCreateOptions { Amount = numberOfMonths * 389, Description = "Client creation", Currency = "eur", CustomerId = customer.Id }); try { _clientManager.CreateNew(clientName, DateTime.UtcNow.AddMonths(numberOfMonths), _membership.CurrentUser.Id); } catch (BusinessException be) { ///TODO Log error. return(RedirectToAction("Index", "Error")); } return(RedirectToAction("Index", "Profile")); }
public RevokePaymentMethod_Result RevokePaymentMethod(RevokePaymentMethod_Details details) { StripeConfiguration.SetApiKey(secretKey); StripeDeleted delete = new StripeDeleted(); try { var customerService = new StripeCustomerService(); delete = customerService.Delete(details.CardToken); } catch (StripeException e) { return(new RevokePaymentMethod_Result() { ErrorCode = e.StripeError.Code, ErrorMessage = e.StripeError.Message }); } return(new RevokePaymentMethod_Result() { ErrorMessage = delete.Deleted + "", isSuccess = delete.Deleted, TransactionIdentifier = delete.Id, }); }
private StripeCustomer createTCGStripeCustomer(StorePaymentMethod_Details details, string sourceToken) { StripeConfiguration.SetApiKey(secretKey); StripeCustomer customer = new StripeCustomer(); try { StripeSource source = new StripeSource(); if (sourceToken == null) { source = createStripeSource(details.CardNumber, details.CardExpiryYear, details.CardExpiryMonth, details.CardCVV, details.CardHolderFullName, true); } else { source.Id = sourceToken; } //ATTACH THE SOURCE TO CUSTOMER var customerOptions = new StripeCustomerCreateOptions() { SourceToken = source.Id }; var customerService = new StripeCustomerService(); customer = customerService.Create(customerOptions); } catch (StripeException e) { throw new StripeException(e.HttpStatusCode, e.StripeError, e.Message); } return(customer); }
/// <summary> /// Creates a new customer record in Stripe for the given user /// This will set the "PaymentSystemId" property on the given IStripeUser instance if the user was successfully created /// NOTE: Save changes on the underlying context for the model after calling this method /// </summary> /// <param name="customer"></param> /// <param name="paymentToken"></param> public static StripeCustomer CreateCustomer(ICustomerEntity customer, string paymentToken = null) { // Do not overwrite the user, ever if (customer.HasPaymentInfo()) { return(null); } var newCustomer = new StripeCustomerCreateOptions(); newCustomer.Email = customer.Email; if (paymentToken != null) { newCustomer.Source = new StripeSourceOptions() { TokenId = paymentToken } } ; var customerService = new StripeCustomerService(); StripeCustomer stripeCustomer = customerService.Create(newCustomer); // Set the accounting info customer.PaymentSystemId = stripeCustomer.Id; Logger.Log <StripeManager>("Created customer in stripe: '{0}' with id '{1}", LogLevel.Information, customer.Email, customer.PaymentSystemId); return(stripeCustomer); }
// GET: Admin/Dashboard public ActionResult Index() { var customerService = new StripeCustomerService(); var customers = customerService.List(); var balanceService = new StripeBalanceService(); var balance = balanceService.Get(); var chargeService = new StripeChargeService(); var charges = chargeService.List().Where(c => c.Dispute != null); var sc = customers as StripeCustomer[] ?? customers.ToArray(); var model = new DashboardViewModel { CustomerCount = sc.Count(), AccountAvailableBalance = balance.Available.Sum(b => b.Amount), AccountPendingBalance = balance.Pending.Sum(b => b.Amount), MonthlyCustomerValue = sc.Sum(c => c.StripeSubscriptionList.Data.Sum(s => s.StripePlan.Amount)), DisputedChargeCount = charges.Sum(c => c.Dispute.Amount.GetValueOrDefault()), TrialCustomerCount = sc.Count(c => c.StripeSubscriptionList.Data.Any(s => s.Status.Equals("trialing"))), ActiveCustomerCount = sc.Count(c => c.StripeSubscriptionList.Data.Any(s => s.Status.Equals("active"))), PastDueCustomerCount = sc.Count(c => c.StripeSubscriptionList.Data.Any(s => s.Status.Equals("past_due"))), CanceledCustomerCount = sc.Count(c => c.StripeSubscriptionList.Data.Any(s => s.Status.Equals("canceled"))), UnpaidCustomerCount = sc.Count(c => c.StripeSubscriptionList.Data.Any(s => s.Status.Equals("unpaid"))), }; return(View(model)); }
public static StripeCharge GetStripeChargeInfo(string stripeEmail, string stripeToken, int amount) { var customers = new StripeCustomerService(); var charges = new StripeChargeService(); var stripeSettings = new StripeSettings(); stripeSettings.ReloadStripeSettings(); StripeConfiguration.SetApiKey(stripeSettings.SecretKey); var customer = customers.Create(new StripeCustomerCreateOptions { Email = stripeEmail, SourceToken = stripeToken }); var charge = charges.Create(new StripeChargeCreateOptions { Amount = amount * 100, //charge in cents Description = "Dunkey Delivery", Currency = "usd", CustomerId = customer.Id, }); return(charge); }
/// <summary> /// Retrieves the StripeCustomer associated with the given IStripeUser instance /// </summary> /// <param name="user"></param> /// <returns></returns> public static StripeCustomer RetrieveCustomer(IStripeUser user) { var customerService = new StripeCustomerService(); StripeCustomer stripeCustomer = customerService.Get(user.PaymentSystemId); return(stripeCustomer); }
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); }
/// <summary> /// Creates a new customer record in Stripe for the given user /// NOTE: Save changes on the underlying context for the model after calling this method /// </summary> /// <param name="user"></param> public static void CreateCustomer(IStripeUser user, string paymentToken = null) { // Do not overwrite the user, ever if (user.HasPaymentInfo()) { return; } var newCustomer = new StripeCustomerCreateOptions(); newCustomer.Email = user.Email; if (paymentToken != null) { newCustomer.Card = new StripeCreditCardOptions() { TokenId = paymentToken } } ; var customerService = new StripeCustomerService(); StripeCustomer stripeCustomer = customerService.Create(newCustomer); // Set the accounting info user.PaymentSystemId = stripeCustomer.Id; System.Diagnostics.Trace.TraceInformation("Created customer in stripe: '{0}' with id '{1}", user.Email, user.PaymentSystemId); }
public bool SaveCustomerByToken(string email, string stripeToken) { try { var customer = new StripeCustomerCreateOptions(); customer.Email = email; //customer.Description = "Johnny Tenderloin ([email protected])"; customer.TokenId = stripeToken; //customer.PlanId = *planId*; // only if you have a plan //customer.Coupon = *couponId*; // only if you have a coupon //customer.TrialEnd = DateTime.UtcNow.AddMonths(1); // when the customers trial ends (overrides the plan if applicable) //customer.Quantity = 1; // optional, defaults to 1 var customerService = new StripeCustomerService(Cohort.Site.Stripe.SecretKey); var stripeCustomer = customerService.Create(customer); // Create linkage between signup and customer for later charging return(true); } catch (Exception) { // log return(false); } }
public ActionResult Edit(string id) { if (string.IsNullOrEmpty(id)) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } var customerService = new StripeCustomerService(); var stripeCustomer = customerService.Get(id); var applicationUser = UserManager.FindByEmail(stripeCustomer.Email); var customer = new CustomerCreateViewModel { Id = stripeCustomer.Id, Email = stripeCustomer.Email, Description = stripeCustomer.Description, FirstName = applicationUser.FirstName, LastName = applicationUser.LastName, PhoneNumber = applicationUser.PhoneNumber, Address = applicationUser.Address, Address2 = applicationUser.Address2, City = applicationUser.City, State = applicationUser.State, Zip = applicationUser.Zip }; return(View(customer)); }
public void CancelAccount() { Helpers.SslSecurity.Callback(); var customerDetails = GetSavedCustomerStripeDetails(); if (customerDetails == null) { throw new Exceptions.InvalidDataException("Attempting to cancel an account but the customer does not have any stripe details"); } var custService = new StripeCustomerService(Helpers.SiteInfo.StripeAPISecretKey); custService.Delete(customerDetails.Item1); using (var db = InitializeSettings.DbFactory) { var data = db.Get <Majorsilence.Vpn.Poco.Users>(_userId); data.StripeCustomerAccount = ""; db.Update(data); this.email.SendMail_BackgroundThread("Your vpn credit card account has been deleted. " + "You will not be billed again. You will continue to have access until your current payment expires.", "VPN Credit Card Account Deleted", data.Email, true, null, Majorsilence.Vpn.Logic.Email.EmailTemplates.Generic); } }
public ActionResult AddCoupon(string id) { if (string.IsNullOrEmpty(id)) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } var customerService = new StripeCustomerService(); var stripeCustomer = customerService.Get(id); var user = UserManager.Users.First(u => u.Email == stripeCustomer.Email); if (stripeCustomer == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } var couponService = new StripeCouponService(); var coupons = couponService.List().Select(c => new SelectListItem { Value = c.Id, Text = c.Id }); var model = new CustomerAddCouponViewModel { CustomerDescription = string.Format("{0} {1} ({2})", user.FirstName, user.LastName, user.Email), CustomerId = id, SelectedCoupon = "", Coupons = coupons }; return(View(model)); }
public async Task CancelAndRecoverChargesAsync(ISubscriber subscriber) { if (!string.IsNullOrWhiteSpace(subscriber.GatewaySubscriptionId)) { var subscriptionService = new StripeSubscriptionService(); await subscriptionService.CancelAsync(subscriber.GatewaySubscriptionId, false); } if (string.IsNullOrWhiteSpace(subscriber.GatewayCustomerId)) { return; } var chargeService = new StripeChargeService(); var charges = await chargeService.ListAsync(new StripeChargeListOptions { CustomerId = subscriber.GatewayCustomerId }); if (charges?.Data != null) { var refundService = new StripeRefundService(); foreach (var charge in charges.Data.Where(c => !c.Refunded)) { await refundService.CreateAsync(charge.Id); } } var customerService = new StripeCustomerService(); await customerService.DeleteAsync(subscriber.GatewayCustomerId); }
public void CancelSubscription() { var user = AuthHelper.GetCurrentUser(); var usermanager = AuthHelper.GetUserManager(); try { var cust = new StripeCustomerService().Get(user.StripeCustomerId); if (cust != null) { var sub_svc = new StripeSubscriptionService(); var sub = sub_svc.Get(cust.Id, cust.StripeSubscriptionList.Data[0].Id); sub_svc.Cancel(cust.Id, sub.Id, true); } else { throw new ApplicationException("Could not find the customer in stripe to change the plan"); } } catch (Exception ex) { throw ex; } }
private StripeCustomer GetCustomer() { var mycust = new StripeCustomerCreateOptions(); SourceCard card = new SourceCard(); card.Number = "4242424242424242"; card.Name = "Yathiraj U"; card.ExpirationMonth = "10"; card.ExpirationYear = "2016"; card.AddressCountry = "USA"; card.ReceiptEmail = "*****@*****.**"; card.AddressCity = "abc"; mycust.Email = "uryathi834 @gmail.com"; card.Cvc = "123"; mycust.PlanId = "123456"; // mycust.TrialEnd = mycust.Description = "Rahul Pandey([email protected])"; mycust.SourceCard = card; // mycust.SourceCard = "USA"; // mycust.CardExpirationMonth = "10"; // mycust.CardExpirationYear = "2016"; // mycust.PlanId = "100"; //mycust.TrialEnd = getrialend(); var customerservice = new StripeCustomerService("sk_test_CQT723mQ9B3Qhzs7pxUtINLv"); return(customerservice.Create(mycust)); }
public bool Post([FromBody] JObject report) { Dictionary <string, object> parameters = new Dictionary <string, object>(); parameters.Add("Username", report.Property("username").Value.ToString()); List <Subscription> sub = new Subscription().SearchDocument(parameters); if (sub.Count <= 0) { StripeConfiguration.SetApiKey("sk_test_p9FWyo0hC9g8y39CkRR1pnYH"); var options = new StripeCustomerCreateOptions { Email = report.Property("email").Value.ToString(), SourceToken = report.Property("id").Value.ToString() }; var service = new StripeCustomerService(); StripeCustomer customer = service.Create(options); DoSub(customer, report); } else { updateSubscription(report); } return(true); }
public StripeCustomer CreateStripeCustomer(string sEmail, string sToken, string sInputDiscountCode) { try { StripeConfiguration.SetApiKey(ConfigurationManager.AppSettings["stripeApi_LiveKey"]); var customerService = new StripeCustomerService(); string sDiscountCode = ConfigurationManager.AppSettings["discount_code"]; var CustomerOptions = new StripeCustomerCreateOptions() { Email = sEmail, Description = "EmediCodes Basic Plan for " + sEmail, AccountBalance = 0, PlanId = "1", SourceToken = sToken, TrialEnd = DateTime.Now + TimeSpan.FromDays(14) }; if (sInputDiscountCode.Equals(sDiscountCode)) { CustomerOptions.CouponId = sDiscountCode; } StripeCustomer customer = customerService.Create(CustomerOptions); return(customer); } catch (Exception ex) { oLogger.LogData("METHOD: CreateStripeCustomer; ERROR: TRUE; EXCEPTION: " + ex.Message + "; INNER EXCEPTION: " + ex.InnerException + "; STACKTRACE: " + ex.StackTrace); throw; } }
// GET: /<controller>/ public CustomersController(IConfiguration config) { // test commit customerService = new StripeCustomerService(); this.client = new StripeClient("sk_test_4eC39HqLyjWDarjtT1zdp7dc"); _config = config; }
public bool CheckCustomerPaymentMethod(string sStripeCustomerId) { try { StripeConfiguration.SetApiKey(ConfigurationManager.AppSettings["stripeApi_LiveKey"]); bool blnPaymentMethodExists = false; var customerService = new StripeCustomerService(); StripeCustomer customer = customerService.Get(sStripeCustomerId); if (!customer.Sources.Any()) { return(blnPaymentMethodExists); } else { blnPaymentMethodExists = true; return(blnPaymentMethodExists); } } catch (Exception ex) { oLogger.LogData("METHOD: CheckCustomerPaymentMethod; ERROR: TRUE; EXCEPTION: " + ex.Message + "; INNER EXCEPTION: " + ex.InnerException + "; STACKTRACE: " + ex.StackTrace); throw; } }
public ActionResult Charge(string stripeEmail, string stripeToken, int amount) { Information($"stripeEmail: {stripeEmail}, stripeToken: {stripeToken}, amount: {amount}"); StripeConfiguration.SetApiKey(MyStripeSettings.SiteName); var customers = new StripeCustomerService(); var charges = new StripeChargeService(); var customer = customers.Create(new StripeCustomerCreateOptions { Email = stripeEmail, SourceToken = stripeToken }); var charge = charges.Create(new StripeChargeCreateOptions { Amount = amount, Description = "Sample Charge", Currency = "usd", CustomerId = customer.Id }); //return View(); Information($"Transaction completed"); return(RedirectToAction("Index")); }
public ActionResult Subscribe(StripeTokenResponse data) { var myCustomer = new StripeCustomerCreateOptions(); myCustomer.Email = User.Identity.Name; myCustomer.SourceToken = data.StripeToken; myCustomer.PlanId = ConfigurationManager.AppSettings["stripe:plan"]; // only if you have a plan myCustomer.TaxPercent = 0; // only if you are passing a plan, this tax percent will be added to the price. Metrics.Info($"Creating subscription for {myCustomer.Email} {myCustomer.SourceToken} {myCustomer.PlanId}"); var customerService = new StripeCustomerService(ConfigurationManager.AppSettings["stripe:token_secret"]); StripeCustomer stripeCustomer = customerService.Create(myCustomer); using (var db = new Email2SmsContext()) { var userId = GetUserId(); var row = db.Subscriptions.FirstOrDefault(f => f.User == userId); if (row == null) { row = new Subscription { User = userId }; db.Subscriptions.Add(row); } row.StripeCustomer = stripeCustomer.Id; row.LastInvoiceUtc = DateTime.UtcNow; db.SaveChanges(); } return(Redirect("~/home/setup")); }