public RecieptController() { model = new RecieptModel(); isActive = true; }
/// <summary> /// Handles subscription payments. Creates user and subscribes to plan /// </summary> /// <returns>reciept</returns> public ActionResult HandleSubPayment() { var subId = Request.Form["subId"]; var anon = Request.Form["anon"]; var user = Request.Form["user"]; var token = Request.Form["token"]; var email = Request.Form["email"]; var phone = Request.Form["phone"]; var birthnumber = Request.Form["birthnumber"]; var name = Request.Form["name"]; var description = Request.Form["description"]; var recieptemail = ""; //email to send reciept var recieptname = ""; //name on reciept var client = new WebClient(); var data = new NameValueCollection(); data["source"] = token; //the payment token with user's credidentials if (user == "true") { var manager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(_context)); var currentUser = manager.FindById(User.Identity.GetUserId()); recieptemail = currentUser.Email; recieptname = currentUser.Fname + " " + currentUser.Lname; data["email"] = currentUser.Email; data["description"] = "Bruker " + email + " i databasen: " + description; //set description of donation } else if ((anon == "true") && !string.IsNullOrEmpty(description)) { data["description"] = description; } else { if (!string.IsNullOrEmpty(email)) { data["email"] = email; recieptemail = email; } recieptname = name; data["description"] = "Telefon: " + phone + " - Navn: " + name + " - Fødselsnummer: " + birthnumber + " - Beskrivelse: " + description; } client.UseDefaultCredentials = true; //use default credidentials for API request var stripeList = _context.StripeAPI.ToList(); //check if stripe actually exists in the database byte[] response; if (!stripeList.Any()) { return (Json( new { Error = "Stripe er ikke konfigurert for applikasjonen.", Succsess = "false", striperesponse = "false" })); //no stripe in database, return error } if (!stripeList.First().Enabeled) { return (Json( new { Error = "Stripe er avslått for applikasjonen.", Succsess = "false", striperesponse = "false" })); //stripe disabeled } client.Credentials = new NetworkCredential(_context.StripeAPI.ToList().First().Secret, ""); try { response = client.UploadValues("https://api.stripe.com/v1/customers", "POST", data); // upload values and get response } catch (WebException exception) //exepction happen when poisting to API { string responseString; using (var reader = new StreamReader(exception.Response.GetResponseStream())) //read the errorstring { responseString = reader.ReadToEnd(); } return(Json(new { Error = responseString, Success = "false", striperesponse = "true" })); // return responsestring as error message } //if we get here customer was succsessfully created var json_serializer = new JavaScriptSerializer(); var JsonDict = (IDictionary <string, object>)json_serializer.DeserializeObject(client.Encoding.GetString(response)); //deseroalize the response var customer = JsonDict["id"].ToString(); //get id of customer returned by the API data = new NameValueCollection(); //now create a collection for the plan and subscribe data["plan"] = subId; data["customer"] = customer; try { response = client.UploadValues("https://api.stripe.com/v1/subscriptions", "POST", data); // upload values and get response } catch (WebException exception) //exepction happen when poisting to API { string responseString; using (var reader = new StreamReader(exception.Response.GetResponseStream())) //read the errorstring { responseString = reader.ReadToEnd(); } return(Json(new { Error = responseString, Success = "false", striperesponse = "true" })); // return responsestring as error message } //customer successfully subscribed to plan JsonDict = (IDictionary <string, object>)json_serializer.DeserializeObject(client.Encoding.GetString(response)); //deseroalize the response var subscriptionId = JsonDict["id"].ToString(); Response.StatusCode = 200; var sub = _context.Subscriptions.Find(int.Parse(subId)); if (!string.IsNullOrEmpty(recieptemail)) //send reciept email if reciept email is given { var subject = "Kvitering på donasjon"; var message = "Takk for din støtte! \n Du har started et abonement med id " + subId + " for " + sub.Amount + " kroner i måneden til Butterfly Friends. \n" + "Ditt referansenummer er " + subscriptionId + ". \n\n" + "Vennlig hilsen,\nButterfly Friends."; var messageHTML = "<p>Takk for din støtte! <br> Du har startet et abonement med id " + subId + " for " + sub.Amount + " kroner i måneden til Butterfly Friends. <br>" + "Ditt referansenummer er: " + subscriptionId + ". <br><br>" + "Vennlig hilsen,<br>Butterfly Friends.</p>"; if (!SendEmail(message, messageHTML, subject, recieptemail, recieptname)) { //returns true if sending of email was succsessful ViewBag.Error = "Emailkviteringen kunne ikke sendes, Sendgrid er ikke konfigurert."; } } ViewBag.Share = "https://www." + Request.Url.Host + "/Home/Index"; //share link for twitter ViewBag.ShareText = "Jeg donerer " + sub.Amount + " kr i måneden til Butterfly Friends!"; //share message var TwitterList = _context.Twitter.ToList(); //check if facebook and twitter exist var Twitter = new DbTables.Twitter(); if (TwitterList.Any()) { Twitter = TwitterList.First(); } var FacebookList = _context.Facebook.ToList(); var Facebook = new DbTables.Facebook(); if (FacebookList.Any()) { Facebook = FacebookList.First(); } var subReciept = new SubReciept { Amount = sub.Amount, Id = subId, referenceId = subscriptionId }; var model = new RecieptModel { Facebook = Facebook, Twitter = Twitter, SubReciept = subReciept }; return(PartialView("_RecieptPartial", model)); //return reciept view }
public async Task <IActionResult> Index(RecieptModel recieptModel) { if (!ModelState.IsValid) { ViewData["CountryList"] = GetCountryList(); return(View("~/Views/Panel/Reciepts/Index.cshtml")); } if (!(recieptModel.image.ContentType == "image/png" || recieptModel.image.ContentType == "image/jpg" || recieptModel.image.ContentType == "image/jpeg")) { TempData["ImageUploadError"] = "Unsupported image type. Kindly re-upload a JPG/JPEG/PNG only."; return(RedirectToAction("Index", "Profile")); } string dbPath = "/uploads/profile_picure"; string path = _env.WebRootPath + dbPath; string localFileName = Guid.NewGuid().ToString() + "." + recieptModel.image.ContentType.Split("/")[recieptModel.image.ContentType.Split("/").Length - 1]; byte[] imageStream; using (var memoryStream = new MemoryStream()) { await recieptModel.image.CopyToAsync(memoryStream); imageStream = memoryStream.ToArray(); } using (var fs = new FileStream($"{path}/{localFileName}", FileMode.Create, FileAccess.Write)) { await fs.WriteAsync(imageStream, 0, imageStream.Length); } List <KeyValuePair <string, string> > parameters = new List <KeyValuePair <string, string> >(); parameters.Add(new KeyValuePair <string, string>("i_id_organization", _objHelper.GetTokenData(HttpContext.User.Identity as ClaimsIdentity, "id_organization"))); parameters.Add(new KeyValuePair <string, string>("i_image", $"{dbPath}/{localFileName}")); parameters.Add(new KeyValuePair <string, string>("i_dated", recieptModel.dated)); parameters.Add(new KeyValuePair <string, string>("i_notes", recieptModel.notes)); parameters.Add(new KeyValuePair <string, string>("i_category", recieptModel.category)); parameters.Add(new KeyValuePair <string, string>("i_payment_account", recieptModel.payment_account)); parameters.Add(new KeyValuePair <string, string>("i_subtotal", recieptModel.subtotal)); parameters.Add(new KeyValuePair <string, string>("i_currency", recieptModel.currency)); parameters.Add(new KeyValuePair <string, string>("i_total", recieptModel.total)); parameters.Add(new KeyValuePair <string, string>("i_added_by", _objHelper.GetTokenData(HttpContext.User.Identity as ClaimsIdentity, "id_user"))); DataTable _dtResp = _objDataHelper.ExecuteProcedure("insert_reciept", parameters); if (this._objHelper.checkDBResponse(_dtResp)) { if (_dtResp.Rows[0]["response"].ToString() == "0") { ViewData["ErrorMessage"] = _dtResp.Rows[0]["message"].ToString(); } else { ViewData["SuccessMessage"] = "Reciept registered successfuly."; } } else { ViewData["ErrorMessage"] = "Reciept service unavailable"; } ViewData["RecieptList"] = null; DataTable _dtResp2 = GetRecieptList(); if (this._objHelper.checkDBNullResponse(_dtResp2)) { ViewData["RecieptList"] = _dtResp2; } else { ViewData["ListErrorMessage"] = "Unable to fetch data. Try again later."; } ViewData["CountryList"] = GetCountryList(); return(View("~/Views/Panel/Reciepts/Index.cshtml")); }
public ActionResult HandlePayment() { var amount = int.Parse(Request.Form["amount"]); var anon = Request.Form["anon"]; var user = Request.Form["user"]; var token = Request.Form["token"]; var email = Request.Form["email"]; var phone = Request.Form["phone"]; var city = Request.Form["city"]; var streetadress = Request.Form["streetadress"]; var postcode = Request.Form["postcode"]; var birthnumber = Request.Form["birthnumber"]; var name = Request.Form["name"]; var description = Request.Form["description"]; var recieptemail = ""; var recieptname = ""; var donation = new DbTables.Donations(); if (anon == "true") //payment is anonymous { donation = new DbTables.Donations { Amount = amount, Description = description, anonymous = true }; } else if ((user == "true") && (User.Identity.GetUserId() != null)) //connet donation to user as long as there is actually a logged in user { var manager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(_context)); var currentUser = manager.FindById(User.Identity.GetUserId()); donation = new DbTables.Donations { Amount = amount, Description = description, anonymous = false, User = currentUser }; recieptname = currentUser.Fname + " " + currentUser.Lname; recieptemail = currentUser.Email; } else { donation = new DbTables.Donations //information has been given { Amount = amount, Email = email, Phone = phone, City = city, StreetAdress = streetadress, ZipCode = postcode, BirthNumber = birthnumber, Name = name, Description = description, anonymous = false }; recieptemail = email; recieptname = name; } _context.Donations.Add(donation); _context.SaveChanges(); // Process payment. var client = new WebClient(); var data = new NameValueCollection(); data["amount"] = (amount * 100).ToString(CultureInfo.InvariantCulture); // Stripe charges are øre-based in NOK, so 100x the price. data["currency"] = "nok"; data["source"] = token; //the payment token with user's credidentials data["description"] = "Donasjon " + donation.Id + ": " + description; //description of donation. if (!string.IsNullOrEmpty(email)) { data["receipt_email"] = email; } else if (user == "true") { data["receipt_email"] = donation.User.Email; } client.UseDefaultCredentials = true; //use default credidentials for API request var stripeList = _context.StripeAPI.ToList(); //check if stripe actually exists in the database byte[] response; if (!stripeList.Any()) { return (Json( new { Error = "Stripe er ikke konfigurert for applikasjonen.", Succsess = "false", striperesponse = "false" })); //no stripe in database, return error } if (!stripeList.First().Enabeled) { return (Json( new { Error = "Stripe er avslått for applikasjonen.", Succsess = "false", striperesponse = "false" })); //stripe disabeled } client.Credentials = new NetworkCredential(_context.StripeAPI.ToList().First().Secret, ""); try { response = client.UploadValues("https://api.stripe.com/v1/charges", "POST", data); // upload values and get response } catch (WebException exception) //exepction happen when poisting to API { string responseString; using (var reader = new StreamReader(exception.Response.GetResponseStream())) //read the errorstring { responseString = reader.ReadToEnd(); } return(Json(new { Error = responseString, Success = "false", striperesponse = "true" })); // return responsestring as error message } /*var json_serializer = new JavaScriptSerializer(); * var JsonDict = (IDictionary<string, object>)json_serializer.DeserializeObject(client.Encoding.GetString(response));*/ //These lines parses the respone, which is at the moment not used for anything // If we got this far, there were no errors, and we set the order to paid, and save. Response.StatusCode = 200; donation.isPaid = true; //change element to paid _context.SaveChanges(); //save db if (!string.IsNullOrEmpty(recieptemail)) //send reciept email if reciept email is given { var subject = "Kvitering på donasjon"; var message = "Takk for din støtte! \n Du har donert " + amount + " kroner til Butterfly Friends. \n" + "Ditt referansenummer er " + donation.Id + ". \n\n" + "Vennlig hilsen,\nButterfly Friends."; var messageHTML = "<p>Takk for din støtte! <br> Du har donert " + amount + " kroner til Butterfly Friends. <br>" + "Ditt referansenummer er " + donation.Id + ". <br><br>" + "Vennlig hilsen,<br>Butterfly Friends.</p>"; if (!SendEmail(message, messageHTML, subject, recieptemail, recieptname)) { //returns true if sending of email was succsessful ViewBag.Error = "Emailkviteringen kunne ikke sendes, Sendgrid er ikke konfigurert."; } } ViewBag.Share = "https://www." + Request.Url.Host + "/Home/Index"; //share link for twitter ViewBag.ShareText = "Jeg har donert " + amount + " kr. til Butterfly Friends!"; //share message var TwitterList = _context.Twitter.ToList(); //check if facebook and twitter exist var Twitter = new DbTables.Twitter(); if (TwitterList.Any()) { Twitter = TwitterList.First(); } var FacebookList = _context.Facebook.ToList(); var Facebook = new DbTables.Facebook(); if (FacebookList.Any()) { Facebook = FacebookList.First(); } var model = new RecieptModel { Facebook = Facebook, Twitter = Twitter, Donation = donation }; return(PartialView("_RecieptPartial", model)); //return reciept view }