private async Task <PaymentResponse> PayWithCC(CreditCard cc) { PaymentResponse paymentResponse = new PaymentResponse(); try { StripeServices stripe = new StripeServices(); CardValidate ccValidate = stripe.CardToToken(cc).Result; if (!String.IsNullOrEmpty(ccValidate.ccConfirm)) { cc.token = ccValidate.ccConfirm; string strMoneyValue = TotalTextBox.Text; decimal decimalMoneyValue = decimal.Parse(strMoneyValue, NumberStyles.Currency); paymentResponse = await MakeStripePayment(cc, decimalMoneyValue); //paymentResponse = p.Result; paymentResponse.ccConfirm = ccValidate.ccConfirm; } else { paymentResponse.Messages.Add("Stripe", ccValidate.ErrorMessages); } } catch (Exception ex) { //CANNOT save cc data to db Exception ex2 = new Exception("PayWithCC", ex); ((App)App.Current).LogError(ex2.Message, "Card holder name is " + NameOnCardTextBox.Text); } return(paymentResponse); }
public async Task <IActionResult> AccountSubscribeAsync(string tokenId, string planId, string userId) { try { ApplicationUser user = await checkUserExistAsync(userId); if (user != null) { StripeServices ss = new StripeServices(); if (string.IsNullOrWhiteSpace(user.StripeToken)) { string stripeCustomerId = ss.CreateStripeCustomer(tokenId, planId, user); user.StripeToken = stripeCustomerId; await _userManager.UpdateAsync(user); return(Ok()); } else { string stripeCustomerId = ss.SubscribeAccountPlan(planId, user.StripeToken); return(Ok()); } } else { return(BadRequest()); } } catch (Exception e) { return(BadRequest()); } }
public List <StripePlan> GetAllSubscription() { StripeServices ss = new StripeServices(); var allPlans = ss.GetAllPlans().ToList(); foreach (var onePlan in allPlans) { onePlan.StatementDescriptor = _applicationDbContext.SubscriptionModel.Where(t => t.IdToken == onePlan.Id).First().IsActive.ToString(); } return(allPlans); }
public JsonResult ApplyCoupon(String code) { String msg = ""; var custm_id = SessionData.StripeCustId; msg = !string.IsNullOrWhiteSpace(custm_id) ? StripeServices.ApplyPromoCode(custm_id, code.Trim()) : Constant.STRIPE_ID_NOTFOUND; return(new JsonResult() { Data = msg, JsonRequestBehavior = JsonRequestBehavior.AllowGet }); }
public List <StripePlan> GetAllActiveSubscription() { StripeServices ss = new StripeServices(); var allPlans = ss.GetAllPlans().ToList(); var notActivePlans = _applicationDbContext.SubscriptionModel.Where(t => t.IsActive == false).ToList(); foreach (var singleNotActivePlan in notActivePlans) { var sm = allPlans.Where(t => t.Id == singleNotActivePlan.IdToken).First(); allPlans.Remove(sm); } return(allPlans); }
public JsonResult ApplyPromo(String custm_id, String code) { String msg = ""; if (!string.IsNullOrWhiteSpace(custm_id)) { msg = StripeServices.ApplyPromoCode(custm_id, code.Trim()); } else { msg = Constant.STRIPE_ID_NOTFOUND; } return(new JsonResult() { Data = msg, JsonRequestBehavior = JsonRequestBehavior.AllowGet }); }
public async Task <bool> CreateSubscriptionAsync(SubscriptionViewModel svm) { try { StripeServices ss = new StripeServices(); string id = ss.CreateSubscription(svm.price, svm.name, svm.interval.ToLower()); SubscriptionModel sm = new SubscriptionModel(); sm.IdToken = id; sm.IsActive = svm.status; _applicationDbContext.SubscriptionModel.Add(sm); await _applicationDbContext.SaveChangesAsync(); return(true); } catch (Exception e) { return(false); } }
public async Task <IActionResult> Create([FromBody] CreateModel model) { try { await StripeServices.CreateCharge(model.CompanyId, model.Token, model.Amount, model.Email, model.Metadata); } catch (Exception exception) { Logger.LogError(exception, "Caught exception"); return(StatusCode(StatusCodes.Status500InternalServerError, new { status = "error", error = exception.Message })); } return(Ok(new { status = "success" })); }
public bool UpdateSubscription(string planId, string name) { StripeServices ss = new StripeServices(); try { SubscriptionModel sm = _applicationDbContext.SubscriptionModel.Where(t => t.IdToken == planId).First(); if (sm != null) { ss.UpdateSubscription(planId, name); return(true); } else { throw new Exception(); } } catch (Exception e) { return(false); } }
public async Task <StripePlan> GetSubscription(string userId) { try { ApplicationUser user = await checkUserExistAsync(userId); if (user != null) { StripeServices ss = new StripeServices(); string stripeCustomerId = user.StripeToken; return(ss.GetUserPlan(stripeCustomerId)); } else { return(null); } } catch (Exception e) { return(null); } }
public JsonResult PlanSubscription(Int32 planStatus, String nextPlanDate) { string msg = ""; var subscription = false; String CustmId = SessionData.StripeCustId; String CardId = SessionData.StripeCardId; if (!String.IsNullOrWhiteSpace(CustmId)) { DateTime plandate = !String.IsNullOrWhiteSpace(nextPlanDate) ? Convert.ToDateTime(nextPlanDate) : plandate = Convert.ToDateTime("1900-01-01 00:00:00"); if (planStatus == 1 && plandate <= DateTime.Now) { msg = StripeServices.SubscribePlan(CustmId, CardId); } else { subscription = true; } if (subscription || planStatus == 2) { UserPlanData pdata = new UserPlanData(); msg = pdata.UpdatePlanData(SessionData.UserID, planStatus); } if (msg == "") { SessionData.PlanStatus = planStatus; } } else { msg = Constant.STRIPE_ID_NOTFOUND; } return(new JsonResult() { Data = msg, JsonRequestBehavior = JsonRequestBehavior.AllowGet }); }
public async Task <IActionResult> UnsubscribeAccountAsync(string userId) { try { ApplicationUser user = await checkUserExistAsync(userId); if (user != null) { string stripeCustomerId = user.StripeToken; StripeServices ss = new StripeServices(); ss.UnsubscribePlan(stripeCustomerId); return(Ok()); } else { return(BadRequest()); } } catch (Exception e) { return(BadRequest()); } }
//[ValidateAntiForgeryToken] public ActionResult Login(LoginViewModel model, String returnUrl) { String msg = ""; Int32 UserID = 0; DataSet ds; DataTable dt, dtbl; DataRow dr = null, dr1 = null; if (ModelState.IsValid) { String email = model.Email.Trim(); ds = userregistrationData.ValidateEmailAndGetUserinfo(email); if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { dt = ds.Tables[0]; dr = dt.Rows[0]; UserID = Convert.ToInt32(dr["MppUserID"]); msg = userregistrationData.CheckUserLogin(UserID, model.Password); if (msg == "") { dtbl = ds.Tables[1]; dr1 = dtbl.Rows[0]; String CustmId, CardId; SessionData.UserID = UserID; String FirstName = Convert.ToString(dr["FirstName"]); SessionData.LastName = Convert.ToString(dr["LastName"]); String PlanDate = Convert.ToString(dr1["PlanDate"]); DateTime?Today, NextPlanDate = DateTime.MaxValue; Today = DateTime.Now; DateTime StartDate = Convert.ToDateTime(dr["StartDate"]); if (!String.IsNullOrWhiteSpace(PlanDate)) { NextPlanDate = Convert.ToDateTime(PlanDate); } SessionData.StartDate = StartDate.ToString("yyyy/MM/dd hh:mm:ss tt"); SessionData.PlanStatus = Convert.ToInt32(dr["PlanStatus"]); SessionData.PlanID = Convert.ToInt32(dr["PlanID"]); SessionData.FormulaAccess = Convert.ToInt16(dr["IsSetFormula"]); SessionData.TrialEndOn = Convert.ToDateTime(dr["TrailEndDate"]); SessionData.Email = email; SessionData.IsAgreementAccept = Convert.ToInt16(dr["IsAgreementConfirm"]); SessionData.ProfileAccess = Convert.ToInt16(dr["ProfileAccess"]); SessionData.AlertCount = Convert.ToInt32(dr1["total_alerts"]); CustmId = Convert.ToString(dr["stp_custId"]); CardId = Convert.ToString(dr["stp_cardId"]); if (!String.IsNullOrWhiteSpace(CustmId)) { FormsAuthentication.SetAuthCookie(FirstName, false); var custm = StripeHelper.GetStripeCustomer(CustmId); if (!String.IsNullOrWhiteSpace(custm.DefaultSourceId) && String.IsNullOrWhiteSpace(CardId)) { StripeHelper.DeleteCard(custm.DefaultSourceId, CustmId); } SessionData.StripeCardId = CardId; SessionData.StripeCustId = CustmId; if (((SessionData.PlanID == 1 && SessionData.TrialEndOn < Today && !String.IsNullOrWhiteSpace(CardId)) || NextPlanDate < Today) && SessionData.PlanStatus == 1) // When plan was expired { if (String.IsNullOrWhiteSpace(CardId)) { return(RedirectToAction("Plan", "Settings")); } else { msg = StripeServices.SubscribePlan(CustmId, CardId); } if (!String.IsNullOrWhiteSpace(msg)) { TempData["IsValid"] = msg; return(RedirectToAction("Login", "UserAccount")); } } if (SessionData.PlanID != 1) { if (SessionData.PlanStatus == 0) // handles unsubscribed status after trial period { return(RedirectToAction("Plan", "Settings")); } else if (String.IsNullOrWhiteSpace(CardId) && SessionData.PlanStatus == 1) // When CardId was not found and Plan was not trail { return(RedirectToAction("Cards", "Settings")); } } } else { return(View("Error")); } if (Url.IsLocalUrl(returnUrl)) { return(Redirect(returnUrl)); } else { return(RedirectToAction("Dashboard", "Main")); } } } else { msg = "Invalid login attempt!"; } TempData["IsValid"] = msg; return(RedirectToAction("Login", "UserAccount")); } return(View(model)); }
//Billing public ActionResult CreateStripeCustomer(string token) { var email = Session["Email"].ToString(); var subscription = new StripeSubscription(); var customerDetails = new StripeCustomer(); var userInfo = new UpdateUserInfo(); string msg = ""; var cardStatus = 0; DataTable userData; StripeCharge charge = null; try { if (token != null) { var ds = new AccountData().ValidateEmailAndGetUserinfo(email); userData = ds.Tables[0]; var custID = Convert.ToString(userData.Rows[0]["stp_custId"]); if (userData.Rows.Count > 0 && !string.IsNullOrWhiteSpace(custID)) //update { var customerUpdateOptions = new StripeCustomerUpdateOptions { Email = email, Description = Session["FirstName"] + " " + Session["LastName"], SourceToken = token }; //updated customer customerDetails = StripeHelper.UpdateCustomer(custID, customerUpdateOptions); //add a test charge for $1 var makeTestCharge = new StripeChargeCreateOptions { CustomerId = customerDetails.Id, Amount = 100, Currency = "usd", Description = "Card verification charge", SourceTokenOrExistingSourceId = customerDetails.DefaultSourceId }; charge = StripeHelper.MakePayment(makeTestCharge); if (charge != null) { var refund = StripeHelper.RefundCharge(charge.Id); cardStatus = 1; userInfo.CustId = customerDetails.Id; userInfo.CardId = customerDetails.DefaultSourceId; userInfo.UserId = Convert.ToInt32(Session["UserID"]); AccountData.UpdateStripeCardData(userInfo); if ((SessionData.PlanID == 1 && SessionData.TrialEndOn < DateTime.Now) || SessionData.PlanStatus == 0) //When trail was expired || Unsubscribed and adding a card since payments are not succesfull { msg = StripeServices.SubscribePlan(SessionData.StripeCustId, userInfo.CardId); } if (String.IsNullOrWhiteSpace(msg)) { SessionData.PlanStatus = 1; //Default subscription SessionData.StripeCustId = customerDetails.Id; SessionData.StripeCardId = customerDetails.DefaultSourceId; } } else { StripeHelper.DeleteCard(customerDetails.DefaultSourceId, custID); cardStatus = 0; } } customerDetails = StripeHelper.GetStripeCustomer(customerDetails.Id); } var respo = new { Status = cardStatus, Message = msg, CustomerDetails = customerDetails }; return(Json(respo, JsonRequestBehavior.AllowGet)); } catch (Exception ex) { LogFile.WriteLog("CreateCustomer - " + ex.Message.ToString()); return(Json(null, JsonRequestBehavior.AllowGet)); } }
public StripeController(StripeServices stripeServices, ILogger <StripeController> logger) { StripeServices = stripeServices; Logger = logger; }
private void PayWithCC() { Pay.IsEnabled = false; CreditCard cc = new CreditCard() { Cvc = CVV.Text, HolderName = NameOnCard.Text, Numbers = CardNumber.Text, Month = ExpirationMonth.Text, Year = ExpirationYear.Text }; List <string> msgs = cc.VerifyCreditCardInfo(); if (msgs.Count == 0) { try { StripeServices stripe = new StripeServices(); CardValidate ccValidate = stripe.CardToToken(cc).Result; if (!String.IsNullOrEmpty(ccValidate.ccConfirm)) { cc.token = ccValidate.ccConfirm; string strMoneyValue = Total.Text; decimal decimalMoneyValue = decimal.Parse(strMoneyValue, NumberStyles.Currency); PaymentResponse response = MakeStripePayment(cc, decimalMoneyValue); if (response.success) { //what should we do if the card is successfully charged but the payment record isn't saved? bool paymentSaved = SavePaymentRecord(response.StripeChargeId).Result; if (paymentSaved) { PaymentSuccess(); } } else { //add message let them try again? Send email? DisplayAlert("Error", "Payment Unsuccessful", "OK"); Pay.IsEnabled = true; } } else { DisplayAlert("Error", ccValidate.ErrorMessages[0], "OK"); Pay.IsEnabled = true; } } catch (Exception ex) { //CANNOT save cc data to db Exception ex2 = new Exception("PayWithCC", ex); ((App)App.Current).LogError(ex2.Message, "Card holder name is " + NameOnCard.Text); } } else { string errorMsg = String.Empty; foreach (string msg in msgs) { errorMsg += msg + "\n"; } //ErrorMessages.Text = errorMsg; Pay.IsEnabled = true; } }
private void Pay_Clicked(object sender, EventArgs e) { Pay.IsEnabled = false; CreditCard cc = new CreditCard() { Cvc = CVV.Text, HolderName = NameOnCard.Text, Numbers = CardNumber.Text, Month = ExpirationMonth.Text, Year = ExpirationYear.Text }; List <string> msgs = cc.VerifyCreditCardInfo(); if (msgs.Count == 0) { StripeServices stripe = new StripeServices(); CardValidate ccValidate = stripe.CardToToken(cc).Result; if (!String.IsNullOrEmpty(ccValidate.ccConfirm)) { cc.token = ccValidate.ccConfirm; PaymentResponse response = MakeStripePayment(cc, workOrderPayment.WorkOrderPaymentAmount); if (response.success) { //what should we do if the card is successfully charged but the payment record isn't saved? bool paymentSaved = SavePaymentRecord(response.StripeChargeId).Result; if (paymentSaved) { //DisplayAlert("Success", "Payment Successful", "OK").Wait(); //navigate back to WorkOrder and clear all fields PopUntilDestination(typeof(WorkOrderPage)); //Navigation.RemovePage(this); //CCPaymentPage //Task<Page> p = Navigation.PopModalAsync(); //PaymentPage //if (p.Result is ContentPage) //{ // ContentPage cp = p.Result as ContentPage; // if (cp != null) // { // if (cp is WorkOrderPage) // { // //clear fields // ((WorkOrderPage)cp).OnClear(this, null); // } // } //} } } else { //add message let them try again? DisplayAlert("Error", "Payment Unsuccessful", "OK"); Pay.IsEnabled = true; } } else { DisplayAlert("Error", ccValidate.ErrorMessages[0], "OK"); Pay.IsEnabled = true; } } else { string errorMsg = String.Empty; foreach (string msg in msgs) { errorMsg += msg + "\n"; } //ErrorMessages.Text = errorMsg; Pay.IsEnabled = true; } }