public ActionResult Redirect(int userId) { ViewBag.UserId = userId; ViewBag.ErrorDetails = "Something went wrong with payment"; // --- Перетворюю відповідь LiqPay в Dictionary<string, string> для зручності: var request_dictionary = Request.Form.AllKeys.ToDictionary(key => key, key => Request.Form[key]); // --- Розшифровую параметр data відповіді LiqPay та перетворюю в Dictionary<string, string> для зручності: byte[] request_data = Convert.FromBase64String(request_dictionary["data"]); string decodedString = Encoding.UTF8.GetString(request_data); var request_data_dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(decodedString); // --- Отримую сигнатуру для перевірки var mySignature = LiqPayHelper.GetLiqPaySignature(request_dictionary["data"]); // --- Якщо сигнатура серевера не співпадає з сигнатурою відповіді LiqPay - щось пішло не так if (mySignature != request_dictionary["signature"]) return View("~/Views/Shared/Error.cshtml"); // --- Якщо статус відповіді "Тест" або "Успіх" - все добре if (request_data_dictionary["status"] == "sandbox" || request_data_dictionary["status"] == "success") { // Тут можна оновити статус замовлення та зробити всі необхідні речі. Id замовлення можна взяти тут: request_data_dictionary[order_id] // ... return View("Thanks"); } return View("~/Views/Shared/Error.cshtml"); }
public ActionResult AcceptAppointment(int?id, int?serviceId) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } Record record = db.Records.Find(id); record.TypeOfServiceId = serviceId; TypeOfService typeOfService = db.TypeOfServices.Where(u => u.Id == serviceId).FirstOrDefault(); ApplicationUser Patient = db.Users.Find(User.Identity.GetUserId()); Payment payment = new Payment() { RecordId = record.Id, PatientId = Patient.Id, amount = typeOfService.Price, order_id = Guid.NewGuid().ToString() }; ViewBag.Patient = Patient; ViewBag.Payment = payment; ViewBag.Record = record; db.Payments.Add(payment); db.SaveChanges(); return(View("Payment", LiqPayHelper.GetLiqPayModel(payment, typeOfService, Patient))); }
public ActionResult UpdatePayedReception() { var requestDictionary = Request.Form.Keys.ToDictionary(key => key, key => Request.Form[key]); var requestData = Convert.FromBase64String(requestDictionary["data"]); var decodedString = Encoding.UTF8.GetString(requestData); var requestDataDictionary = JsonConvert.DeserializeObject <Dictionary <string, string> >(decodedString); var signature = LiqPayHelper.GetLiqPaySignature(requestDictionary["data"]); if (signature != requestDictionary["signature"]) { return(BadRequest()); } if (requestDataDictionary["status"] == "sandbox" || requestDataDictionary["status"] == "success") { var receptionToUpdate = _context.Receptions.FirstOrDefault(r => r.PaymentId == requestDataDictionary["order_id"]); if (receptionToUpdate != null) { receptionToUpdate.IsPayed = true; _context.Entry(receptionToUpdate).State = EntityState.Modified; _context.SaveChangesAsync(); } } return(Ok(new object())); }
public ActionResult Redirect() { // --- Перетворюю відповідь LiqPay в Dictionary<string, string> для зручності: var request_dictionary = Request.Form.AllKeys.ToDictionary(key => key, key => Request.Form[key]); // --- Розшифровую параметр data відповіді LiqPay та перетворюю в Dictionary<string, string> для зручності: byte[] request_data = Convert.FromBase64String(request_dictionary["data"]); string decodedString = Encoding.UTF8.GetString(request_data); var request_data_dictionary = JsonConvert.DeserializeObject <Dictionary <string, string> >(decodedString); // --- Отримую сигнатуру для перевірки var mySignature = LiqPayHelper.GetLiqPaySignature(request_dictionary["data"]); // --- Якщо сигнатура серевера не співпадає з сигнатурою відповіді LiqPay - щось пішло не так if (mySignature != request_dictionary["signature"]) { return(View("~/Views/Shared/_Error.cshtml")); } // --- Якщо статус відповіді "Тест" або "Успіх" - все добре if (request_data_dictionary["status"] == "sandbox" || request_data_dictionary["status"] == "success") { // Тут можна оновити статус замовлення та зробити всі необхідні речі. Id замовлення можна взяти тут: request_data_dictionary[order_id] // ... var ord = DatAcessService.FindOrder(Convert.ToInt32(request_data_dictionary["order_id"])); ord.Status = "Payed"; return(View("~/Views/Shared/SuccessPayment.cshtml")); } return(View("~/Views/Shared/Error.cshtml")); }
public ActionResult LiqPayCallback() { LiqPayHelper liqPayHelper = new LiqPayHelper(ConfigurationManager.AppSettings["LiqPayPrivateKey"], ConfigurationManager.AppSettings["LiqPayPublicKey"]); // --- Перетворюю відповідь LiqPay в Dictionary<string, string> для зручності: var request_dictionary = Request.Form.AllKeys.ToDictionary(key => key, key => Request.Form[key]); // --- Розшифровую параметр data відповіді LiqPay та перетворюю в Dictionary<string, string> для зручності: byte[] request_data = Convert.FromBase64String(request_dictionary["data"]); string decodedString = Encoding.UTF8.GetString(request_data); var request_data_dictionary = JsonConvert.DeserializeObject <Dictionary <string, string> >(decodedString); // --- Отримую сигнатуру для перевірки var mySignature = liqPayHelper.GetLiqPaySignature(request_dictionary["data"]); // --- Якщо сигнатура серевера не співпадає з сигнатурою відповіді LiqPay - щось пішло не так if (mySignature != request_dictionary["signature"]) { return(View("PurchaseError")); } //return new HttpStatusCodeResult(HttpStatusCode.BadRequest); string order_id = request_data_dictionary["order_id"]; Order order = orderRepository.FindBy(x => x.TestIdForLiqpay == order_id).FirstOrDefault(); if (order == null) { return(View("PurchaseError")); } //new HttpStatusCodeResult(HttpStatusCode.BadRequest); // --- Якщо статус відповіді "Тест" або "Успіх" - все добре if (request_data_dictionary["status"] == "sandbox" || request_data_dictionary["status"] == "success") { // Тут можна оновити статус замовлення та зробити всі необхідні речі. Id замовлення можна взяти тут: request_data_dictionary[order_id] foreach (var item in order.OrderItems) { item.Ticket.StatusId = 1; } order.OrderStatusId = 1; order.PurchaseDate = DateTime.Now; orderRepository.AddOrUpdate(order); orderRepository.Save(); return(View("PurchaseSuccess", order)); } // delete tickets foreach (var item in order.OrderItems) { if (item.Ticket != null) { ticketRepository.Delete(item.Ticket); } } ticketRepository.Save(); TicketHub.NotifyToAllClients(); return(View("PurchaseError")); }
public ActionResult CancelReception(int?recordId) { ApplicationUser mainUser = db.Users.Find(User.Identity.GetUserId()); Record record = db.Records.Find(recordId); Payment payment = db.Payments.Where(p => p.RecordId == recordId && (p.status == "sandbox" || p.status == "success")).FirstOrDefault(); return(View(LiqPayHelper.GetLiqPayRefund(payment))); }
public ActionResult PayTheBill(string orderId) { var ord = DatAcessService.FindOrder(Convert.ToInt32(orderId)); ord.Status = "Payed"; DatAcessService.CreateOrder(ord); return(View(LiqPayHelper.GetLiqPayModel(orderId))); }
public LiqPayCheckoutModel GetLiqPayCheckoutModel(string donationAmount, int?projectId, HttpContext context) { try { return(LiqPayHelper.GetLiqPayCheckoutModel(donationAmount, projectId, context)); } catch (Exception ex) { throw new Exception($"Error while generation a request to LiqPay platform, {nameof(donationAmount)} or {nameof(projectId)} is invalid ", ex); } }
public ActionResult BuyTickets(List <SelectedSeatsViewModel> selected_seats, int?session_id) { if (!IsValidSelectedSeats(selected_seats, session_id) || !ModelState.IsValid) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } // створюю список позицій замовлення (квитків) Session session = sessionRepository.FindBy(x => x.Id == session_id).FirstOrDefault(); List <OrderItem> orderItems = new List <OrderItem>(); foreach (var item in selected_seats) { TicketPrice ticketPrice = session.TicketPrices.FirstOrDefault(x => x.Seat.Row == item.Row && x.Seat.Number == item.Number); orderItems.Add(new OrderItem { Movie = session.Movie, Price = ticketPrice.Price, Ticket = new Ticket { SessionDateTime = session.DateTime, CreationDateTime = DateTime.Now, TicketPrice = ticketPrice, Seat = ticketPrice.Seat, StatusId = 3, // зарезервовано на 15хв } }); } // створюю замовлення та зберігаю його в бд ApplicationUserManager userMgr = new ApplicationUserManager(new UserStore <ApplicationUser>(context)); Order order = new Order { TestIdForLiqpay = Guid.NewGuid().ToString(), // ця властивість необхідна для тестування "лікпею" OrderItems = orderItems, OrderStatusId = 3, // статус "відхилено" поки користувач не заплатить User = userMgr.FindByName(User.Identity.Name), PurchaseDate = DateTime.Now }; orderRepository.AddOrUpdate(order); orderRepository.Save(); TicketHub.NotifyToAllClients(); // на основі створенго замовлення збираю необхідні для liqpay api дані та відправляю їх на в'ю LiqPayHelper liqPayHelper = new LiqPayHelper(ConfigurationManager.AppSettings["LiqPayPrivateKey"], ConfigurationManager.AppSettings["LiqPayPublicKey"]); string redirect_url = Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host + (Request.Url.IsDefaultPort ? "" : ":" + Request.Url.Port) + "/Order/LiqPayCallback"; var model = liqPayHelper.GetLiqPayModel(order, redirect_url); return(View(model)); }
public ActionResult <IEnumerable <PatientReceptionViewModel> > GetPatientsReceptions() { var patient = Utils.GetPatient(_caller, _context); var result = from reception in _context.Receptions join doctor in _context.Doctors on reception.DoctorId equals doctor.DoctorId where reception.PatientId == patient.PatientId orderby reception.Date select new PatientReceptionViewModel { ReceptionId = reception.ReceptionId, PatientId = reception.PatientId, DoctorId = reception.DoctorId, HospitalId = reception.HospitalId, Time = reception.Time, Duration = reception.Duration, FormatedDate = $"{reception.Date.Day}/{reception.Date.Month}/{reception.Date.Year}", DayOfWeek = reception.DayOfWeek, Address = reception.Address, Purpose = reception.Purpose, Result = reception.Result, Price = reception.Price, Name = doctor.Name, PaymentId = reception.PaymentId, IsPayed = reception.IsPayed }; var receptions = result.ToList(); for (var i = 0; i < receptions.Count; i++) { var paymentId = Guid.NewGuid().ToString(); var liqPayModel = LiqPayHelper.GetLiqPayModel(paymentId, Convert.ToInt32(receptions[i].Price)); receptions[i].Data = liqPayModel.Data; receptions[i].Signature = liqPayModel.Signature; var receptionToUpdate = _context.Receptions.Find(receptions[i].ReceptionId); receptionToUpdate.PaymentId = paymentId; _context.Entry(receptionToUpdate).State = EntityState.Modified; } _context.SaveChangesAsync(); return(Ok(receptions)); }
public IActionResult LiqPayResult() { var requestDictionary = Request.Form.Keys.ToDictionary(key => key, key => Request.Form[key]); var requestData = Convert.FromBase64String(requestDictionary["data"]); var decodedString = Encoding.UTF8.GetString(requestData); var requestDataDictionary = JsonConvert.DeserializeObject <Dictionary <string, string> >(decodedString); var mySignature = LiqPayHelper.GetLiqPaySignature(requestDictionary["data"]); if (!mySignature.Equals(requestDictionary["signature"])) { return(RedirectToAction("Completed", new { success = false, result = "ERROR" })); } var orderId = requestDataDictionary["order_id"]; var transactionId = requestDataDictionary["transaction_id"]; return(RedirectToAction("Completed", new { success = true, result = "Success", orderId, transactionId })); }
public async Task <ActionResult> Post(string donationId, int?projectId, [FromForm] string data, [FromForm] string signature) { if (string.IsNullOrEmpty(data)) { throw new ArgumentException($"{nameof(data)} can not be null"); } if (string.IsNullOrEmpty(signature)) { throw new ArgumentException($"{nameof(signature)} can not be null"); } string mySignature = LiqPayHelper.GetLiqPaySignature(data); if (mySignature != signature) { throw new Exception($"Error, while checking LiqPay response signature, the {nameof(signature)} was not authenticated "); } await _donationService.AddDonation(projectId, donationId, data, signature); return(Ok()); }
public IActionResult Cart(string items) { var cart = items .Split('|') .Select(int.Parse) .Distinct() .Select(x => Items.Find(i => i.Id == x)) .ToList(); var totalPrice = Convert.ToDecimal(cart.Sum(x => x.Price)); var(dataHash, signatureHash) = LiqPayHelper.GetLiqPayProcessedData(totalPrice, Guid.NewGuid().ToString(), "http://localhost:5000/Home/LiqPayResult"); var cartViewModel = new CartViewModel { Data = dataHash, Signature = signatureHash, Cart = cart }; return(View(cartViewModel)); }
public ActionResult Pay() { var request_dictionary = Request.Form.AllKeys.ToDictionary(key => key, key => Request.Form[key]); byte[] request_data = Convert.FromBase64String(request_dictionary["data"]); string decodedString = Encoding.UTF8.GetString(request_data); var request_data_dictionary = JsonConvert.DeserializeObject <Dictionary <string, string> >(decodedString); var mySignature = LiqPayHelper.GetLiqPaySignature(request_dictionary["data"]); if (mySignature != request_dictionary["signature"]) { return(RedirectToAction("UserPage", "Account", new { Message = ManageMessageId.Error })); } if (request_data_dictionary["status"] == "sandbox" || request_data_dictionary["status"] == "success") { var account = _accountService.GetUserAccount(User.Identity.GetUserId()); _accountService.AddToBalance(account.Id.ToString(), double.Parse(request_data_dictionary["amount"])); return(RedirectToAction("UserPage", "Account", new { Message = ManageMessageId.PaymentSuccess })); } return(RedirectToAction("UserPage", "Account", new { Message = ManageMessageId.Error })); }
public LiqPayCheckoutFormModel GetLiqPayModel(int doctorId) { return(LiqPayHelper.GetLiqPayModel(Guid.NewGuid().ToString(), Convert.ToInt32(_context.Doctors.First(d => d.DoctorId == doctorId).ReceptionPrice))); }
public ActionResult Index() { return(View(LiqPayHelper.GetLiqPayModel(Guid.NewGuid().ToString()))); }
public ActionResult Payment(int?amount) { return(View(LiqPayHelper.GetLiqPayModel(Guid.NewGuid().ToString(), amount.HasValue?amount.Value:100))); }
public async Task <ActionResult> AppointmentResult() { var request_dictionary = Request.Form.AllKeys.ToDictionary(key => key, key => Request.Form[key]); // --- Розшифровую параметр data відповіді LiqPay та перетворюю в Dictionary<string, string> для зручності: byte[] request_data = Convert.FromBase64String(request_dictionary["data"]); string decodedString = Encoding.UTF8.GetString(request_data); var request_data_dictionary = JsonConvert.DeserializeObject <Dictionary <string, string> >(decodedString); // --- Отримую сигнатуру для перевірки var mySignature = LiqPayHelper.GetLiqPaySignature(request_dictionary["data"]); // --- Якщо сигнатура серевера не співпадає з сигнатурою відповіді LiqPay - щось пішло не так if (mySignature != request_dictionary["signature"]) { return(View("~/Views/Shared/_Error.cshtml")); } // --- Якщо статус відповіді "Тест" або "Успіх" - все добре if (request_data_dictionary["status"] == "sandbox" || request_data_dictionary["status"] == "success") { Payment payment = db.Payments.Find(request_data_dictionary["order_id"]); Record record = db.Records.Find(payment.RecordId); payment.status = request_data_dictionary["status"]; record.PatientId = payment.PatientId; db.SaveChanges(); // настройка логина, пароля отправителя var from = "*****@*****.**"; var pass = "******"; // создаем письмо: message.Destination - адрес получателя var emailMessage = new MimeMessage() { Subject = "eLife підтвердження запису", Body = new TextPart(MimeKit.Text.TextFormat.Html) { Text = "<h2> " + record.Patient.Name + " , ви успішно записались на прийом" + " </h2> <br>" + "Лікар:" + record.AttendingDoctor.Name + " <br>" + " Клініка:" + record.AttendingDoctor.DoctorInform.Clinic.Name + " < br > " + " Дата та час:" + record.Date + " < br > " + " Вид прийому:" + record.TypeOfService.Name + " < br > " } }; emailMessage.From.Add(new MailboxAddress("Администрация сайта", from)); emailMessage.To.Add(new MailboxAddress("", record.Patient.Email)); // адрес и порт smtp-сервера, с которого мы и будем отправлять письмо using (var client = new SmtpClient()) { await client.ConnectAsync("smtp.gmail.com", 465); await client.AuthenticateAsync(from, pass); await client.SendAsync(emailMessage); await client.DisconnectAsync(true); } ViewBag.Type = record.TypeOfService.Name; return(View(record)); } return(View("~/Views/Shared/_Error.cshtml")); }
// GET: Payment public ActionResult Index(int userId) { return View(LiqPayHelper.GetLiqPayModel(Guid.NewGuid().ToString(), userId)); }