protected void btnPay_Click(object sender, EventArgs e) { // submit payment Item itemInfo = ItemDB.getItembyID(Request.QueryString["itemID"]); Member mem = MemberDB.getMemberbyEmail(Session["user"].ToString()); Rental rentInfo = (Rental)Session["rental"]; var myCharge = new StripeChargeCreateOptions(); myCharge.Amount = Convert.ToInt32(rentInfo.RentalFee) * 100; myCharge.Currency = "sgd"; myCharge.SourceCard = new SourceCard() { Number = "4242424242424242", ExpirationYear = 2022, ExpirationMonth = 10, AddressCountry = "SG", // optional AddressLine1 = mem.Address, // optional AddressLine2 = mem.Address, // optional AddressCity = "Singapore", // optional AddressState = "NC", // optional AddressZip = mem.PostalCode.ToString(), // optional Name = mem.Name, // optional Cvc = "1223" // optional }; var chargeService = new StripeChargeService(); StripeCharge stripeCharge = chargeService.Create(myCharge); PaymentPay pay = new PaymentPay(); pay.StripeRefNum = Utility.getRandomizedChar(5, 0); string n = Session["rentalPeriod"].ToString(); string startDate = n.Substring(0, 10); string endDate = n.Substring(n.Length - 10); if (Session["itemExtension"].ToString() == "NotExtension") { rentInfo.DateCreated = DateTime.Now; rentInfo.Deposit = itemInfo.Deposit; rentInfo.PaymentReleaseCode = Utility.getRandomizedChar(6, 0); rentInfo.Item = itemInfo; rentInfo.StartDate = Convert.ToDateTime(startDate); rentInfo.EndDate = Convert.ToDateTime(endDate); rentInfo.Status = "Scheduled"; rentInfo.Payment = PaymentDB.getPaymentbyID(Utility.convertIdentitytoPK("PAY", PaymentDB.addPayment(pay))); rentInfo.Rentee = mem; rentInfo.Unit = "Day"; Response.Redirect("RentalDetails.aspx?rentalID=" + Utility.convertIdentitytoPK("RNT", RentalDB.addRental(rentInfo))); } else { Rental rent = RentalDB.getRentalbyID(Request.QueryString["rentalID"]); Extension ext = new Extension(); ext.ExtensionRentalFee = rentInfo.RentalFee; ext.NewEndDate = Convert.ToDateTime(endDate); ext.NewReturnLocation = rent.ReturnLocation; int paymentID = PaymentDB.addPayment(pay); pay.PaymentID = Utility.convertIdentitytoPK("PAY", paymentID); ext.NewReturnTime = rent.ReturnTime; ext.Payment = pay; ext.Rental = rent; ext.Status = "Granted"; ext.Unit = "Day"; ExtensionDB.addExtension(ext); Response.Redirect("RentalDetails.aspx?rentalID=" + Request.QueryString["rentalID"]); } }
public Payment Charge(string stripeEmail, string stripeToken) { // check for active tokens var db = Common.GetDB(formatikSettings.DbConnection); var existingPayment = db .GetCollection <Payment>("Payments") .Find(Builders <Payment> .Filter.And( Builders <Payment> .Filter.Eq(p => p.Email, stripeEmail.ToLower()), Builders <Payment> .Filter.Gte(p => p.Expires, DateTime.Now))) .Limit(1) .First(); if (existingPayment == null) { 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 = 100, Description = "3 day unlimited Formatik", Currency = "usd", CustomerId = customer.Id }); if (charge != null) { var payment = new Payment() { _id = ObjectId.GenerateNewId(), Email = stripeEmail, Expires = DateTime.Now.AddDays(3), Created = DateTime.Now }; db .GetCollection <Payment>("Payments") .InsertOne(payment); return(payment); } else { return(Payment.GetError(ErrorCode.PaymentError, "Failed to process payment")); } } else { return(new Payment() { _id = existingPayment._id, Expires = existingPayment.Expires, ErrorCode = ErrorCode.DuplicatePayment.ToString(), Error = "Duplicate Payment" }); } }
public async Task <IActionResult> Create(Order frmOrder) { if (ModelState.IsValid) { var user = _identitySvc.Get(HttpContext.User); Order order = frmOrder; order.UserName = user.Email; order.BuyerId = user.Id; var chargeOptions = new StripeChargeCreateOptions() { //required Amount = (int)(order.OrderTotal * 100), Currency = "usd", SourceTokenOrExistingSourceId = order.StripeToken, //optional Description = string.Format("Order Payment {0}", order.UserName), ReceiptEmail = order.UserName, }; var chargeService = new StripeChargeService(); chargeService.ApiKey = _config["StripePrivateKey"]; StripeCharge stripeCharge = null; try { stripeCharge = chargeService.Create(chargeOptions); _logger.LogDebug("Stripe charge object creation" + stripeCharge.StripeResponse.ObjectJson); } catch (StripeException stripeException) { _logger.LogDebug("Stripe exception " + stripeException.Message); ModelState.AddModelError(string.Empty, stripeException.Message); return(View(frmOrder)); } try { if (stripeCharge.Id != null) { //_logger.LogDebug("TransferID :" + stripeCharge.Id); order.PaymentAuthCode = stripeCharge.Id; //_logger.LogDebug("User {userName} started order processing", user.UserName); int orderId = await _orderSvc.CreateOrder(order); //_logger.LogDebug("User {userName} finished order processing of {orderId}.", order.UserName, order.OrderId); await _cartSvc.ClearCart(user); return(RedirectToAction("Complete", new { id = orderId, userName = user.UserName })); } else { ViewData["message"] = "Payment cannot be processed, try again"; return(View(frmOrder)); } } catch (BrokenCircuitException) { ModelState.AddModelError("Error", "It was not possible to create a new order, please try later on. (Business Msg Due to Circuit-Breaker)"); return(View(frmOrder)); } } else { return(View(frmOrder)); } }
public async Task <BillingInfo> GetBillingAsync(ISubscriber subscriber) { var billingInfo = new BillingInfo(); var customerService = new StripeCustomerService(); var subscriptionService = new StripeSubscriptionService(); var chargeService = new StripeChargeService(); var invoiceService = new StripeInvoiceService(); if (!string.IsNullOrWhiteSpace(subscriber.GatewayCustomerId)) { var customer = await customerService.GetAsync(subscriber.GatewayCustomerId); if (customer != null) { if (!string.IsNullOrWhiteSpace(customer.DefaultSourceId) && customer.Sources?.Data != null) { if (customer.DefaultSourceId.StartsWith("card_")) { var source = customer.Sources.Data.FirstOrDefault(s => s.Card?.Id == customer.DefaultSourceId); if (source != null) { billingInfo.PaymentSource = new BillingInfo.BillingSource(source); } } else if (customer.DefaultSourceId.StartsWith("ba_")) { var source = customer.Sources.Data .FirstOrDefault(s => s.BankAccount?.Id == customer.DefaultSourceId); if (source != null) { billingInfo.PaymentSource = new BillingInfo.BillingSource(source); } } } var charges = await chargeService.ListAsync(new StripeChargeListOptions { CustomerId = customer.Id, Limit = 20 }); billingInfo.Charges = charges?.Data?.OrderByDescending(c => c.Created) .Select(c => new BillingInfo.BillingCharge(c)); } } if (!string.IsNullOrWhiteSpace(subscriber.GatewaySubscriptionId)) { var sub = await subscriptionService.GetAsync(subscriber.GatewaySubscriptionId); if (sub != null) { billingInfo.Subscription = new BillingInfo.BillingSubscription(sub); } if (!sub.CanceledAt.HasValue && !string.IsNullOrWhiteSpace(subscriber.GatewayCustomerId)) { try { var upcomingInvoice = await invoiceService.UpcomingAsync(subscriber.GatewayCustomerId); if (upcomingInvoice != null) { billingInfo.UpcomingInvoice = new BillingInfo.BillingInvoice(upcomingInvoice); } } catch (StripeException) { } } } return(billingInfo); }
public async Task <ActionResult> Download(int?id, bool?bought, string stripeId) { Service service = db.Services.Find(id); if (id == null) { return(View("NotFound")); } if (service.Video != null) { if (bought == true && stripeId != null) { int nonNullId = id.Value; string strIpAddress = string.Empty; strIpAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (strIpAddress == "" || strIpAddress == null) { strIpAddress = Request.ServerVariables["REMOTE_ADDR"]; } //Don't record analytics coming from garbage IP addresses if (strIpAddress != "::1") { DownloadAnalytic analyitic = new DownloadAnalytic(); analyitic.IPAddress = strIpAddress; analyitic.ServiceId = nonNullId; service.DownloadAnalytics.Add(analyitic); db.SaveChanges(); await PopulateDownloadAnalyticObject(analyitic); } try { var chargeService = new StripeChargeService(); StripeCharge stripeCharge = chargeService.Get(stripeId); if (stripeCharge.Status == "succeeded") { CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["StorageConnectionString"]); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference("videos"); string userFileName = service.FirstName + "_" + service.LastName + "_Video.mp4"; CloudBlockBlob blob = container.GetBlockBlobReference(service.Video.ConvertedFilePath); SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy() { Permissions = SharedAccessBlobPermissions.Read, SharedAccessExpiryTime = DateTime.Now.AddYears(100) }; SharedAccessBlobHeaders blobHeaders = new SharedAccessBlobHeaders() { ContentDisposition = "attachment; filename=" + userFileName }; string sasToken = blob.GetSharedAccessSignature(policy, blobHeaders); var sasUrl = blob.Uri.AbsoluteUri + sasToken;//This is the URL you will use. It will force the user to download the vi return(Redirect(sasUrl)); } } catch { return(View("NotFound")); } } //publicly exposing URL for now if (Authorize(service) || service.IsSecured != true) { if (service.Video != null) { CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["StorageConnectionString"]); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference("videos"); string userFileName = service.FirstName + "_" + service.LastName + "_Video.mp4"; CloudBlockBlob blob = container.GetBlockBlobReference(service.Video.ConvertedFilePath); SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy() { Permissions = SharedAccessBlobPermissions.Read, SharedAccessExpiryTime = DateTime.Now.AddYears(100) }; SharedAccessBlobHeaders blobHeaders = new SharedAccessBlobHeaders() { ContentDisposition = "attachment; filename=" + userFileName }; string sasToken = blob.GetSharedAccessSignature(policy, blobHeaders); var sasUrl = blob.Uri.AbsoluteUri + sasToken;//This is the URL you will use. It will force the user to download the vi return(Redirect(sasUrl)); } } } return(View("NotFound")); }
public async Task <IActionResult> Create([FromBody] CreateOrderViewModel model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var user = await _db.Users.SingleAsync(x => x.UserName == HttpContext.User.Identity.Name); var order = new Data.Entities.Order { DeliveryAddress = new Data.Entities.Address { FirstName = model.FirstName, LastName = model.LastName, Address1 = model.Address1, Address2 = model.Address2, TownCity = model.TownCity, County = model.County, Postcode = model.Postcode }, Items = model.Items.Select(x => new Data.Entities.OrderItem { ProductId = x.ProductId, ColorId = x.ColorId, StorageId = x.StorageId, Quantity = x.Quantity }).ToList() }; user.Orders.Add(order); await _db.SaveChangesAsync(); var total = await _db.Orders .Where(x => x.Id == order.Id) .Select(x => Convert.ToInt32(x.Items.Sum(i => i.ProductVariant.Price * i.Quantity) * 100)) .SingleAsync(); var charges = new StripeChargeService(); var charge = await charges.CreateAsync(new StripeChargeCreateOptions { Amount = total, Description = $"Order {order.Id} payment", Currency = "USD", SourceTokenOrExistingSourceId = model.StripeToken }); if (string.IsNullOrEmpty(charge.FailureCode)) { order.PaymentStatus = PaymentStatus.Paid; } else { order.PaymentStatus = PaymentStatus.Declined; } await _db.SaveChangesAsync(); return(Ok(new CreateOrderResponseViewModel(order.Id, order.PaymentStatus))); }
public HttpResponseMessage CreateOrder(JObject orderBundle) { //TransactionStatus transactionStatus; // var results = new StudentValidation().Validate(studentViewModel); //if (!results.IsValid) //{ // studentViewModel.Errors = GenerateErrorMessage.Built(results.Errors); // studentViewModel.ErrorType = ErrorTypeEnum.Error.ToString().ToLower(); // studentViewModel.Status = false; // var badResponse = Request.CreateResponse(HttpStatusCode.BadRequest, studentViewModel); // return badResponse; //} //var stundentBo = BuiltStudentBo(studentViewModel); //stundentBo.PaymentMethods = string.Join(",", studentViewModel.SelectedPaymentMethods); //stundentBo.Gender = studentViewModel.SelectedGender; //transactionStatus = _studentService.CreateStudent(stundentBo); int place = 0; try { //quick val check required? //deserial obj var order = BuildOrder(orderBundle); //validate //capacity and such //calculate fees place = 1; Owner owner = db.Owners.Where(o => o.Id == 1).SingleOrDefault(); if (owner == null) { throw new Exception("Owner Setup is Not Configured Correctly"); } //var custDesc = string.Empty; //var partEmail = string.Empty; //var partName = string.Empty; var part = db.Participants.Where(p => p.Id == order.HouseId).FirstOrDefault(); if (part != null) { //custDesc = part.FirstName + " " + part.LastName + "_ord" + order.Id; //partEmail = part.Email; //partName = part.FirstName + " " + part.LastName; } else { throw new Exception("couldn't find that houseId"); } place = 2; //calulate order.CardProcessorFeeInCents = Convert.ToInt32(Math.Round(Convert.ToInt32(order.Amount * 100) * owner.CardProcessorFeePercentPerCharge / 100, 0) + owner.CardProcessorFeeFlatPerChargeInCents); order.LocalFeeInCents = Convert.ToInt32(Math.Round(Convert.ToInt32(order.Amount * 100) * owner.LocalFeePercentOfCharge / 100, 0) + owner.LocalFeeFlatPerChargeInCents); order.LocalApplicationFee = order.LocalFeeInCents - order.CardProcessorFeeInCents; if (order.LocalApplicationFee < 0) { order.LocalApplicationFee = 0; } //} //create stripe service,customer, charge //charge card //var stripeService = new Stripe. //if good //record charege //create order //StripeService stripeService = new StripeService(); //tring customerEmail,string customerDescription, string customerToken, string accessToken, string chargeDescription, decimal chargeAmount, Int32 applicationFee //var stripeCharge = stripeService.CreateCharge(part.Email, part.FirstName + " " + part.LastName, order.Token, owner.AccessToken, owner.Name, order.Amount, order.LocalApplicationFee); // public StripeCharge CreateCharge(string customerEmail,string customerDescription, string customerToken, string accessToken, string chargeDescription, decimal chargeAmount, Int32 applicationFee ) //{ place = 3; var customerOptions = new StripeCustomerCreateOptions { Email = part.Email, //Email, Description = part.FirstName + " " + part.LastName, TokenId = order.Token, }; var stripeCustomerService = new StripeCustomerService(owner.AccessToken); //owner.AccessToken var customer = stripeCustomerService.Create(customerOptions); place = 4; //int err = place / (place - place); var stripeChargeService = new StripeChargeService(owner.AccessToken); //The token returned from the above method var stripeChargeOption = new StripeChargeCreateOptions() { Amount = Convert.ToInt32(order.Amount * 100), Currency = "usd", CustomerId = customer.Id, Description = owner.Name, ApplicationFee = order.LocalApplicationFee }; place = 5; var stripeCharge = stripeChargeService.Create(stripeChargeOption); place = 6; if (string.IsNullOrEmpty(stripeCharge.FailureCode)) { //orderService.CompleteOrder(stripeCharge) order.AuthorizationCode = stripeCharge.Id; //stripeCharge. order.CardNumber = stripeCharge.StripeCard.Last4; order.CardCvcCheck = stripeCharge.StripeCard.CvcCheck; order.CardExpires = stripeCharge.StripeCard.ExpirationMonth + "/" + stripeCharge.StripeCard.ExpirationYear; order.CardFingerprint = stripeCharge.StripeCard.Fingerprint; //order.CardId = stripeCharge.StripeCard.; order.CardName = stripeCharge.StripeCard.Name; order.CardOrigin = stripeCharge.StripeCard.Country; //mjb fixorder.CardType = stripeCharge.StripeCard.Type; order.Voided = false; order.Status = "Complete"; order.OrderStatus = OrderStatus.Completed; //mjb fix order.PaymentType = "credit"; //db.Orders.Add(order); //db.SaveChanges(); place = 7; //not good return reason OrderService _orderService = new OrderService(); var x = _orderService.CreateOrder(order); place = 8; HttpResponseMessage result; if (ConfigurationManager.AppSettings["CustomName"] == "bourbonchase") { //result = new MailController().SendBourbonLotteryConfirm(order.Id); result = new MailController().SendConfirmMail(order.Id); //change back to bourbon chase?? } else { result = new MailController().SendConfirmMail(order.Id); } //HttpResponseMessage result = new MailController().SendTestEmail(); var resp = Request.CreateResponse(HttpStatusCode.OK); //resp.Content = new StringContent(); resp.Content = new StringContent(order.Id.ToString(), Encoding.UTF8, "text/plain"); return(resp); } else { //order.Status = stripeCharge.FailureMessage; //db.SaveChanges(); //return //var badResponse = Request.CreateResponse(HttpStatusCode.ExpectationFailed, stripeCharge); //stripeCharge.FailureCode //return badResponse; var logE = new EventureLog(); logE.Message = "Stripe Exception: " + stripeCharge.FailureMessage + " -- place: " + place + " -- bundle: " + orderBundle; logE.Caller = "Order_ERROR_stripe"; logE.Status = "Warning"; logE.LogDate = System.DateTime.Now.ToLocalTime(); logE.DateCreated = System.DateTime.Now.ToLocalTime(); db.EventureLogs.Add(logE); db.SaveChanges(); var badResp = Request.CreateResponse(HttpStatusCode.BadRequest); badResp.Content = new StringContent(stripeCharge.FailureMessage, Encoding.UTF8, "text/plain"); return(badResp); } } catch (Exception ex) { var logE = new EventureLog(); logE.Message = "Order exception: " + ex.Message + " -- place: " + place + " -- bundle: " + orderBundle; logE.Caller = "Order_ERROR"; logE.Status = "ERROR"; logE.LogDate = System.DateTime.Now.ToLocalTime(); logE.DateCreated = System.DateTime.Now.ToLocalTime(); db.EventureLogs.Add(logE); db.SaveChanges(); //var x = "there was an issue"; //var badResponse = Request.CreateResponse(HttpStatusCode.BadRequest, x.ToString()); //return badResponse; string message = ex.Message; string returnMessage = string.Empty; if (message.Substring(0, 4) == "Your") { returnMessage = ex.Message; } else { returnMessage = "There was problem processing your order. Please Try again."; } var badResp = Request.CreateResponse(HttpStatusCode.BadRequest); //resp.Content = new StringContent(); badResp.Content = new StringContent(returnMessage, Encoding.UTF8, "text/plain"); return(badResp); } //if (transactionStatus.Status == false) //{ // var badResponse = Request.CreateResponse(HttpStatusCode.BadRequest, JsonConvert.SerializeObject(studentViewModel)); // return badResponse; //} //else //{ // transactionStatus.ErrorType = ErrorTypeEnum.Success.ToString(); // transactionStatus.ReturnMessage.Add("Record successfully inserted to database"); // var badResponse = Request.CreateResponse(HttpStatusCode.Created, transactionStatus); // return badResponse; //} }
public StripeCharge GetCustomerPayment(string paymentId) { var chargeService = new StripeChargeService(); return(chargeService.Get(paymentId)); }
public ActionResult Charge(string stripeEmail, string stripeToken) { // TODO Make less dependent on Stripe // Gets the total price var totalPrice = GetTotalPriceFromCookieCart(); int priceInCents = (int)(totalPrice * 100); // Gets the information about the customers from Stripe var customers = new StripeCustomerService(); var customer = customers.Create(new StripeCustomerCreateOptions { Email = stripeEmail, SourceToken = stripeToken }); // Gets the information about the charges made from Stripe var charges = new StripeChargeService(); var charge = charges.Create(new StripeChargeCreateOptions { Amount = priceInCents,//charge in cents Description = "Sample Charge", Currency = "eur", CustomerId = customer.Id }); if (charge.Paid) { // TODO ERROR // Gets the deliveryOption from the cookie Delivery deliveryOption = Newtonsoft.Json.JsonConvert.DeserializeObject <Delivery>(Request.Cookies[ConstVal.cookieDeliverOptionName].Value); IncomingOrder order; if (deliveryOption.OtherAddress) { // If the client wants to use another address // Get the client ID int clientID = int.Parse(RudycommerceLib.Security.Encryption.DecryptString(Request.Cookies[ConstVal.cookieClientIDName].Value)); // Pass the inserted deliveryOption to the incoming order order = new IncomingOrder(deliveryOption) { ClientID = clientID }; } else { // If the client wants to use his home address for delivery // Gets the client var client = _client; // Adds the client with his address to the incoming order order = new IncomingOrder(client) { ClientID = client.ID }; } // Gives a status code 0 ( = Ordered, but not yet picked) order.StatusCode = 0; // Adds a paymentComplete, paymentOption and totalprice order.PaymentComplete = true; order.PaymentOption = charge.Source.Card.Brand; order.TotalPrice = totalPrice; // Gets the products from the cart cookie and adds them as order lines) var cart = GetCartFromCookie(); foreach (var item in cart.ProductList) { order.IncomingOrderLines.Add(new IncomingOrderLines { ProductID = item.ID, ProductQuantity = item.Quantity, ProductUnitPrice = item.Price / 100 }); } // Creates the order and saves it _incOrderRepo.Add(order); _incOrderRepo.SaveChangesAsync(); try { string productsString = ""; foreach (var prod in cart.ProductList) { productsString += prod.Quantity.ToString() + " x " + prod.Name + "\r\n"; } string title = Resources.Checkout.OrderEmailTitle; string content = string.Format(Resources.Checkout.OrderEmailContent, _client.FullName, productsString, deliveryOption.StreetAndNumber, deliveryOption.MailBox, deliveryOption.PostalCode, deliveryOption.City); GmailNotifier gmail = new GmailNotifier(); gmail.Notify(new System.Net.Mail.MailAddress(_client.Email), title, content); } catch (EmailSentFailed) { } catch (Exception) { throw; } // Redirects to the Thank you page return(RedirectToAction("OrderFinished", "Orders", null)); } else { // If the payment failed, send back to the payment page return(Payment()); } }
public ActionResult verifyPayments() { try { var getStripes = (from s in db.stripes join p in db.properties on s.PropertyID equals p.PropertyID join c in db.companies on p.CompanyID equals c.CompanyID where c.Active == 1 select s).ToList(); foreach (var stripe in getStripes) { // Villa Nueva for test StripeConfiguration.SetApiKey(stripe.SecretKey); // Get Payments for a month date range DateTime today = DateTime.Now; var chargeService = new StripeChargeService(); StripeList <StripeCharge> chargeItems = chargeService.List( new StripeChargeListOptions() { Limit = 1000, Created = new StripeDateFilter { GreaterThanOrEqual = today.AddMonths(-1), LessThanOrEqual = today } } ); foreach (var item in chargeItems) { if (item.Refunded) { // Remove it from tenant ledger if there int tenantID = 0; if (!string.IsNullOrEmpty(item.CustomerId)) { var getStripeCustomer = db.stripe_customer.Where(x => x.StripeCustomer == item.CustomerId).FirstOrDefault(); if (getStripeCustomer != null) { tenantID = (int)getStripeCustomer.TenantID; } } else { TenantModel tm = new TenantModel(); tenantID = tm.getTenantID(item.Description); } double amount = (double)item.Amount / 100; SourceType source = item.Source.Type; if (source.ToString() == "Card") { amount = (amount - 0.3) * 0.971; } else { double achAmount = amount * 0.008; if (achAmount > 5) { amount -= 5; } else { amount -= achAmount; } } amount = Math.Round(amount, 2); Decimal paidAmount = (decimal)amount; var getTenantTransaction = (from tt in db.tenanttransactions where tt.TenantID == tenantID && tt.TenantTransactionDate == item.Created.Date && tt.TransactionAmount == paidAmount && (tt.Comment == "Tenant Payment - Online ACH Payment" || tt.Comment == "Tenant Payment - Online Tenant Credit Card Payment" || tt.Comment == "Tenant Payment via ACH" || tt.Comment == "Tenant Payment via Credit Card") select tt).FirstOrDefault(); if (getTenantTransaction != null) { Decimal transactionAmount = getTenantTransaction.TransactionAmount; // Send PM Email var getTenant = db.tenants.Where(x => x.TenantID == tenantID).FirstOrDefault(); var getUnit = db.units.Find(getTenant.UnitID); Email email = new Email(); string ToEmail = ""; ToEmail = email.getPropertyManagerEmail((int)getTenant.PropertyID); if (string.IsNullOrEmpty(ToEmail)) { ToEmail = email.getAdminEmail((int)getTenant.PropertyID); } string emailBody = "The payment of " + string.Format("{0:C}", transactionAmount) + " made on " + item.Created.Date.ToString("MM/dd/yyyy") + " was deleted from "; emailBody += "tenant: " + getTenant.TenantFName + " " + getTenant.TenantLName + ". Unit: " + getUnit.UnitName + ".\n\n"; emailBody += "Reason: Refunded"; string subject = "Tenant Payment Refunded"; int checkRegisterID = getTenantTransaction.CheckRegisterID; var getCR = db.checkregisters.Find(checkRegisterID); if (getCR != null) { db.checkregisters.Remove(getCR); } db.tenanttransactions.Remove(getTenantTransaction); db.SaveChanges(); email.sendEmail(ToEmail, "*****@*****.**", subject, emailBody); } } } } SendUsEmail emailOK = new SendUsEmail(); emailOK.sendAlert("Just run Verify payments", "Verify Payments"); return(new HttpStatusCodeResult(HttpStatusCode.OK)); } catch (Exception any) { SendUsEmail email = new SendUsEmail(); email.sendError(any.ToString(), "Error Verify Refunded Payments"); return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } }
public async Task <ActionResult> Payment(int id, string stripeToken, string stripeEmail) { var selectQuery = await _orderService.Query(x => x.ID == id).Include(x => x.Listing).SelectAsync(); // Check if order exists var order = selectQuery.FirstOrDefault(); if (order == null) { return(new HttpNotFoundResult()); } var stripeConnectQuery = await _stripConnectService.Query(x => x.UserID == order.UserProvider).SelectAsync(); var stripeConnect = stripeConnectQuery.FirstOrDefault(); if (stripeConnect == null) { return(new HttpNotFoundResult()); } //https://stripe.com/docs/checkout var charge = new StripeChargeCreateOptions(); // always set these properties charge.Amount = order.PriceInCents; charge.Currency = CacheHelper.Settings.Currency; charge.Source = new StripeSourceOptions() { TokenId = stripeToken }; // set booking fee var bookingFee = (int)Math.Round(CacheHelper.Settings.TransactionFeePercent * order.PriceInCents); if (bookingFee < CacheHelper.Settings.TransactionMinimumFee * 100) { bookingFee = (int)(CacheHelper.Settings.TransactionMinimumFee * 100); } charge.ApplicationFee = bookingFee; charge.Capture = false; charge.Description = order.Description; charge.Destination = stripeConnect.stripe_user_id; var chargeService = new StripeChargeService(CacheHelper.GetSettingDictionary("StripeApiKey").Value); StripeCharge stripeCharge = chargeService.Create(charge); // Update order status order.Status = (int)Enum_OrderStatus.Pending; order.PaymentPlugin = StripePlugin.PluginName; _orderService.Update(order); // Save transaction var transaction = new StripeTransaction() { OrderID = id, ChargeID = stripeCharge.Id, StripeEmail = stripeEmail, StripeToken = stripeToken, Created = DateTime.Now, LastUpdated = DateTime.Now, FailureCode = stripeCharge.FailureCode, FailureMessage = stripeCharge.FailureMessage, ObjectState = Repository.Pattern.Infrastructure.ObjectState.Added }; _transactionService.Insert(transaction); await _unitOfWorkAsync.SaveChangesAsync(); await _unitOfWorkAsyncStripe.SaveChangesAsync(); ClearCache(); // Payment succeeded if (string.IsNullOrEmpty(stripeCharge.FailureCode)) { // Send message to the user var message = new MessageSendModel() { UserFrom = order.UserReceiver, UserTo = order.UserProvider, Subject = order.Listing.Title, ListingID = order.ListingID, Body = HttpContext.ParseAndTranslate(string.Format( "[[[Order Requested - %0 - Total Price %1 %2. <a href=\"%3\">See Details</a>|||{0}|||{1}|||{2}|||{3}]]]", order.Description, order.Price, order.Currency, Url.Action("Orders", "Payment"))) }; await MessageHelper.SendMessage(message); TempData[TempDataKeys.UserMessage] = "[[[Thanks for your order! You payment will not be charged until the provider accepted your request.]]]"; return(RedirectToAction("Orders", "Payment")); } else { TempData[TempDataKeys.UserMessageAlertState] = "bg-danger"; TempData[TempDataKeys.UserMessage] = stripeCharge.FailureMessage; return(RedirectToAction("Payment")); } }
/// <summary> /// As long as payments continue the users account will not expire /// </summary> private void CheckForNewPayments() { // retrieve all events for the past day and proceed to process // subscription cancellations. using (var db = InitializeSettings.DbFactory) { var data = db.Query <Majorsilence.Vpn.Poco.DatabaseInfo>("SELECT * FROM DatabaseInfo"); if (data.Count() != 1) { throw new Majorsilence.Vpn.Logic.Exceptions.InvalidDataException("Incorrect data in DatabaseInfo table. To many or too few rows."); } Helpers.SslSecurity.Callback(); var eventService = new StripeChargeService(Majorsilence.Vpn.Logic.Helpers.SiteInfo.StripeAPISecretKey); var options = new StripeChargeListOptions() { Limit = 1000, Created = new StripeDateFilter { GreaterThanOrEqual = data.First().LastDailyProcess } }; IEnumerable <StripeCharge> response = eventService.List(options); foreach (var evt in response) { //if (evt.LiveMode == false) //{ // continue; //} // A new payment has been made. string stripeCustomerId = evt.CustomerId; //var users = db.Select<Majorsilence.Vpn.Poco.Users>(q => q.PaymentExpired == false); var user = db.Query <Majorsilence.Vpn.Poco.Users>("SELECT * FROM Users WHERE StripeCustomerAccount=@StripeCustomerAccount", new { StripeCustomerAccount = stripeCustomerId }); if (user == null || user.Count() != 1) { var ex = new Majorsilence.Vpn.Logic.Exceptions.InvalidDataException("Cannot find stripe customer data in users table. Stripe Customer Account: " + stripeCustomerId); Majorsilence.Vpn.Logic.Helpers.Logging.Log(ex); InitializeSettings.Email.SendMail_BackgroundThread("Error running DailyProcessing: " + ex.Message, "Error running DailyProcessing", Majorsilence.Vpn.Logic.Helpers.SiteInfo.AdminEmail, true, null, Email.EmailTemplates.Generic); continue; } int userid = user.First().Id; var pay = new Payments.Payment(userid); // amount in cents pay.SaveUserPayment((decimal)(evt.Amount / 100.0m), evt.Created, Helpers.SiteInfo.MonthlyPaymentId); Majorsilence.Vpn.Logic.ActionLog.Log_BackgroundThread("Payment made", userid); } data.First().LastDailyProcess = DateTime.UtcNow; db.Update(data.First()); } }
public ActionResult SignUp(SignUpViewModel viewModel, string stripeEmail, string stripeToken) { if (!string.IsNullOrEmpty(stripeEmail) && !string.IsNullOrEmpty(stripeToken)) { var customers = new StripeCustomerService(); var charges = new StripeChargeService(); if (viewModel.Price == 0) { viewModel.Price = 15000; } var customer = customers.Create(new StripeCustomerCreateOptions { Email = stripeEmail, SourceToken = stripeToken }); var charge = charges.Create(new StripeChargeCreateOptions { Amount = viewModel.Price,//charge in cents Description = "MWS - Funeral Webcasting", Currency = "usd", CustomerId = customer.Id }); ViewBag.IsCharged = true; viewModel.IsCharged = true; return(View(viewModel)); } ViewBag.IsCharged = false; var funeralHome = new FuneralHome() { City = viewModel.City, ZipCode = viewModel.ZipCode, Email = viewModel.Email, UserName = viewModel.UserName, OwnerId = 1, PaymentStatus = PaymentStatus.HasPaid, Name = viewModel.Name, DevHome = true, State = viewModel.State }; if (db.Users.Count(u => u.UserName == viewModel.UserName) > 1) { ViewBag.ErrorText = "Login name already in use"; return(View(viewModel)); } if (ModelState.IsValid) { var fhh = new FuneralHomeHelper(); var fhresult = fhh.CreateFuneralHome(funeralHome, viewModel.Email, WebsiteProvider.GenericIframe, viewModel.Password); if (fhresult.Success == true) { var user = UserManager.Find(viewModel.UserName, viewModel.Password); SignInAsync(user, false); this.Session.Add("UserId", user.Id.ToString()); Email.sendWelcomeEmail(funeralHome); return(RedirectToAction("Index", "Services")); } else { Error.ReportError(ErrorSeverity.Fatal, "AccountController", "SignUp", "204"); ViewBag.ErrorText = fhresult.UserErrors; } } return(View(viewModel)); }
public int Add(AddSubscriptionBookingParams param) { try { using (var transaction = new TransactionScope()) { var bookingCode = Helper.RandomString(Constant.BookingCodeLength); while (IsBookingCodeExists(bookingCode)) { bookingCode = Helper.RandomString(Constant.BookingCodeLength); } param.SubscriptionBookingsObject.BookingCode = bookingCode; // Insert New Bookings DayaxeDbContext.SubscriptionBookings.InsertOnSubmit(param.SubscriptionBookingsObject); Commit(); if (param.SubscriptionBookingDiscounts != null && param.SubscriptionBookingDiscounts.Id > 0) { var subscriptionDiscount = new SubscriptionBookingDiscounts { DiscountId = param.SubscriptionBookingDiscounts.Id, SubscriptionBookingId = param.SubscriptionBookingsObject.Id, SubscriptionId = param.SubscriptionBookingsObject.SubscriptionId }; DayaxeDbContext.SubscriptionBookingDiscounts.InsertOnSubmit(subscriptionDiscount); } // Insert to History for First Cycle var cycle = new SubscriptionCycles { SubscriptionBookingId = param.SubscriptionBookingsObject.Id, StartDate = param.SubscriptionBookingsObject.StartDate, EndDate = param.SubscriptionBookingsObject.EndDate, CancelDate = param.SubscriptionBookingsObject.CancelDate, LastUpdatedBy = param.SubscriptionBookingsObject.LastUpdatedBy, LastUpdatedDate = param.SubscriptionBookingsObject.LastUpdatedDate, Status = param.SubscriptionBookingsObject.Status, Price = param.ActualPrice, MerchantPrice = param.MerchantPrice, PayByCredit = param.PayByCredit, TotalPrice = param.TotalPrice, Quantity = param.SubscriptionBookingsObject.Quantity, StripeChargeId = string.Empty, StripeCouponId = param.SubscriptionBookingsObject.StripeCouponId, StripeInvoiceId = string.Empty, CycleNumber = 1 }; DayaxeDbContext.SubscriptionCycles.InsertOnSubmit(cycle); // Insert Discount for Current Customer active Subscription var discount = new Discounts { DiscountName = string.Format("{0} - {1} {2}", param.SubscriptionName, param.FirstName, param.LastName), Code = string.Format("SUP{0}", Helper.RandomString(8)), StartDate = param.SubscriptionBookingsObject.StartDate, EndDate = param.SubscriptionBookingsObject.EndDate, CodeRequired = true, PercentOff = 100, PromoType = (byte)Enums.PromoType.SubscriptionPromo, MinAmount = 0, IsAllProducts = true, MaxPurchases = (byte)param.MaxPurchases }; DayaxeDbContext.Discounts.InsertOnSubmit(discount); Commit(); // Add Invoices var subscriptionInvoice = new SubscriptionInvoices { SubscriptionCyclesId = cycle.Id, BookingStatus = cycle.Status, Quantity = cycle.Quantity, Price = cycle.Price, MerchantPrice = cycle.MerchantPrice, PayByCredit = cycle.PayByCredit, TotalPrice = cycle.TotalPrice, InvoiceStatus = (int)Enums.InvoiceStatus.Charge, StripeChargeId = cycle.StripeChargeId, ChargeAmount = cycle.Price, StripeRefundId = string.Empty, RefundAmount = 0, RefundCreditAmount = 0, StripeCouponId = cycle.StripeCouponId, CreatedDate = DateTime.UtcNow, CreatedBy = 1 }; DayaxeDbContext.SubscriptionInvoices.InsertOnSubmit(subscriptionInvoice); var discountUsed = new SubsciptionDiscountUseds { CustomerId = param.SubscriptionBookingsObject.CustomerId, DiscountId = discount.Id, SubscriptionBookingId = param.SubscriptionBookingsObject.Id }; DayaxeDbContext.SubsciptionDiscountUseds.InsertOnSubmit(discountUsed); var cusCredits = DayaxeDbContext.CustomerCredits .SingleOrDefault(cc => cc.CustomerId == param.CustomerCreditsObject.CustomerId); // Add Logs when refund by Upgrade to Subscription if (param.RefundCreditByUpgrade > 0) { var creditLogs = new CustomerCreditLogs { Amount = param.RefundCreditByUpgrade, ProductId = 0, BookingId = 0, SubscriptionId = param.SubscriptionBookingsObject.SubscriptionId, CreatedBy = param.CustomerCreditsObject.CustomerId, CreatedDate = DateTime.UtcNow, CreditType = (byte)Enums.CreditType.PartialPuchaseRefund, Description = param.RefundCreditDescription, CustomerId = param.CustomerCreditsObject.CustomerId, ReferralId = param.CustomerCreditsObject.ReferralCustomerId, SubscriptionBookingId = param.SubscriptionBookingsObject.Id, Status = true, GiftCardId = 0 }; DayaxeDbContext.CustomerCreditLogs.InsertOnSubmit(creditLogs); if (cusCredits != null) { cusCredits.Amount += param.RefundCreditByUpgrade; } } // Add Logs when pay by DayAxe Credit if (param.PayByCredit > 0) { var creditLogs = new CustomerCreditLogs { Amount = param.PayByCredit, ProductId = 0, BookingId = 0, SubscriptionId = param.SubscriptionBookingsObject.SubscriptionId, CreatedBy = param.CustomerCreditsObject.CustomerId, CreatedDate = DateTime.UtcNow, CreditType = (byte)Enums.CreditType.Charge, Description = param.Description, CustomerId = param.CustomerCreditsObject.CustomerId, ReferralId = param.CustomerCreditsObject.ReferralCustomerId, SubscriptionBookingId = param.SubscriptionBookingsObject.Id, Status = true, GiftCardId = 0 }; DayaxeDbContext.CustomerCreditLogs.InsertOnSubmit(creditLogs); if (cusCredits != null) { cusCredits.Amount -= param.PayByCredit; } } // First Buy of referral if (param.CustomerCreditsObject != null && param.CustomerCreditsObject.ReferralCustomerId > 0 && ( DayaxeDbContext.Bookings.Count(x => x.CustomerId == param.SubscriptionBookingsObject.CustomerId) == 1 || DayaxeDbContext.SubscriptionBookings.Count(x => x.CustomerId == param.SubscriptionBookingsObject.CustomerId) == 1)) { var logs = DayaxeDbContext.CustomerCreditLogs .Where(ccl => ccl.CustomerId == param.CustomerCreditsObject.ReferralCustomerId && ccl.ReferralId == param.SubscriptionBookingsObject.CustomerId && !ccl.Status) .ToList(); if (logs.Any()) { logs.ForEach(log => { var cus = DayaxeDbContext.CustomerCredits .FirstOrDefault(cc => cc.CustomerId == log.CustomerId); if (cus != null) { cus.Amount += log.Amount; } log.Status = true; }); Commit(); } } // Add to Customer Credit Log var logsReferred = DayaxeDbContext.CustomerCreditLogs .Where(ccl => ccl.ReferralId == param.SubscriptionBookingsObject.CustomerId && !ccl.Status) .ToList(); if (logsReferred.Any()) { logsReferred.ForEach(log => { var cus = DayaxeDbContext.CustomerCredits .FirstOrDefault(cc => cc.CustomerId == log.CustomerId); if (cus != null) { cus.Amount += log.Amount; } log.Status = true; }); } // Insert Schedule var schedules = new Schedules { ScheduleSendType = (int)Enums.ScheduleSendType.IsEmailConfirmSubscription, Name = "Send Email confirm Subscription", Status = (int)Enums.ScheduleType.NotRun, SubscriptionBookingId = param.SubscriptionBookingsObject.Id }; DayaxeDbContext.Schedules.InsertOnSubmit(schedules); // Maybe not use here because flow upgrade to subscription do not use this if (param.BookingId > 0) { var bookings = DayaxeDbContext.Bookings.FirstOrDefault(b => b.BookingId == param.BookingId); if (bookings != null) { var chargePrice = (int)((bookings.TotalPrice - bookings.HotelPrice) * 100); try { bookings.TotalPrice -= bookings.HotelPrice; bookings.PassStatus = (int)Enums.BookingStatus.Active; var discounts = new DiscountBookings { DiscountId = discount.Id, ProductId = bookings.ProductId, BookingId = bookings.BookingId }; DayaxeDbContext.DiscountBookings.InsertOnSubmit(discounts); bookings.IsActiveSubscription = true; string responseString; if (chargePrice > 0) { var chargeService = new StripeChargeService(); StripeCharge charge = chargeService.Capture(bookings.StripeChargeId, chargePrice); responseString = charge.StripeResponse.ResponseJson; } else { var refundOptions = new StripeRefundCreateOptions { Reason = StripeRefundReasons.RequestedByCustomer }; var refundService = new StripeRefundService(); StripeRefund refund = refundService.Create(bookings.StripeChargeId, refundOptions); responseString = refund.StripeResponse.ResponseJson; } var logs = new Logs { LogKey = "UpgradeSubscriptionCharge", UpdatedContent = string.Format("Params: {0} - Response: {1}", JsonConvert.SerializeObject(param, CustomSettings.SerializerSettings()), responseString), UpdatedBy = param.SubscriptionBookingsObject.CustomerId, UpdatedDate = DateTime.UtcNow }; AddLog(logs); } catch (Exception ex) { var logs = new Logs { LogKey = "UpgradeSubscriptionChargeError", UpdatedContent = string.Format("Params: {0} - {1} - {2} - {3}", JsonConvert.SerializeObject(param, CustomSettings.SerializerSettings()), ex.Message, ex.StackTrace, ex.Source), UpdatedBy = param.SubscriptionBookingsObject.CustomerId, UpdatedDate = DateTime.UtcNow }; AddLog(logs); } } } Commit(); transaction.Complete(); } } catch (Exception ex) { var logs = new Logs { LogKey = "AddBookingError", UpdatedContent = string.Format("{0} - {1} - {2} - {3}", param.SubscriptionBookingsObject.CustomerId, ex.Message, ex.StackTrace, ex.Source), UpdatedBy = param.SubscriptionBookingsObject.CustomerId, UpdatedDate = DateTime.UtcNow }; AddLog(logs); throw new Exception(ex.Message, ex); } return(param.SubscriptionBookingsObject.Id); }
public string CreditCardPayment(string stripeEmail, string stripeToken, int?PGID, long UserID) { using (var Tran = db.Database.BeginTransaction()) { var pkgdetail = db.Packages.FirstOrDefault(x => x.Id == PGID); if (pkgdetail == null) { throw new ArgumentNullException(); } try { var customers = new StripeCustomerService(); var charges = new StripeChargeService(); var customer = customers.Create(new StripeCustomerCreateOptions { Email = stripeEmail, SourceToken = stripeToken }); var PaymentDue = Convert.ToInt32(pkgdetail.YearlyPlanPrices * 100); var charge = charges.Create(new StripeChargeCreateOptions { Amount = PaymentDue, //charge in cents Description = "OolaData Package: " + pkgdetail.Name, Currency = "usd", CustomerId = customer.Id }); db.StripPayments.Add(new StripPayment() { PaymentStatus = charge.Status, Email = stripeEmail, InvoiceID = DateTime.Now.ToString("ddmmyy") + UserID, CustomerID = customer.Id, CreatedDateTime = DateTime.UtcNow, StripeToken = stripeToken }); db.SaveChanges(); if (charge.Status == "succeeded") { db.UserSubscriptions.Add(new UserSubscription() { UserID = UserID, PackageID = PGID, PaymentMethod = (int)PaymentMethod.Strip, ExpireDate = DateTime.UtcNow.AddYears(1), PlanRegistrationDate = DateTime.UtcNow, IsActive = true }); } else { db.UserSubscriptions.Add(new UserSubscription() { UserID = UserID, PackageID = PGID, PaymentMethod = (int)PaymentMethod.Strip, ExpireDate = DateTime.UtcNow.AddYears(1), PlanRegistrationDate = DateTime.UtcNow, IsActive = false }); } db.SaveChanges(); Tran.Commit(); return(charge.Status); } catch (Exception er) { Tran.Rollback(); } return("failed"); } }
public ActionResult CompleteRegistration(Student model) { Context db = new Context(); //JavaScriptSerializer jss = new JavaScriptSerializer(); //Student model = jss.Deserialize<Student>(st); string subdomain = Request.Url.Host.Split(new char[] { '.' })[0]; EnrollSetting seting = db.EnrolSetting.Where(x => x.SiteName == subdomain).FirstOrDefault(); try { if (model.PaymentType == 2) { var mycharge = new StripeChargeCreateOptions(); mycharge.Amount = (int)((model.TotalClassPrice - model.DiscountPrice) * 100); int paymentAmount = (int)((model.TotalClassPrice - model.DiscountPrice) * 100); mycharge.Currency = "USD"; mycharge.SourceCard = new SourceCard() { Number = model.CardNo, ExpirationYear = Convert.ToInt32(model.ExpirationYear), ExpirationMonth = Convert.ToInt32(model.ExpirationMonth), AddressCountry = "US", AddressLine1 = model.MailingAddress1, AddressLine2 = model.MailingAddress2, AddressCity = model.MailingCity, AddressState = model.MailingState, AddressZip = model.MailingZip, Name = model.LastName + " " + model.FirstName + " (" + model.Email + ")", Cvc = model.SecurityCode }; mycharge.Description = "Payment received from student registration"; mycharge.Capture = true; //mycharge.CustomerId = current.Id; string key = seting.StripeLiveSecretKey; //"sk_test_2LVKznWm1WA4kvWngmGaPdLx"; var chargeservice = new StripeChargeService(key); StripeCharge currentcharge = chargeservice.Create(mycharge); //StripeCustomer current = GetCustomer(); if (currentcharge.Status == "succeeded" && currentcharge.Paid == true) { int StudentID = SaveRegistration(model); StudentPayment payment = new StudentPayment(); payment.PaymentID = 0; payment.PaymentDate = DateTime.Now; payment.TransactionID = currentcharge.Id; payment.type = "Credit Card"; payment.StudentID = StudentID; payment.Detail = ""; payment.Amount = (model.TotalClassPrice - model.DiscountPrice); db.StudentPayment.Add(payment); db.SaveChanges(); Utilities.AssignKeycodesToCourseAddons(model.SelectedOptions, model.FirstName, model.LastName, model.Email, model.ClassID, StudentID); Utilities.SendClassRegistrationConfirmationToStudent(model); return(RedirectToAction("RegistrationConfirmed", new { id = StudentID })); } else { FlashMessage.Warning("Credit Card Transaction Fail"); return(RedirectToAction("RegistrationError")); } } else { int StudentID = SaveRegistration(model); //SendRegistrationConfirmationToStudent(model); return(RedirectToAction("RegistrationConfirmed", new { id = StudentID })); } } catch (Exception ex) { FlashMessage.Warning(ex.Message); return(RedirectToAction("RegistrationError")); } }
public IActionResult ChargeCard([Bind("number", "expMonth", "expYear", "CCV")] CreditCard creditCard) { StripeConfiguration.SetApiKey("sk_test_LYk237i5xPRlstCABBIWqDsb00eWmKk85w"); if (!ModelState.IsValid) { return(View(creditCard)); } var tokenServices = new StripeTokenCreateOptions { Card = new StripeCreditCardOptions { Number = creditCard.number, ExpirationMonth = creditCard.expMonth, ExpirationYear = creditCard.expYear, Cvc = creditCard.CCV } }; StripeTokenService service = new StripeTokenService(); try { //StripeToken token = service.Create(tokenServices); // double totalPrice = double.Parse(ViewData["totalPrice"].ToString()); // int totalPriceInt = (int)(100 * totalPrice); String username = HttpContext.Session.GetString("Username"); if (!String.IsNullOrEmpty(username)) { ViewData["Username"] = username; } SQLFunction functions = HttpContext.RequestServices.GetService(typeof(SQLFunction)) as SQLFunction; String listString = functions.GetUserCart(username); String[] listArray = listString.Split(","); double totalPrice = 0.0; List <Food> allFood = new List <Food>(); foreach (String s in listArray) { if (!String.IsNullOrEmpty(s)) { allFood.Add(functions.RetriveCart(s)); totalPrice += allFood.ElementAt(allFood.Count() - 1).Price; } } TempData["totalPrice"] = totalPrice; int totalPriceInt = (int)(100 * totalPrice); var chargeOption = new StripeChargeCreateOptions { Amount = totalPriceInt, Currency = "usd", Description = "Description", SourceTokenOrExistingSourceId = "tok_amex" }; StripeChargeService chargeService = new StripeChargeService(); StripeCharge charge = chargeService.Create(chargeOption); }catch (StripeException e) { ViewData["CardError"] = e.Message; } return(View("Index")); }
//The top up method that will validate the user payment public async void onTopUpClick(int amount) { //Creating indicator object var topUpDialog = ProgressDialog.Show(this, "Please wait...", "Validating your payment...", true); try { var amountText = FindViewById <EditText>(Resource.Id.input_amount); // Use Stripe's library to make request StripeConfiguration.SetApiKey("sk_test_Ep5V2ffFq69TP6cDSEf71fr2"); var chargeOptions = new StripeChargeCreateOptions() { Amount = amount, Currency = "usd", Description = "Top Up", SourceTokenOrExistingSourceId = "tok_amex" // obtained with Stripe.js }; //Creating charge service object that will validate the banking card var chargeService = new StripeChargeService(); StripeCharge charge = chargeService.Create(chargeOptions); if (charge.Paid) { //Initializing the user table IMobileServiceTable <Wallet> walletTable = client.GetTable <Wallet>(); //Getting the Wallet details from the Database List <Wallet> currentBalance = await walletTable.Where (item => item.Email == client.CurrentUser.UserId).ToListAsync(); //Checking if the user has a wallet already if (currentBalance.Count > 0) { wallet = currentBalance[0]; //Adding the top up to the previous wallet balance wallet.Balance = Convert.ToString(Convert.ToInt32(wallet.Balance) + Convert.ToInt32(amountText.Text)); //Creating important extra parameters for the backend request var extraParameters = new Dictionary <string, string>(); extraParameters.Add("userId", user.Id); extraParameters.Add("type", "topUp"); extraParameters.Add("parkingId", "1"); //Sending update wallet request to the backend await walletTable.UpdateAsync(wallet, extraParameters); //Showing success message Android.App.AlertDialog.Builder alertSuccess = new Android.App.AlertDialog.Builder(this); alertSuccess.SetTitle("Top Up"); alertSuccess.SetMessage("Top is successful"); alertSuccess.SetPositiveButton("Ok", (senderAlertSucces, argsSuccess) => { Intent walletActivityIntent = new Intent(Application.Context, typeof(WalletActivity)); walletActivityIntent.PutExtra("User", JsonConvert.SerializeObject(user)); this.StartActivity(walletActivityIntent); Finish(); }); Dialog dialogSuccess = alertSuccess.Create(); dialogSuccess.Show(); } //If the user has no wallet, it will be created else { //Assigning wallet Email to the user and creating new balance wallet.Email = user.Email; wallet.Balance = amountText.Text; //Creating necessary extra parameters for the backend request Dictionary <string, string> extraParameters = new Dictionary <string, string>(); extraParameters.Add("Id", user.Id); extraParameters.Add("type", "topUp"); extraParameters.Add("parkingId", "1"); //Inserting new wallet to the Database await walletTable.InsertAsync(wallet, extraParameters); //Creating success message Android.App.AlertDialog.Builder alertSuccess = new Android.App.AlertDialog.Builder(this); alertSuccess.SetTitle("Top Up"); alertSuccess.SetMessage("Top is successful"); alertSuccess.SetPositiveButton("Ok", (senderAlertSucces, argsSuccess) => { Intent walletActivityIntent = new Intent(Application.Context, typeof(WalletActivity)); walletActivityIntent.PutExtra("User", JsonConvert.SerializeObject(user)); this.StartActivity(walletActivityIntent); Finish(); }); Dialog dialogSuccess = alertSuccess.Create(); dialogSuccess.Show(); } } } //All possible exceptions from Stripe service catch (StripeException e) { switch (e.StripeError.ErrorType) { case "card_error": Console.WriteLine(" Code: " + e.StripeError.Code); Console.WriteLine("Message: " + e.StripeError.Message); break; case "api_connection_error": break; case "api_error": break; case "authentication_error": break; case "invalid_request_error": break; case "rate_limit_error": break; case "validation_error": break; default: // Unknown Error Type break; } } }
public async Task <IActionResult> Charge(string stripeEmail, string stripeToken) { var stripeProvider = await _paymentProviderRepository.Query().FirstOrDefaultAsync(x => x.Id == PaymentProviderHelper.StripeProviderId); var stripeSetting = JsonConvert.DeserializeObject <StripeConfigForm>(stripeProvider.AdditionalSettings); var stripeChargeService = new StripeChargeService(stripeSetting.PrivateKey); var currentUser = await _workContext.GetCurrentUser(); var cart = await _cartService.GetActiveCart(currentUser.Id).FirstOrDefaultAsync(); var orderCreationResult = await _orderService.CreateOrder(cart.Id, "Stripe", 0, OrderStatus.PendingPayment); if (!orderCreationResult.Success) { TempData["Error"] = orderCreationResult.Error; return(Redirect("~/checkout/payment")); } var order = orderCreationResult.Value; var zeroDecimalOrderAmount = order.OrderTotal; if (!CurrencyHelper.IsZeroDecimalCurrencies()) { zeroDecimalOrderAmount = zeroDecimalOrderAmount * 100; } var regionInfo = new RegionInfo(CultureInfo.CurrentCulture.LCID); var payment = new Payment() { OrderId = order.Id, Amount = order.OrderTotal, PaymentMethod = "Stripe", CreatedOn = DateTimeOffset.UtcNow }; try { var charge = stripeChargeService.Create(new StripeChargeCreateOptions { Amount = (int)zeroDecimalOrderAmount, Description = "Sample Charge", Currency = regionInfo.ISOCurrencySymbol, SourceTokenOrExistingSourceId = stripeToken }); payment.GatewayTransactionId = charge.Id; payment.Status = PaymentStatus.Succeeded; order.OrderStatus = OrderStatus.PaymentReceived; _paymentRepository.Add(payment); await _paymentRepository.SaveChangesAsync(); return(Redirect("~/checkout/congratulation")); } catch (StripeException ex) { payment.Status = PaymentStatus.Failed; payment.FailureMessage = ex.StripeError.Message; order.OrderStatus = OrderStatus.PaymentFailed; _paymentRepository.Add(payment); await _paymentRepository.SaveChangesAsync(); TempData["Error"] = ex.StripeError.Message; return(Redirect("~/checkout/payment")); } }
public HttpResponseMessage Transfer(JObject saveBundle) { try { //int numOfRegs = 0; //decimal totalFees = 0; var transferId = (Int32)saveBundle["transferId"]; var transferNewListName = (string)saveBundle["transferNewListName"]; var participantId = (Int32)saveBundle["partId"]; var log = new EventureLog(); log.Message = "starting transfer: " + transferId; log.Caller = "transfer"; log.Status = "Info"; log.LogDate = System.DateTime.Now.ToLocalTime(); db.EventureLogs.Add(log); db.SaveChanges(); var transfer = db.EventureTransfers.Where(t => t.Id == transferId).Single(); var order = new EventureOrder { DateCreated = DateTime.Now, //HouseId = (Int32)saveBundle["houseId"], Amount = (Decimal)saveBundle["amount"], Token = (string)saveBundle["token"], //is this safe?? OwnerId = (Int32)saveBundle["ownerId"], Status = "init transfer", Voided = false }; db.Orders.Add(order); Owner owner = db.Owners.Where(o => o.Id == order.OwnerId).SingleOrDefault(); if (owner == null) { throw new Exception("Owner Setup is Not Configured Correctly"); } //validate //must have transferId, //i could process without partId just no email //calulate order.CardProcessorFeeInCents = Convert.ToInt32(Math.Round(Convert.ToInt32(order.Amount * 100) * owner.CardProcessorFeePercentPerCharge / 100, 0) + owner.CardProcessorFeeFlatPerChargeInCents); order.LocalFeeInCents = Convert.ToInt32(Math.Round(Convert.ToInt32(order.Amount * 100) * owner.LocalFeePercentOfCharge / 100, 0) + owner.LocalFeeFlatPerPerChargeInCents); order.LocalApplicationFee = order.LocalFeeInCents - order.CardProcessorFeeInCents; string custDesc = string.Empty; string partEmail = string.Empty; var part = db.Participants.Where(p => p.Id == participantId).FirstOrDefault(); if (part != null) { custDesc = "_transfer" + transferId; partEmail = part.Email; } else { //this should never happen throw exception? //NO house Id throw new Exception("There was an issue with submission, Not signed into account."); } // create customer var customerOptions = new StripeCustomerCreateOptions { Email = partEmail, Description = custDesc, TokenId = order.Token, }; var stripeCustomerService = new StripeCustomerService(owner.AccessToken); var customer = stripeCustomerService.Create(customerOptions); var stripeChargeService = new StripeChargeService(owner.AccessToken); //The token returned from the above method var stripeChargeOption = new StripeChargeCreateOptions() { AmountInCents = Convert.ToInt32(order.Amount * 100), Currency = "usd", CustomerId = customer.Id, Description = owner.Name, //this needs to be dynamic ApplicationFeeInCents = order.LocalApplicationFee }; var stripeCharge = stripeChargeService.Create(stripeChargeOption); if (string.IsNullOrEmpty(stripeCharge.FailureCode)) { // update reg var reg = db.Registrations.Where(r => r.Id == transfer.RegistrationId).Single(); reg.EventureListId = transfer.EventureListIdTo; // mjb 060914 reg.Name = transferNewListName; reg.Type = "xferup"; transfer.IsComplete = true; order.AuthorizationCode = stripeCharge.Id; //stripeCharge. order.CardNumber = stripeCharge.StripeCard.Last4; order.CardCvcCheck = stripeCharge.StripeCard.CvcCheck; order.CardExpires = stripeCharge.StripeCard.ExpirationMonth + "/" + stripeCharge.StripeCard.ExpirationYear; order.CardFingerprint = stripeCharge.StripeCard.Fingerprint; //order.CardId = stripeCharge.StripeCard.; order.CardName = stripeCharge.StripeCard.Name; order.CardOrigin = stripeCharge.StripeCard.Country; order.CardType = stripeCharge.StripeCard.Type; order.Voided = false; order.Status = "Complete"; db.SaveChanges(); var resp = Request.CreateResponse(HttpStatusCode.OK); //resp.Content = new StringContent(); resp.Content = new StringContent(transferId.ToString(), Encoding.UTF8, "text/plain"); //send transferId?? just for practice?? return(resp); //var resp = Request.CreateResponse(HttpStatusCode.OK); ////resp.Content = new StringContent(); //resp.Content = new StringContent(order.Id.ToString(), Encoding.UTF8, "text/plain"); //return resp; } else { order.Status = stripeCharge.FailureMessage; db.SaveChanges(); //should i save here? return(Request.CreateResponse(HttpStatusCode.ExpectationFailed, stripeCharge)); } } catch (Exception ex) { //send quick email HttpResponseMessage result = new MailController().SendInfoMessage("*****@*****.**", "Error Handler_Payment_Post: " + ex.Message + "\n\n" + ex.InnerException); //regular log var logE = new EventureLog { Message = "Error Handler: " + ex.Message + "\n\n" + ex.InnerException, Caller = "Payment_Post", Status = "ERROR", LogDate = System.DateTime.Now.ToLocalTime() }; db.EventureLogs.Add(logE); db.SaveChanges(); var returnMessage = "There was error with your transaction, please try again."; if (ex.Source == "Stripe.net") { returnMessage = ex.Message; } if (Request != null) { return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, returnMessage)); } //return Request.CreateResponse(HttpStatusCode.InternalServerError); else { return(new HttpResponseMessage(HttpStatusCode.InternalServerError)); //return new HttpResponseMessage(HttpStatusCode.InternalServerError,); } } }
public StripeBillingChargeService(string apiKey, IMapper mapper) { _service = new StripeChargeService(apiKey); _mapper = mapper; }
public Transaction_Result Auth(Sale_Details details) { bool isApproved = false; bool isPending = false; bool failed = false; try { StripeConfiguration.SetApiKey(secretKey); if (details.ProviderToken == null || details.ProviderToken.Length <= 1) { try { StripeSource source = createStripeSource(details.CardNumber, details.CardExpiryYear, details.CardExpiryMonth, details.CardCCV, details.CardHolderName + " " + details.CardHolderLastName, false); details.ProviderToken = source.Id; } catch (StripeException e) { return(new Transaction_Result() { isApproved = false, hasServerError = true, ErrorCode = e.StripeError.Code, ErrorText = e.StripeError.Message, FullResponse = e.StripeError.StripeResponse.ResponseJson }); } } StripeCustomer customer = new StripeCustomer(); if (details.ProviderToken.IndexOf("cus") > -1) { customer = getTCGStripeCustomer(details.ProviderToken); } else { customer = createTCGStripeCustomer(new StorePaymentMethod_Details() { CardCVV = details.CardCCV, CardExpiryMonth = details.CardExpiryMonth, CardExpiryYear = details.CardExpiryYear, CardHolderName = details.CardHolderName, CardNumber = details.CardNumber, CardHolderSurname = details.CardHolderLastName }, details.ProviderToken); } details.ProviderToken = customer.DefaultSourceId; var chargeOptions = new StripeChargeCreateOptions() { Amount = calculateAmount(details.Amount, details.CurrencyCode), Currency = details.CurrencyCode.ToLower(), //SHOULD BE LOWER CASE Description = "Authentication for " + details.CustomerLastName + ", " + details.CustomerFirstName, SourceTokenOrExistingSourceId = details.ProviderToken, CustomerId = customer.Id, Capture = false }; var chargeService = new StripeChargeService(); StripeCharge charge = chargeService.Create(chargeOptions); string status = charge.Status; if (status.Contains("succeeded")) { isApproved = true; } else if (status.Contains("pending")) { isPending = true; } else { failed = true; } return(new Transaction_Result { isApproved = isApproved, hasServerError = failed, ErrorText = charge.FailureMessage, ResultText = charge.Status, isPending = isPending, ProviderToken = charge.Id, FullResponse = charge.StripeResponse.ResponseJson, ApprovalCode = charge.Status }); } catch (StripeException e) { return(new Transaction_Result { isApproved = false, hasServerError = true, ErrorText = e.StripeError.Message, ProviderToken = null, ErrorCode = e.StripeError.Code, FullResponse = e.StripeError.StripeResponse.ResponseJson }); } }
public ActionResult StoreCheckout(string stripeEmail, string stripeToken, int bandId, string productsSold, string firstName, string lastName, string streetOne, string city, string StateId, string zipCode, double totalPrice) { List <SoldProduct> soldProducts = JsonConvert.DeserializeObject <List <SoldProduct> >(productsSold); var band = db.Bands .Include(b => b.Store) .Include("Store.Products") .Include("Store.Products.ProductType") .Include("Store.Products.Sizes") .Where(b => b.BandId == bandId) .FirstOrDefault(); //STRIPE STUFF/////////////////////////////////////////////////////// KeyManager keyManager = new KeyManager(); string stripeKey = keyManager.StripeSecretKey; StripeConfiguration.SetApiKey(stripeKey); //Create Customer var customerOptions = new StripeCustomerCreateOptions { Email = stripeEmail, }; var customerService = new StripeCustomerService(); StripeCustomer customer = customerService.Create(customerOptions); // Charge the user's card: int amountInCents = Convert.ToInt32(totalPrice * 100); var charges = new StripeChargeService(); var charge = charges.Create(new StripeChargeCreateOptions { Amount = amountInCents, Currency = "usd", Description = band.Name + " Band Merch Order", SourceTokenOrExistingSourceId = stripeToken }); ///////////////////////////////////////////////////////////////////////// Transaction transaction = new Transaction(); transaction.CreatedOn = DateTime.Now; Address address = GetAddress(streetOne, city, StateId, zipCode); transaction.CustomerAddress = address; transaction.CustomerFirstName = firstName; transaction.CustomerLastName = lastName; transaction.TotalPrice = totalPrice; transaction.ConfirmationNumber = stripeToken; transaction.CustomerEmail = stripeEmail; transaction.SoldProducts = new List <SoldProduct>(); //decrease inventory and create a transaction foreach (SoldProduct soldProduct in soldProducts) { soldProduct.SoldAtTourDate = false; soldProduct.BandId = bandId; soldProduct.DateSold = DateTime.Now; //db.SoldProducts.Add(soldProduct); transaction.SoldProducts.Add(soldProduct); //decrement the inventory Product product = db.Products .Include(p => p.ProductType) .Include(p => p.Sizes) .Where(p => p.ProductId == soldProduct.ProductId) .FirstOrDefault(); if (product.ProductType.ProductTypeId == 2)//Garment { foreach (Size size in product.Sizes) { if (size.SizeId == soldProduct.SizeId) { size.QuantityAvailable--; product.QuantityAvailable--; } } } else { product.QuantityAvailable--; } } db.Transactions.Add(transaction); db.SaveChanges(); TempData["storeId"] = band.Store.StoreId; TempData["bandName"] = band.Name; TempData["orderConfirmation"] = transaction.ConfirmationNumber; return(RedirectToAction("ThankYou", "Store")); }
public Transaction_Result Sale(Sale_Details details) { StripeConfiguration.SetApiKey(secretKey); //ONCE-OFF PAYMENT if (details.ProviderToken == null || details.ProviderToken.Length <= 1) { try { StripeSource source = createStripeSource(details.CardNumber, details.CardExpiryYear, details.CardExpiryMonth, details.CardCCV, details.CardHolderName + " " + details.CardHolderLastName, false); details.ProviderToken = source.Id; } catch (StripeException e) { return(new Transaction_Result() { isApproved = false, hasServerError = true, ErrorCode = e.StripeError.Code, ErrorText = e.StripeError.Message, FullResponse = e.StripeError.StripeResponse.ResponseJson }); } } //INITIATING A CHARGE var chargeOptions = new StripeChargeCreateOptions(); var chargeService = new StripeChargeService(); StripeCharge charge = new StripeCharge(); chargeOptions.Capture = true; bool isApproved = false; bool isPending = false; try { //IF A SOURCE TOKEN IS PROVIDED >>>> ONCE-OFF PAYMENT if (details.ProviderToken.IndexOf("src") > -1) { var sourceService = new StripeSourceService(); StripeSource source = sourceService.Get(details.ProviderToken); chargeOptions.SourceTokenOrExistingSourceId = source.Id; chargeOptions.Amount = calculateAmount(details.Amount, details.CurrencyCode); // $1.00 = 100 cents chargeOptions.Currency = details.CurrencyCode.ToLower(); //SHOULD BE LOWER CASE charge = chargeService.Create(chargeOptions); } //ONCE-OFF PAYMENT else if (details.ProviderToken.IndexOf("tok") > -1) { var sourceService = new StripeSourceService(); chargeOptions.SourceTokenOrExistingSourceId = details.ProviderToken; chargeOptions.Amount = calculateAmount(details.Amount, details.CurrencyCode); // $1.00 = 100 cents chargeOptions.Currency = details.CurrencyCode.ToLower(); //SHOULD BE LOWER CASE charge = chargeService.Create(chargeOptions); } //A REUSABLE CUSTOMER (OR A CARD) else if (details.ProviderToken.IndexOf("cus") > -1) { var customerService = new StripeCustomerService(); StripeCustomer customer = customerService.Get(details.ProviderToken); chargeOptions.SourceTokenOrExistingSourceId = customer.DefaultSourceId; chargeOptions.CustomerId = details.ProviderToken; chargeOptions.Amount = calculateAmount(details.Amount, details.CurrencyCode); // $1.00 = 100 cents chargeOptions.Currency = details.CurrencyCode.ToLower(); //SHOULD BE LOWER CASE charge = chargeService.Create(chargeOptions); } string status = charge.Status; if (status.Contains("succeeded")) { isApproved = true; } else if (status.Contains("pending")) { isPending = true; } return(new Transaction_Result { isApproved = isApproved, hasServerError = isPending, ErrorText = charge.FailureMessage, ErrorCode = charge.FailureCode, TransactionIndex = charge.BalanceTransactionId, ProviderToken = charge.Id, ResultText = charge.Status, FullResponse = charge.StripeResponse.ResponseJson }); } catch (StripeException e) { return(new Transaction_Result { isApproved = false, hasServerError = true, ErrorText = e.StripeError.Message, ProviderToken = null, ErrorCode = e.StripeError.Code, FullResponse = e.StripeError.StripeResponse.ResponseJson }); } }
public PaymentService(IOptions <PaymentSettings> paymentSettings, StripeChargeService stripeChargeService) { _paymentSettings = paymentSettings.Value; _stripeChargeService = stripeChargeService; }
public ActionResult Charge(string stripeEmail, string stripeToken) { try { var order = ProcessToDatabase(this.HttpContext); var cart = ShoppingCart.GetCart(this.HttpContext); var cartProduct = cart.GetCartItems(); foreach (var item in cartProduct) { Products product = db.Products.Where(p => p.ProductId == item.ProductId).First(); if (product.InStock == false) { return(RedirectToAction("Index", "Checkout", 1)); } } db.Order.Add(order); db.SaveChanges(); APIFucnction.SendSimpleMessage("Your order has been placed", "*****@*****.**", "Thank you for choosing PaintedPlunders"); foreach (var item in cartProduct) { OrderItem oi = new OrderItem(); oi.OrderId = order.OrderId; oi.Order = order; oi.ProductId = item.ProductId; oi.Product = item.Product; db.OrderItems.Add(oi); db.SaveChanges(); } order.PublicOrderNum = GetRandomizedString(order.OrderId); db.SaveChanges(); var orderList = db.OrderItems.Where(o => o.OrderId == order.OrderId).ToList(); foreach (var item in orderList) { Products product = db.Products.Where(p => p.ProductId == item.ProductId).First(); product.InStock = false; db.SaveChanges(); } cart.EmptyCart(); } catch { return(RedirectToAction("Index", "Checkout", 2)); } var customers = new StripeCustomerService(); var charges = new StripeChargeService(); var customer = customers.Create(new StripeCustomerCreateOptions { Email = stripeEmail, SourceToken = stripeToken }); // Need to not hard code total as amount var charge = charges.Create(new StripeChargeCreateOptions { Amount = 4900,//charge in cents Description = "Sample Charge", Currency = "usd", CustomerId = customer.Id }); return(RedirectToAction("Index", "Home")); }
private void FrmProcessing_Shown(object sender, EventArgs e) { Cursor = Cursors.WaitCursor; Error = null; var thread = new Thread(new ThreadStart(delegate { var api = Properties.Settings.Default.StripeKey; var tokenService = new StripeTokenService(api); try { var description = Description + " for "; var tokenData = new StripeTokenCreateOptions { CardNumber = CardNumber, CardExpirationMonth = CardMonth, CardExpirationYear = CardYear, CardCvc = CardCVC }; if (Person != null) { tokenData.CardAddressLine1 = Person.Address1; tokenData.CardAddressLine2 = Person.Address2; tokenData.CardAddressCity = Person.City; tokenData.CardAddressState = Person.State; tokenData.CardAddressZip = Person.ZipCode; tokenData.CardAddressCountry = Person.Country; tokenData.CardName = Person.Name; description += Person.Name + " (#" + Person.PeopleID + ")"; } else { tokenData.CardName = PayeeName; description += PayeeName; } var token = tokenService.Create(tokenData); var chargeData = new StripeChargeCreateOptions { TokenId = token.Id, Description = description, AmountInCents = Convert.ToInt32(Amount * 100), Currency = "usd" }; var chargeService = new StripeChargeService(api); if (!FirstTry) { // Double-check to see if we already have a charge recently that matches the details of this. Helps with dealing // with timeout scenarios to prevent double-charges. var lastCharges = chargeService.List(20, 0, null); foreach (var charge in lastCharges) { if (charge.StripeCard.Last4 == CardNumber.Substring(CardNumber.Length - 4) && charge.StripeCard.ExpirationMonth.PadLeft(2, '0') == CardMonth && charge.StripeCard.ExpirationYear.Substring(2) == CardYear && charge.AmountInCents == Convert.ToInt32(Amount * 100) && charge.Description == "Purchases for " + Person.Name + " (#" + Person.PeopleID + ")") { Charge = charge; break; } } } if (Charge == null) { Charge = chargeService.Create(chargeData); } } catch (StripeException ex) { Error = ex; } _processingDone = true; })); thread.Start(); while (!_processingDone) { Application.DoEvents(); } Cursor = Cursors.Default; DialogResult = DialogResult.OK; }
public async Task <ActionResult> Create([Bind(Include = "ID,FirstName,LastName,EmailAddress,PhoneNumber,Quantity,DeliveryDate,IsMetro,DeliveryArea,NeedsPrint,PrintSize,PrintFormat,IsDoubleSided,Attachment,Cost")] CreateOrderViewModel createOrderViewModel) { if (!string.IsNullOrEmpty(createOrderViewModel.DeliveryArea)) { if (createOrderViewModel.DeliveryArea.EndsWith(", ")) { createOrderViewModel.DeliveryArea = createOrderViewModel.DeliveryArea.Remove(createOrderViewModel.DeliveryArea.Length - 2); } } if (!string.IsNullOrEmpty(Request["token1"]) && ModelState.IsValid) { HttpContext.Session["homePageModel1"] = createOrderViewModel; CreateOrderViewModel model = (CreateOrderViewModel)HttpContext.Session["homePageModel1"]; Order order = this.ProcessOrder(createOrderViewModel); // Add the order to session for use when the customer returns from payment HttpContext.Session["orderInformation"] = order; var myCharge = new StripeChargeCreateOptions { // convert the amount of $12.50 to cents i.e. 1250 Amount = (int)(order.Quote.Cost * 100), Currency = "aud", Description = "SG Fast Flyers Order Number:" + order.ID.ToString(), SourceTokenOrExistingSourceId = Request["token1"] }; var chargeService = new StripeChargeService(Config.privateStripeKey); var stripeCharge = chargeService.Create(myCharge); if (stripeCharge != null && !String.IsNullOrEmpty(stripeCharge.FailureMessage)) //// Failed.. { throw new Exception("ERROR:" + stripeCharge.FailureMessage); } else //// All good { string attach = Server.MapPath(@"\Content\Documents\SGFastFlyers_Letterbox_Printing_&_Delivery_Details.pdf"); var body = "Hi {6}, </br><p>Here is your order: </p></br><p>Order ID: {9}</p></br><p>Quantity: {0}</p><p>Delivery Date: {8}</p><p>Delivery Area: {7}</p><p>Metro Area: {1}</p><p>Is printing required: {2}" + "</p><p>Print Size: {3}</p><p>Double Sided: {4}</p><p>Price: {5}</p></br><p>Thank you for your order.</p><p>Kind Regards,</p>SG Fast Flyers."; var message = new MailMessage(); message.To.Add(new MailAddress(model.EmailAddress)); // replace with valid value message.Bcc.Add(new MailAddress(Config.sgEmail)); message.From = new MailAddress(Config.sgEmail); // replace with valid value message.Subject = "Order ID " + order.ID.ToString();; message.Body = string.Format(body, model.Quantity, (model.IsMetro == true ? Config.Yes : Config.No), (model.NeedsPrint == true ? Config.Yes : Config.No), model.PrintSize, (model.IsDoubleSided == true ? Config.Yes : Config.No), model.FormattedCost, model.FirstName, model.DeliveryArea, model.DeliveryDate, order.ID); message.IsBodyHtml = true; message.Attachments.Add(new Attachment(attach)); try { using (SmtpClient smtp = new SmtpClient()) { await smtp.SendMailAsync(message); } } catch (Exception) { //TODO: Something needs to be done with this exception... } return(this.Redirect("/Orders/PaymentComplete")); } } if (!string.IsNullOrEmpty(Request.Form["hdndirectDebitEmail"]) && ModelState.IsValid && createOrderViewModel.NeedsPrint) { HttpContext.Session["homePageModel1"] = createOrderViewModel; CreateOrderViewModel model = (CreateOrderViewModel)HttpContext.Session["homePageModel1"]; DirectDebitEmail model1 = new DirectDebitEmail(); Order order = this.ProcessOrder(createOrderViewModel); { var url = @"\home\index"; var linkText = "Click here"; var body = "Hi {6}, </br><p>Here is your order: </p></br><p>Order ID: {9}</p></br><p>Quantity: {0}</p><p>Delivery Date: {8}</p><p>Delivery Area: {7}</p><p>Metro Area: {1}</p><p>Is printing required: {2}" + "</p><p>Print Size: {3}</p><p>Double Sided: {4}</p><p>Price: {5}</p></br><p>Thank you for your order.</p><p> Our Direct Deposit Details are:</p><p>BSB: 014-289</p><p>" + "Account: 463-181-792</p><p>Please use your name as your reference.</p><p>Kind Regards,</p>SG Fast Flyers."; var firstName = model.FirstName; string fN = string.Format("Hi {0},", firstName); string href = String.Format("<a href='{0}'>{1}</a>", url, linkText); string attach = Server.MapPath(@"\Content\Documents\SGFastFlyers_Letterbox_Printing_&_Delivery_Details.pdf"); string yourEncodedHtml = fN + "</br><p>You have been emailed your order with details of how to pay via Direct Debit. </p></br><p> Please note, your order " + "will not be acted upon until payment has been recieved into our account.</p></br> <p>Thank you for your order.</p>" + href + " to begin another quote. <p>Have a great day.</p>"; var html = new MvcHtmlString(yourEncodedHtml); var message = new MailMessage(); message.To.Add(new MailAddress(createOrderViewModel.EmailAddress)); // replace with valid value message.Bcc.Add(new MailAddress(Config.sgEmail)); message.From = new MailAddress(Config.sgEmail); // replace with valid value message.Subject = "Order ID " + order.ID.ToString(); message.Body = string.Format(body, model.Quantity, (model.IsMetro == true ? Config.Yes : Config.No), (model.NeedsPrint == true ? Config.Yes : Config.No), model.PrintSize, (model.IsDoubleSided == true ? Config.Yes : Config.No), model.FormattedCost, model.FirstName, model.DeliveryArea, model.DeliveryDate, order.ID); message.IsBodyHtml = true; message.Attachments.Add(new Attachment(attach)); try { using (SmtpClient smtp = new SmtpClient()) { await smtp.SendMailAsync(message); } ViewBag.Status = html; } catch (Exception) { ViewBag.Status = "Problem while sending email, Please check details."; } } return(View("DirectDebitEmail", model1)); } if (!string.IsNullOrEmpty(Request.Form["hdndirectDebitEmail"]) && ModelState.IsValid && (createOrderViewModel.NeedsPrint == false)) { HttpContext.Session["homePageModel1"] = createOrderViewModel; CreateOrderViewModel model = (CreateOrderViewModel)HttpContext.Session["homePageModel1"]; DirectDebitEmail model1 = new DirectDebitEmail(); Order order = this.ProcessOrder(createOrderViewModel); { var url = @"\home\index"; var linkText = "Click here"; var body = "Hi {0}, </br><p>Here is your order: </p></br><p>Order ID: {6}</p></br><p>Quantity: {1}</p><p>Delivery Date: {2:d}</p><p>Delivery Area: {3}</p><p>Metro Area: {4}</p>" + "<p>Price: {5}</p></br><p>Thank you for your order.</p><p> Our Direct Deposit Details are:</p><p>BSB: 014-289</p><p>" + "Account: 463-181-792</p><p>Please use your name as your reference.</p><p>Kind Regards,</p>SG Fast Flyers."; var firstName = model.FirstName; string fN = string.Format("Hi {0},", firstName); string href = String.Format("<a href='{0}'>{1}</a>", url, linkText); string attach = Server.MapPath(@"\Content\Documents\SGFastFlyers_Letterbox_Printing_&_Delivery_Details.pdf"); string yourEncodedHtml = fN + "</br><p>You have been emailed your order with details of how to pay via Direct Debit. </p></br><p> Please note, your order " + "will not be acted upon until payment has been recieved into our account.</p></br> <p>Thank you for your order.</p>" + href + " to begin another quote. <p>Have a great day.</p>"; var html = new MvcHtmlString(yourEncodedHtml); var message = new MailMessage(); message.To.Add(new MailAddress(createOrderViewModel.EmailAddress)); // replace with valid value message.Bcc.Add(new MailAddress(Config.sgEmail)); message.From = new MailAddress(Config.sgEmail); // replace with valid value message.Subject = "Your Quote"; message.Body = string.Format(body, model.FirstName, model.Quantity, model.DeliveryDate, model.DeliveryArea, (model.IsMetro == true ? Config.Yes : Config.No), model.FormattedCost, order.ID); message.IsBodyHtml = true; message.Attachments.Add(new Attachment(attach)); try { using (SmtpClient smtp = new SmtpClient()) { await smtp.SendMailAsync(message); } ViewBag.Status = html; } catch (Exception) { ViewBag.Status = "Problem while sending email, Please check details."; } } return(View("DirectDebitEmail", model1)); } return(this.View(createOrderViewModel)); }
protected void Page_Load(object sender, EventArgs e) { //Get Querystring Values if (string.IsNullOrEmpty(Request.QueryString["Item"]) || string.IsNullOrEmpty(Request.QueryString["UserID"]) || string.IsNullOrEmpty(Request.QueryString["UserName"]) || string.IsNullOrEmpty(Request.QueryString["Price"])) { //QueryString null, Redirect USer Response.Redirect("/Home?MSG=CheckOutError"); } else { //Retrieve QS values ItemPrice = Request.QueryString["Price"]; Item = Request.QueryString["Item"]; UserName = Request.QueryString["UserName"]; UserId = Request.QueryString["UserID"]; } //Check for postback if (!Page.IsPostBack) { //Load Data to form try { //Get the logged in User if any MembershipUser LoggedInMembershipUser; LoggedInMembershipUser = Membership.GetUser(); //Check if there is a logged in User if (LoggedInMembershipUser != null) { //Membership Data UserName2.Text = LoggedInMembershipUser.UserName.ToString(); Email.Text = LoggedInMembershipUser.Email.ToString(); Price.Text = "$" + ItemPrice; Hours.Text = Item; //Set link HLPaypal.NavigateUrl = "https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&business=J9T4RVL3P6SRE&item_name=" + Item + "&amount=" + ItemPrice + "&on1=RALTUserID&os1=" + UserId + "&on0=RALTUserName&os0=" + UserName; //RALT UserData user UserData = new user(); UserData = UserService.GetUserByMemberId(Convert.ToInt32(LoggedInMembershipUser.ProviderUserKey.ToString())); //Show User Status if (UserData.account_status == "Request Made") { ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "CompleteVerify", "CompleteStep(" + '0' + ");", true); } else if (UserData.account_status == "Verified") { ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "CompleteVerify", "CompleteStep(" + '1' + ");", true); } else if (UserData.account_status == "Email Sent") { ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "CompleteVerify", "CompleteStep(" + '2' + ");", true); } else if (UserData.account_status == "Paid") { ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "CompleteVerify", "CompleteStep(" + '3' + ");", true); } else if (UserData.account_status == "First Class") { ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "CompleteVerify", "CompleteStep(" + '4' + ");", true); } } } catch { } } //PostBack else { //Retrieve the StripeToken if any var customerToken = this.Request.Form["stripeToken"]; //No Token do not proceed if (!object.ReferenceEquals(customerToken, null)) { try { var myCharge = new StripeChargeCreateOptions(); double Price = Convert.ToDouble(ItemPrice); // always set these properties myCharge.AmountInCents = (int)(Price * 100); myCharge.Currency = "usd"; // set this if you want to myCharge.Description = Request.QueryString["Item"]; Dictionary <string, string> dictionary = new Dictionary <string, string>(); dictionary.Add("RALTUserName", Request.QueryString["UserName"]); dictionary.Add("RALTUserID", Request.QueryString["UserID"]); myCharge.Metadata = dictionary; // set this property if using a token myCharge.TokenId = customerToken; // (not required) set this to false if you don't want to capture the charge yet - requires you call capture later myCharge.Capture = true; var chargeService = new StripeChargeService(); StripeCharge stripeCharge = chargeService.Create(myCharge); //Clear CC details // this.Request.Form.Remove("stripeToken"); CardHolderName.Text = ""; CardNumber.Text = ""; CVC.Text = ""; EXPMonth.Text = ""; EXPYear.Text = ""; App_Code.NotificationService.SendNotification("ChargeComplete", "Thank you, your payment is complete.", "success", "3000"); } catch (Exception ex) { App_Code.NotificationService.SendNotification("ChargeError", ex.Message, "error"); } } } }
static void Main(string[] args) { // Set Stripe Api Key StripeConfiguration.SetApiKey(AppConfiguration.StripeApiKey); using (var subscriptionBookingRepository = new SubscriptionBookingRepository()) { var subscriptionBookingList = subscriptionBookingRepository.SubscriptionBookingsList.ToList(); // Each Subscription Bookings subscriptionBookingList.ForEach(subscriptionBookings => { var customerInfos = subscriptionBookingRepository.CustomerInfoList .FirstOrDefault(ci => ci.CustomerId == subscriptionBookings.CustomerId); // Customer Infos if (customerInfos != null) { var subscriptionService = new StripeSubscriptionService(); StripeSubscription subscription = subscriptionService.Get(subscriptionBookings.StripeSubscriptionId); DateTime?canceledDate = subscription.CanceledAt; var invoiceService = new StripeInvoiceService(); // All Invoices of Customer var invoiceItems = invoiceService.List(new StripeInvoiceListOptions { CustomerId = customerInfos.StripeCustomerId } ).OrderBy(ic => ic.Date).ToList(); short cycleNumber = 0; invoiceItems.ForEach(invoice => { if (invoice.SubscriptionId.Equals(subscriptionBookings.StripeSubscriptionId, StringComparison.InvariantCulture)) { cycleNumber++; double totalCharge = (double)invoice.Total / 100; if (!totalCharge.Equals(subscriptionBookings.TotalPrice)) { subscriptionBookings.Price = totalCharge; } DateTime?periodStart = invoice.PeriodStart; DateTime?periodEnd = invoice.PeriodEnd; try { if (periodStart.Value.Date == periodEnd.Value.Date) { periodEnd = periodEnd.Value.AddDays(30); } periodStart = invoice.StripeInvoiceLineItems.Data[0].StripePeriod.Start; periodEnd = invoice.StripeInvoiceLineItems.Data[0].StripePeriod.End; } catch (Exception) { } var subscriptionCycle = new SubscriptionCycles { SubscriptionBookingId = subscriptionBookings.Id, StartDate = periodStart, EndDate = periodEnd, CancelDate = subscriptionBookings.CancelDate, Status = subscriptionBookings.Status, LastUpdatedDate = subscriptionBookings.LastUpdatedDate, LastUpdatedBy = subscriptionBookings.LastUpdatedBy, Price = totalCharge.Equals(0) && subscriptionBookings.PayByCredit > 0 ? subscriptionBookings.PayByCredit : totalCharge, MerchantPrice = subscriptionBookings.MerchantPrice, PayByCredit = subscriptionBookings.PayByCredit, TotalPrice = totalCharge, Quantity = subscriptionBookings.Quantity, StripeInvoiceId = invoice.Id, StripeChargeId = invoice.ChargeId, StripeCouponId = subscriptionBookings.StripeCouponId, CycleNumber = cycleNumber }; var param = new AddSubscriptionCycleParams { CanceledDate = canceledDate, SubscriptionCyclesObject = subscriptionCycle, SubscriptionInvoices = new List <SubscriptionInvoices>() }; SubscriptionInvoices subscriptionInvoice; // Paid Charge if (invoice.Paid) { if (!string.IsNullOrEmpty(invoice.ChargeId)) { var chargeService = new StripeChargeService(); StripeCharge charge = chargeService.Get(invoice.ChargeId); subscriptionInvoice = new SubscriptionInvoices { SubscriptionCyclesId = subscriptionCycle.Id, BookingStatus = subscriptionCycle.Status, Quantity = subscriptionBookings.Quantity, Price = (double)charge.Amount / 100, MerchantPrice = subscriptionBookings.MerchantPrice, PayByCredit = subscriptionBookings.PayByCredit, TotalPrice = (double)charge.Amount / 100, InvoiceStatus = (int)Enums.InvoiceStatus.Charge, StripeChargeId = charge.Id, ChargeAmount = (double)charge.Amount / 100, StripeRefundId = string.Empty, RefundAmount = 0, RefundCreditAmount = 0, StripeCouponId = subscriptionBookings.StripeCouponId, CreatedDate = DateTime.UtcNow, CreatedBy = 1 }; param.SubscriptionInvoices.Add(subscriptionInvoice); // Charge with Refunded if (charge.Refunded || charge.AmountRefunded > 0) { var refundList = charge.Refunds; for (int i = 0; i < refundList.Data.Count; i++) { var refundItem = charge.Refunds.Data[i]; var subscriptionInvoiceRefunded = new SubscriptionInvoices { SubscriptionCyclesId = subscriptionCycle.Id, BookingStatus = subscriptionCycle.Status, Quantity = subscriptionBookings.Quantity, Price = (double)charge.Amount / 100 - (double)refundItem.Amount / 100, MerchantPrice = subscriptionBookings.MerchantPrice, PayByCredit = subscriptionBookings.PayByCredit, TotalPrice = subscriptionBookings.MerchantPrice - (double)refundItem.Amount / 100 - subscriptionBookings.PayByCredit, InvoiceStatus = refundItem.Amount < charge.Amount ? (int)Enums.InvoiceStatus.PartialRefund : (int)Enums.InvoiceStatus.FullRefund, StripeChargeId = charge.Id, ChargeAmount = (double)charge.Amount / 100, StripeRefundId = refundItem.Id, RefundAmount = (double)refundItem.Amount / 100, RefundCreditAmount = 0, StripeCouponId = subscriptionBookings.StripeCouponId, CreatedDate = DateTime.UtcNow, CreatedBy = 1 }; param.SubscriptionInvoices.Add(subscriptionInvoiceRefunded); param.SubscriptionCyclesObject.Price = subscriptionInvoiceRefunded.Price; param.SubscriptionCyclesObject.TotalPrice = subscriptionInvoiceRefunded.TotalPrice; } } } else { // Charge but have Coupon and use DayAxe Credit so Amount = 0 subscriptionInvoice = new SubscriptionInvoices { SubscriptionCyclesId = subscriptionCycle.Id, BookingStatus = subscriptionCycle.Status, Quantity = subscriptionBookings.Quantity, Price = 0, MerchantPrice = subscriptionBookings.MerchantPrice, PayByCredit = subscriptionBookings.PayByCredit, TotalPrice = 0, InvoiceStatus = (int)Enums.InvoiceStatus.Charge, StripeChargeId = string.Empty, ChargeAmount = 0, StripeRefundId = string.Empty, RefundAmount = 0, RefundCreditAmount = 0, StripeCouponId = subscriptionBookings.StripeCouponId, CreatedDate = DateTime.UtcNow, CreatedBy = 1 }; param.SubscriptionInvoices.Add(subscriptionInvoice); } } else { // Closed Charge subscriptionInvoice = new SubscriptionInvoices { SubscriptionCyclesId = subscriptionCycle.Id, BookingStatus = subscriptionCycle.Status, Quantity = subscriptionBookings.Quantity, Price = totalCharge, MerchantPrice = subscriptionBookings.MerchantPrice, PayByCredit = subscriptionBookings.PayByCredit, TotalPrice = totalCharge, InvoiceStatus = (int)Enums.InvoiceStatus.Charge, StripeChargeId = invoice.ChargeId, ChargeAmount = totalCharge, StripeRefundId = string.Empty, RefundAmount = 0, RefundCreditAmount = 0, StripeCouponId = subscriptionBookings.StripeCouponId, CreatedDate = DateTime.UtcNow, CreatedBy = 1 }; param.SubscriptionInvoices.Add(subscriptionInvoice); } subscriptionBookingRepository.AddSubscriptionCycle(param); Console.WriteLine("Update - " + invoice.SubscriptionId); } }); } }); Console.WriteLine("Done!!!"); Console.ReadLine(); } }