public ActionResult ConfirmOrder() { string token = Request["token"]; RequestCheckOrder info = new RequestCheckOrder(); info.Merchant_id = _merchantId; info.Merchant_password = _merchantPassword; info.Token = token; APICheckoutV3 objNLChecout = new APICheckoutV3(); ResponseCheckOrder result = objNLChecout.GetTransactionDetail(info); if (result.errorCode == "00") { //update status order _orderService.UpdateStatus(int.Parse(result.order_code)); _orderService.Save(); ViewBag.IsSuccess = true; ViewBag.Result = "Thanh toán thành công. Chúng tôi sẽ liên hệ lại sớm nhất."; } else { ViewBag.IsSuccess = true; ViewBag.Result = "Có lỗi xảy ra. Vui lòng liên hệ admin."; } return(View()); }
//Khi thanh toán Ngan Luong XOng public ActionResult confirm_orderPaymentOnline() { String Token = Request["token"]; RequestCheckOrder info = new RequestCheckOrder(); info.Merchant_id = nganluongInfo.Merchant_id; info.Merchant_password = nganluongInfo.Merchant_password; info.Token = Token; APICheckoutV3 objNLChecout = new APICheckoutV3(); ResponseCheckOrder result = objNLChecout.GetTransactionDetail(info); if (result.errorCode == "00") { String codeOrder = Session["OrderId"].ToString(); var OrderInfo = db.Orders.OrderByDescending(m => m.code == codeOrder).FirstOrDefault(); OrderInfo.StatusPayment = 1; db.Entry(OrderInfo).State = EntityState.Modified; db.SaveChanges(); ViewBag.paymentStatus = OrderInfo.StatusPayment; ViewBag.Methodpayment = OrderInfo.deliveryPaymentMethod; return(View("oderComplete", OrderInfo)); } else { ViewBag.status = false; } return(View("confirm_orderPaymentOnline")); }
public ActionResult PaymentReturn(string token, string key, int type = 0) { string result; //DEBUG //Logger.GetInstance().Write("Payment Return URL:"); //Logger.GetInstance().Write(Request.Url.AbsoluteUri.ToString()); if (type == ReturnType.Cancel.GetHashCode() || type == ReturnType.Timeout.GetHashCode() || string.IsNullOrEmpty(key) || string.IsNullOrEmpty(token)) { result = DbContext.CancelUrl(key); return(Redirect(result)); } var db = new DbContext(); var details = db.GetDetails(key); if (details != null && details.ProviderTransRefId == token) { var info = new RequestCheckOrder(); info.Merchant_id = ConfigCode.GetInstance().MerchantID; info.Merchant_password = ConfigCode.GetInstance().MerchantPassword; info.Token = token; var objApiCheckout = new APICheckoutV3(); ResponseCheckOrder checkOrderRs = objApiCheckout.GetTransactionDetail(info); //DEBUG //Logger.GetInstance().Write("Transaction details:"); // Logger.GetInstance().Write(JsonConvert.SerializeObject(checkOrderRs)); switch (checkOrderRs.transactionStatus) { case "00": details.PaymentStatus = EnumPaymentStatus.Paid.GetHashCode(); break; case "01": details.PaymentStatus = EnumPaymentStatus.Pending.GetHashCode(); break; case "02": details.PaymentStatus = EnumPaymentStatus.Unpaid.GetHashCode(); break; } var updateRs = db.SetDetails(key, details); // Build the success url and redirect back to Arcadier result = DbContext.SuccessUrl(key, ""); return(Redirect(result)); } else { // Build the failure url and redirect back to Arcadier result = DbContext.CancelUrl(key); return(Redirect(result)); } }
public JsonResult GetLinkNl(string paymentMethod, string strBankcode, string name, string email, string mobile, int uid, string money) { var info = new RequestInfo { Merchant_id = ConfigWeb.MerchantId, Merchant_password = ConfigWeb.MerchantPassword, Receiver_email = ConfigWeb.ReceiverEmail, cur_code = "vnd", bank_code = strBankcode, Order_code = DateTime.Now.Ticks + "-UID:" + uid, Total_amount = money, fee_shipping = "0", Discount_amount = "0", order_description = "Thanh toan SDT : " + mobile, return_url = ConfigWeb.ReturnUrl, cancel_url = ConfigWeb.CancelUrl, Buyer_fullname = name, Buyer_email = email, Buyer_mobile = mobile, Payment_type = "1" // Thanh toan ngay }; var objNlChecout = new APICheckoutV3(); var result = objNlChecout.GetUrlCheckout(info, paymentMethod); if (result.Error_code == "00") { var objPayment = new PaymentItem { buyer_uid = uid, buyer_fullname = info.Buyer_fullname, buyer_mobile = info.Buyer_mobile, total_amount = Convert.ToInt32(info.Total_amount), order_code = info.Order_code, payment_method = info.Payment_method, bank_code = info.bank_code, payment_type = info.Payment_type, transaction_status = "01", token = result.Token, time_request = DateTime.Now, time_receive = DateTime.Now }; _iGamePlayerRepository.InsertPayment(objPayment); return(Json(new { content = result.Checkout_url, error = false }, JsonRequestBehavior.AllowGet)); } return(Json(new { content = result.Description, error = false }, JsonRequestBehavior.AllowGet)); }
public async System.Threading.Tasks.Task <ActionResult> GetProvidership(NganLuongPaymentModel nganLuongPayment) { // Check if the request contains all valid params int plan; if (nganLuongPayment?.OrderCode == null || !int.TryParse(nganLuongPayment.OrderCode, out plan) || !Constants.PROVIDER_PLAN.Contains(plan)) { return(new HttpStatusCodeResult(400, "Invalid request")); } // Get current user var customerID = User.Identity.GetUserId(); var userService = this.Service <IUserService>(); var user = await userService.GetAsync(customerID); // Calculate the date of IsProviderUntil // We will save it into Order_code and then get it back on success // To validate and set the new IsProviderUntil of user DateTime newIsProviderUntil; if (user.IsProviderUntil == null || user.IsProviderUntil < DateTime.Now) { newIsProviderUntil = DateTime.Now.AddDays(30 * plan); } else { newIsProviderUntil = user.IsProviderUntil.Value.AddDays(30 * plan); } // validate nganluong params before redirect to nganluong var info = new RequestInfoTestTemplate { bank_code = nganLuongPayment.BankCode, Order_code = user.Id + " - " + newIsProviderUntil.ToString(), order_description = "Test becomeProvider, plan = " + plan + "months", return_url = "http://localhost:65358/becomeProvider/success", cancel_url = "http://localhost:65358/", Buyer_fullname = user.FullName, Buyer_email = user.Email, Buyer_mobile = user.PhoneNumber }; var objNLCheckout = new APICheckoutV3(); var result = objNLCheckout.GetUrlCheckout(info, nganLuongPayment.PaymentMethod); if (result.Error_code == "00") { return(Redirect(result.Checkout_url)); } return(new HttpStatusCodeResult(400, "Invalid request")); }
protected void Page_Load(object sender, EventArgs e) { String Token = Request["token"]; RequestCheckOrder info = new RequestCheckOrder(); info.Merchant_id = "24338"; info.Merchant_password = "******"; info.Token = Token; APICheckoutV3 objNLChecout = new APICheckoutV3(); ResponseCheckOrder result = objNLChecout.GetTransactionDetail(info); result_NL.Text = result.errorCode + result.payerName; }
/// <summary> /// Get info then redirect to NganLuong /// </summary> /// <param name="inputData"></param> /// <returns></returns> public ActionResult CheckOutNganLuong(NganLuongCheckOut inputData) { //get data from form string payment_method = inputData.option_payment; string str_bankcode = inputData.bankcode; bool isPublic = inputData.isPublic != "0"; var numberofMoney = inputData.numberMoney == "0" ? inputData.inputMoney : inputData.numberMoney; //set data to nganluongAPI RequestInfo info = new RequestInfo { Merchant_id = WsConstant.NganLuongApi.MerchantId, Merchant_password = WsConstant.NganLuongApi.Password, Receiver_email = WsConstant.NganLuongApi.AdminEmail, cur_code = "vnd", bank_code = str_bankcode, Order_code = "chuyen_khoan_ung_ho", Total_amount = numberofMoney, fee_shipping = "0", Discount_amount = "0", order_description = "Chuyển tiền ủng hộ thông qua Ngân Lượng", return_url = "http://localhost:2710/#/DonationComplete", cancel_url = "http://localhost:2710/#/DonationFailed", Buyer_fullname = inputData.buyer_fullname, Buyer_email = inputData.buyer_email, Buyer_mobile = inputData.buyer_mobile }; APICheckoutV3 objNLChecout = new APICheckoutV3(); ResponseInfo result = objNLChecout.GetUrlCheckout(info, payment_method); //get and set data to session var newDonate = new DonationDTO(); newDonate.IsPublic = isPublic; newDonate.DonatedMoney = decimal.Parse(numberofMoney); newDonate.TradeCode = result.Token; newDonate.UserId = inputData.DonateUserId; newDonate.EventId = inputData.DonateEventId; newDonate.Content = inputData.DonateContent; Session["DonatedInfo"] = newDonate; //return to checkout page or error page if (result.Error_code == "00") { return(Redirect(result.Checkout_url)); //return Redirect("http://localhost:2710/#/DonationComplete"); //return Redirect("http://localhost:2710/#/DonationFailed"); } else { return(PartialView("~/Views/Error/_Error.cshtml")); } }
public string NganLuong(string fullname, string mobile, string email, string total) { string payment_method = "VISA"; string str_bankcode = "1234567890"; RequestInfo info = new RequestInfo(); info.Merchant_id = "36680"; info.Merchant_password = "******"; info.Receiver_email = "*****@*****.**"; info.cur_code = "vnd"; info.bank_code = str_bankcode; info.Order_code = "ma_don_hang01"; //info.Total_amount = "10000"; info.Total_amount = total; info.fee_shipping = "0"; info.Discount_amount = "0"; info.order_description = "Thanh toan tes thu dong hang"; info.return_url = "http://localhost"; info.cancel_url = "http://localhost"; //info.Buyer_fullname = buyer_fullname.Value; //info.Buyer_email = buyer_email.Value; //info.Buyer_mobile = buyer_mobile.Value; info.Buyer_fullname = fullname; info.Buyer_email = email; info.Buyer_mobile = mobile; APICheckoutV3 objNLChecout = new APICheckoutV3(); ResponseInfo result = objNLChecout.GetUrlCheckout(info, payment_method); if (result.Error_code == "00") { //return Redirect(result.Checkout_url); return(result.Checkout_url); } else { //return Redirect(info.cancel_url); return(info.cancel_url); } }
public ActionResult ThanhToanThanhCong() { var model = new PaymentItem(); var status = Request["error_code"]; var token = Request["token"]; if (status == "00") { var objCheck = new RequestCheckOrder { Merchant_id = ConfigWeb.MerchantId, Merchant_password = ConfigWeb.MerchantPassword, Token = token }; var objNlChecout = new APICheckoutV3(); var detailResult = objNlChecout.GetTransactionDetail(objCheck); var detailPayment = _iGamePlayerRepository.GetDetailPaymentByToken(detailResult.token); if (detailPayment != null && detailPayment.transaction_status != "00" && detailResult.transactionStatus == "00") { detailPayment.total_amount = Convert.ToInt32(detailResult.paymentAmount); detailPayment.transaction_status = detailResult.transactionStatus; detailPayment.transaction_id = detailResult.transactionId; detailPayment.time_receive = DateTime.Now; var updatePayment = _iGamePlayerRepository.UpdatePayment(detailPayment); if (ConfigWeb.PercentSale > 0) { detailPayment.total_amount = detailPayment.total_amount + (detailPayment.total_amount / ConfigWeb.PercentSale); } if (detailResult.transactionStatus == "00") { var updateMoney = _iGamePlayerRepository.InsertMoney(detailPayment); } } return(View(detailPayment)); } return(View(model)); }
protected void Button1_Click(object sender, EventArgs e) { string payment_method = Request.Form["option_payment"]; string str_bankcode = Request.Form["bankcode"]; RequestInfo info = new RequestInfo(); info.Merchant_id = "36680"; info.Merchant_password = "******"; info.Receiver_email = "*****@*****.**"; info.cur_code = "vnd"; info.bank_code = str_bankcode; info.Order_code = "ma_don_hang01"; info.Total_amount = "10000"; info.fee_shipping = "0"; info.Discount_amount = "0"; info.order_description = "Thanh toan tes thu dong hang"; info.return_url = "http://localhost"; info.cancel_url = "http://localhost"; info.Buyer_fullname = buyer_fullname.Value; info.Buyer_email = buyer_email.Value; info.Buyer_mobile = buyer_mobile.Value; APICheckoutV3 objNLChecout = new APICheckoutV3(); ResponseInfo result = objNLChecout.GetUrlCheckout(info, payment_method); if (result.Error_code == "00") { Response.Redirect(result.Checkout_url); } else { txtserverkt.InnerHtml = result.Description; } }
public ActionResult NLCallback(String Token) { AnperoService ws = new AnperoService(); PaymentConfig[] pc = ws.GetPaymentAPIConfig(StoreID, TokenKey); if (pc != null && pc.Length > 0) { for (int i = 0; i < pc.Length; i++) { if (pc[i].Name.ToUpper() == "NL") { RequestCheckOrder info = new RequestCheckOrder(); //for test //info.Merchant_id = "24338"; //info.Merchant_password = "******"; info.Merchant_id = pc[i].MerchantId; info.Merchant_password = pc[i].MerchantPassword; info.Token = Token; APICheckoutV3 objNLChecout = new APICheckoutV3(); ResponseCheckOrder result = objNLChecout.GetTransactionDetail(info); string rs = "Giao dịch Thành công, đơn hàng của quý khách đang được xử lý nhanh chóng"; rs += result.description; rs += "<br>"; rs += "Số tiền thanh toán: " + result.paymentAmount; rs += "<br>"; rs += "Mã giao dịch Ngân Lượng: " + result.transactionId; rs += "<br>"; rs += "Mã đơn hàng: " + result.order_code; rs += "<br>"; rs += "Tên người thanh toán: " + result.payerName; //update and add cash book ws.UpdateOrderStatus(StoreID, TokenKey, Convert.ToInt32(result.order_code), Convert.ToInt32(result.paymentAmount), "Ngân Lượng (Mã giao dịch Ngân Lượng " + result.transactionId + ")<br />" + rs); ViewBag.Msg = rs; } } } return(View("Index")); }
public ActionResult Success() { var order = new tbl_HoaDon(); String Token = Request["token"]; if (Token != null) { long orderID = long.Parse(Request["Order_code"]); RequestCheckOrder info = new RequestCheckOrder(); info.Merchant_id = MerchantID; info.Merchant_password = MerchantPassword; info.Token = Token; APICheckoutV3 objNLChecout = new APICheckoutV3(); ResponseCheckOrder result = objNLChecout.GetTransactionDetail(info); ViewBag.Message = result.errorCode + result.payerName; order.ID = orderID; order.iStatus = 1; order.iMaTrangThai = 1; new HoaDonDAO().Update(order); } return(View()); }
public ActionResult DonationComplete() { try { //check exist DonatedInfo Session if (Session["DonatedInfo"] == null) { return(null); } else { //Get data in session and transactiondetail and return to view var newDonate = (DonationDTO)Session["DonatedInfo"]; newDonate.DonatedDate = DateTime.Now.ToString("hh:mm dd/MM/yy"); RequestCheckOrder info = new RequestCheckOrder(); info.Merchant_id = "48283"; info.Merchant_password = "******"; info.Token = newDonate.TradeCode; APICheckoutV3 objNLChecout = new APICheckoutV3(); ResponseCheckOrder result = objNLChecout.GetTransactionDetail(info); using (var db = new DonationDAL()) { db.AddNewDonation(newDonate); } using (var db = new EventDAL()) { newDonate.EventName = db.GetEventNameById(newDonate.EventId); } Session.Remove("DonatedInfo"); return(PartialView("~/Views/Donation/_DonationDone.cshtml", newDonate)); } } catch (Exception) { return(PartialView("~/Views/Error/_Error.cshtml")); } }
//Khi thanh toán Ngan Luong XOng public ActionResult confirm_orderPaymentOnline() { String Token = Request["token"]; RequestCheckOrder info = new RequestCheckOrder(); info.Merchant_id = nganluongInfo.Merchant_id; info.Merchant_password = nganluongInfo.Merchant_password; info.Token = Token; APICheckoutV3 objNLChecout = new APICheckoutV3(); ResponseCheckOrder result = objNLChecout.GetTransactionDetail(info); if (result.errorCode == "00") { var cart = Session[SessionCart]; var list = new List <Cart_item>(); ViewBag.cart = (List <Cart_item>)cart; Session["SessionCart"] = null; var OrderInfo = db.Orders.OrderByDescending(m => m.ID).FirstOrDefault(); ViewBag.name = OrderInfo.deliveryname; ViewBag.email = OrderInfo.deliveryemail; ViewBag.address = OrderInfo.deliveryaddress; ViewBag.code = OrderInfo.code; ViewBag.phone = OrderInfo.deliveryphone; OrderInfo.StatusPayment = 1; db.Entry(OrderInfo).State = EntityState.Modified; db.SaveChanges(); ViewBag.paymentStatus = OrderInfo.StatusPayment; ViewBag.Methodpayment = OrderInfo.deliveryPaymentMethod; return(View("payment")); } else { ViewBag.status = false; } return(View("confirm_orderPaymentOnline")); }
public IActionResult ExecutePayment(string buyer_fullname, string buyer_email, string buyer_mobile, string option_payment, string bankcode) { string payment_method = option_payment; string str_bankcode = bankcode; RequestInfo info = new RequestInfo(); info.Merchant_id = "48305"; info.Merchant_password = "******"; info.Receiver_email = "*****@*****.**"; //mk nl ac1d19ab3a0450d7b6d0c3b885448a86 // secrrt d0c398afaa9c40c3abffc82127a38354 //api b6dc94eff0e64a3cafbe6927921bfe03 info.cur_code = "vnd"; info.bank_code = str_bankcode; //int id_new = db.HoaDon.Max(m => m.MaHd) + 1; DateTime currentDate = DateTime.Now; // Voucher voucher = db.Voucher.SingleOrDefault(s => s.NgayBatDau <= currentDate && s.NgayHetHan >= currentDate); double giamGia = 0; // if (voucher != null) // { // giamGia = (double)voucher.GiamGia; //} double totalAmount = 0; totalAmount = Double.Parse(HttpContext.Session.GetString("TongTien")); info.Order_code = "1";//(id_new + 1).ToString(); info.Total_amount = totalAmount.ToString(); info.fee_shipping = "0"; info.Discount_amount = giamGia.ToString(); info.order_description = "Thanh toan test thu dong hang"; info.return_url = "http://web42shop10.somee.com/Checkout/NganLuongPaid/?orderid=" + HttpContext.Session.GetInt32("OrderId").ToString(); info.cancel_url = "http://calhost:44138"; info.Buyer_fullname = buyer_fullname; info.Buyer_email = buyer_email; info.Buyer_mobile = buyer_mobile; APICheckoutV3 objNLChecout = new APICheckoutV3(); ResponseInfo result = objNLChecout.GetUrlCheckout(info, payment_method); if (result.Error_code == "00") { //SaveOrder(totalAmount, "nganluong"); return(Redirect(result.Checkout_url)); //Response.Redirect(result.Checkout_url); } else { return(View()); } // txtserverkt.InnerHtml = result.Description; }
public ActionResult ExecutePayment(string buyer_fullname, string buyer_email, string buyer_mobile, string option_payment, string bankcode) { string payment_method = option_payment; string str_bankcode = bankcode; RequestInfo info = new RequestInfo(); info.Merchant_id = "48305"; info.Merchant_password = "******"; info.Receiver_email = "*****@*****.**"; //mk nl ac1d19ab3a0450d7b6d0c3b885448a86 // secrrt d0c398afaa9c40c3abffc82127a38354 //api b6dc94eff0e64a3cafbe6927921bfe03 info.cur_code = "vnd"; info.bank_code = str_bankcode; //int id_new = db.HoaDon.Max(m => m.MaHd) + 1; DateTime currentDate = DateTime.Now; // Voucher voucher = db.Voucher.SingleOrDefault(s => s.NgayBatDau <= currentDate && s.NgayHetHan >= currentDate); double giamGia = 0; // if (voucher != null) // { // giamGia = (double)voucher.GiamGia; //} double tt = (double)Session["Total"]; double tygiaUSD = 0; using (THUONGMAIDIENTUEntities db = new THUONGMAIDIENTUEntities()) { var TG = db.TYGIAUSDs.FirstOrDefault(); tygiaUSD = (double)TG.tygia; } double totalAmount = Session["Total"].ToInt() * tygiaUSD; info.Order_code = "1";//(id_new + 1).ToString(); info.Total_amount = totalAmount.ToString(); info.fee_shipping = "0"; info.Discount_amount = giamGia.ToString(); info.order_description = "Thanh toan test thu dong hang"; //info.return_url = "https://cosmeticshop20.azurewebsites.net/Checkout/NganLuongPaid/?orderid=" + HttpContext.Session.GetInt32("OrderId").ToString(); //info.return_url = BaseURL.GetURL(); info.return_url = "http://m-store.store/" + "/cart/Thanhcong"; info.cancel_url = "http://m-store.store/" + "cart/Cancel/"; info.Buyer_fullname = buyer_fullname; info.Buyer_email = buyer_email; info.Buyer_mobile = buyer_mobile; APICheckoutV3 objNLChecout = new APICheckoutV3(); ResponseInfo result = objNLChecout.GetUrlCheckout(info, payment_method); if (result.Error_code == "00") { //SaveOrder(totalAmount, "nganluong"); return(Redirect(result.Checkout_url)); //Response.Redirect(result.Checkout_url); } else { return(View()); } // txtserverkt.InnerHtml = result.Description; }
public ActionResult CreateOrder(string orderViewModel) { var order = new JavaScriptSerializer().Deserialize <OrderViewModel>(orderViewModel); var orderNew = new Order(); orderNew.UpdateOrder(order); if (Request.IsAuthenticated) { orderNew.CustomerId = User.Identity.GetUserId(); orderNew.CreatedBy = User.Identity.GetUserName(); } var cart = GetCart(); List <OrderDetail> orderDetails = new List <OrderDetail>(); foreach (var item in cart) { var detail = new OrderDetail(); detail.ProductID = item.ProductId; detail.Quantity = item.Quantity; detail.Price = item.Product.Price; orderDetails.Add(detail); _productService.SellProduct(item.ProductId, item.Quantity); } var orderReturn = _orderService.Create(ref orderNew, orderDetails); _orderService.Save(); // get ID Order. TempData["OrderID"] = orderReturn.ID; if (order.PaymentMethod == "CASH") { _orderService.Save(); return(Json(new { status = true, data = "CASH" })); } else { var currentLink = ConfigHelper.GetByKey("CurrentLink"); RequestInfo info = new RequestInfo(); info.Merchant_id = _merchantId; info.Merchant_password = _merchantPassword; info.Receiver_email = _merchantEmail; info.cur_code = "vnd"; info.bank_code = order.BankCode; info.Order_code = orderReturn.ID.ToString(); info.Total_amount = orderDetails.Sum(x => x.Quantity * x.Price).ToString(); info.fee_shipping = "0"; info.Discount_amount = "0"; info.order_description = "Thanh toán đơn hàng tại BigShop"; info.return_url = currentLink + "xac-nhan-don-hang.html"; info.cancel_url = currentLink + "huy-don-hang.html"; info.Buyer_fullname = order.CustomerName; info.Buyer_email = order.CustomerEmail; info.Buyer_mobile = order.CustomerMobile; APICheckoutV3 objNLChecout = new APICheckoutV3(); ResponseInfo result = objNLChecout.GetUrlCheckout(info, order.PaymentMethod); if (result.Error_code == "00") { return(Json(new { status = true, urlCheckout = result.Checkout_url, message = result.Description })); } else { return(Json(new { status = false, message = result.Description })); } } }
public async Task <IActionResult> Checkout([FromForm] ShippingInfo shippingInfo, CancellationToken requestAborted) { if (_cart.LineItems.Count() == 0) { ModelState.AddModelError("", "Sorry, your cart is empty!"); } var formCollection = await HttpContext.Request.ReadFormAsync(); if (ModelState.IsValid) { shippingInfo.LineItems = _cart.LineItems; await _repository.SaveOrderAsync(shippingInfo); var currentLink = "http://localhost:17352/"; RequestInfo info = new RequestInfo(); info.Merchant_id = merchantId; info.Merchant_password = merchantPassword; info.Receiver_email = merchantEmail; var money = shippingInfo.LineItems.Sum(e => e.Product.Price * e.Quanlity) * 20000; info.cur_code = "vnd"; info.bank_code = shippingInfo.BankCode; info.Order_code = shippingInfo.ShippingInfoID + "dasdasdas"; info.Total_amount = money + ""; info.fee_shipping = "0"; info.Discount_amount = "0"; info.order_description = "Thanh toán đơn hàng"; info.return_url = currentLink + "xac-nhan-don-hang.html"; info.cancel_url = currentLink + "huy-don-hang.html"; info.Buyer_fullname = shippingInfo.Name; info.Buyer_email = shippingInfo.Email; info.Buyer_mobile = shippingInfo.PhoneNumber; APICheckoutV3 objNLChecout = new APICheckoutV3(); ResponseInfo result = await objNLChecout.GetUrlCheckoutAsync(info); //ResponseInfo result = await objNLChecout.GetUrlCheckoutAsync(info, order.PaymentMethod); if (result.Error_code == "00") { return(Redirect(result.Checkout_url)); //return Json(new //{ // status = true, // urlCheckout = result.Checkout_url, // message = result.Description //}); } else { return(Json(new { status = false, message = result.Description, result = result.Error_code })); } // Save all changes // await dbContext.SaveChangesAsync(requestAborted); return(RedirectToAction(nameof(Completed))); } else { return(View(shippingInfo)); } }
public void ProcessRequest(HttpContext context) { string rs = "0"; try { string op = context.Request["op"].ToLower(); string captcha = context.Request["captcha"]; int price = Convert.ToInt32(context.Request["price"].Replace(@".", string.Empty).Replace(@".", string.Empty)); int orderId = Convert.ToInt32(context.Request["orderId"].Replace(@",", string.Empty)); string name = context.Request["name"]; string shipingFee = context.Request["shipingFee"]; string email = context.Request["email"]; string phone = context.Request["phone"]; Boolean valid = true; if (price <= 0 || orderId <= 0) { valid = false; rs = "Tiền thanh toán không hợp lệ"; } if (String.IsNullOrEmpty(captcha) && valid) { valid = false; rs = "Vui lòng click vào ô kiểm tra"; } if (valid) { AnperoService ws = new AnperoService(); int st = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["storeID"]); string TokenKey = System.Configuration.ConfigurationManager.AppSettings["storeTokenKey"]; PaymentConfig[] pa = ws.GetPaymentAPIConfig(st, TokenKey); switch (op.ToUpper()) { case "LN": if (pa != null && pa.Length > 0) { for (int i = 0; i < pa.Length; i++) { if (pa[i].Isdefault && pa[i].PaymentCode.ToUpper() == "NL") { string payment_method = context.Request["payment_method"]; string str_bankcode = context.Request["bankcode"]; string order_description = context.Request["detail"]; string DomainName = HttpContext.Current.Request.Url.Scheme + @"://" + HttpContext.Current.Request.Url.Host; Anpero.PaymentApi.NganLuong.RequestInfo info = new Anpero.PaymentApi.NganLuong.RequestInfo(); info.Merchant_id = pa[i].MerchantId.ToString(); info.Merchant_password = pa[i].MerchantPassword; //info.Merchant_id = "24338"; //info.Merchant_password = "******"; info.Receiver_email = pa[i].Email; info.cur_code = "vnd"; info.bank_code = str_bankcode; info.Order_code = orderId.ToString(); info.Total_amount = price.ToString(); info.fee_shipping = "0"; info.Discount_amount = "0"; info.order_description = order_description; info.return_url = DomainName + "/API/NLCallback"; info.cancel_url = DomainName + "/API/NLCancel"; info.Buyer_fullname = name; info.Buyer_email = email; info.Buyer_mobile = phone; APICheckoutV3 objNLChecout = new APICheckoutV3(); ResponseInfo result = objNLChecout.GetUrlCheckout(info, payment_method); if (result.Error_code == "00") { rs = result.Checkout_url; } else { rs = result.Description + " (" + result.Description + ")"; } } } } break; case "AL2": if (pa != null && pa.Length > 0) { for (int i = 0; i < pa.Length; i++) { if (pa[i].Isdefault && pa[i].PaymentCode.ToUpper() == "AL") { string order_description = context.Request["detail"]; string DomainName = HttpContext.Current.Request.Url.Scheme + @"://" + HttpContext.Current.Request.Url.Host; //DomainName = "https://demo3.anpero.com"; AlepayCheckout client = new AlepayCheckout(); AlepayInstallmentOrderModel data = new AlepayInstallmentOrderModel(); //AlepayOrderModel data = new AlepayOrderModel(); int month = 0; int.TryParse(context.Request["month"], out month); data.paymentMethod = context.Request["paymentMethod"]; if (month != 0) { data.month = month; } data.bankCode = context.Request["bankCode"]; data.amount = Convert.ToInt32(price); data.tokenKey = pa[i].Token; data.checkoutType = 2; data.returnUrl = DomainName + "/API/AlepayCallback"; data.orderCode = orderId.ToString(); data.orderDescription = order_description; data.cancelUrl = DomainName + "/API/NLCancel"; data.buyerEmail = email; data.buyerName = name; data.buyerAddress = context.Request["Address"]; data.buyerCountry = "Viet Nam"; data.buyerCity = "Viet Nam"; data.buyerPhone = phone; data.customMerchantId = orderId.ToString(); data.allowDomestic = false; data.installment = true; AlepayUltil alepayUltil = new AlepayUltil(); data.signature = alepayUltil.GetSignature(data, pa[i].ChecksumKey); var postData = client.GetRedirectUrl(data); if (!string.IsNullOrEmpty(postData.code) && Convert.ToInt32(postData.code) == 0) { rs = postData.checkoutUrl; } else { rs = postData.message; } } } } break; case "AL": if (pa != null && pa.Length > 0) { for (int i = 0; i < pa.Length; i++) { if (pa[i].Isdefault && pa[i].PaymentCode.ToUpper() == "AL") { string order_description = context.Request["detail"]; string DomainName = HttpContext.Current.Request.Url.Scheme + @"://" + HttpContext.Current.Request.Url.Host; //DomainName = "https://demo3.anpero.com"; AlepayCheckout client = new AlepayCheckout(); AlepayOrderModel data = new AlepayOrderModel(); data.amount = Convert.ToInt32(price); data.tokenKey = pa[i].Token; data.checkoutType = 4; data.returnUrl = DomainName + "/API/AlepayCallback"; data.orderCode = orderId.ToString(); data.orderDescription = order_description; data.cancelUrl = DomainName + "/API/NLCancel"; data.buyerEmail = email; data.buyerName = name; data.buyerAddress = context.Request["Address"]; data.buyerCountry = "Viet Nam"; data.buyerCity = "Viet Nam"; data.buyerPhone = phone; data.customMerchantId = orderId.ToString(); data.allowDomestic = true; AlepayUltil alepayUltil = new AlepayUltil(); data.signature = alepayUltil.GetSignature(data, pa[i].ChecksumKey); var postData = client.GetRedirectUrl(data); if (!string.IsNullOrEmpty(postData.code) && Convert.ToInt32(postData.code) == 0) { rs = postData.checkoutUrl; } else { rs = postData.message; } } } } break; default: break; } } } catch (Exception ex) { } context.Response.ContentType = "text/plain"; context.Response.Write(rs); }
public ActionResult Payment(string sTenNguoiNhan, string sEmail, string sSoDienThoai, string sDiaChi, string FormOfPayment, string sBankCode, FormCollection formcollection) { var order = new tbl_HoaDon(); var userSession = (UserLogin)Session[Common.CommonConstants.USER_SESSION]; var TenTinhThanh = formcollection["hdnTenTinhThanh"]; var TenQuanHuyen = formcollection["hdnTenQuanHuyen"]; string diachi = TenQuanHuyen + ", " + TenTinhThanh; if (userSession != null) { order.IDKhachHang = userSession.UserID; } order.dNgayTao = DateTime.Now; order.sTenNguoiNhan = sTenNguoiNhan; order.sEmailNguoiNhan = sEmail; order.sSDTnguoiNhan = sSoDienThoai; order.sDiaChi = sDiaChi + ", " + TenQuanHuyen + ", " + TenTinhThanh; order.sFormOfPayment = FormOfPayment; order.iMaTrangThai = 1; try { var id = new HoaDonDAO().Insert(order); var cart = (List <GioHangItems>)Session[CartSession]; var detailDao = new Model.DAO.ChiTietHoaDonDAO(); decimal total = 0; foreach (var item in cart) { var divsp = new SanPhamDAO(); var orderDetail = new tbl_ChiTietHoaDon(); orderDetail.IDSanPham = item.SanPham.ID; orderDetail.IDHoaDon = id; orderDetail.sGhiChu = item.sGhiChu; orderDetail.iSoLuong = item.SoLuong; if (item.SanPham.dGiaKhuyenMai != null && item.SanPham.dGiaKhuyenMai != 0) { orderDetail.dDonGia = item.SanPham.dGiaKhuyenMai; } else { orderDetail.dDonGia = item.SanPham.dGiaBan; } detailDao.Insert(orderDetail); if (item.SanPham.dGiaKhuyenMai != null && item.SanPham.dGiaKhuyenMai != 0) { total += (item.SanPham.dGiaKhuyenMai.GetValueOrDefault(0) * item.SoLuong); } else { total += (item.SanPham.dGiaBan.GetValueOrDefault(0) * item.SoLuong); } divsp.divSanPham(item.SanPham.ID, item.SoLuong); //ViewBag.Total = total; } if (!FormOfPayment.Equals("COD")) { RequestInfo info = new RequestInfo(); info.Merchant_id = MerchantID; info.Merchant_password = MerchantPassword; info.Receiver_email = MerchantEmail; info.cur_code = "vnd"; info.bank_code = sBankCode; info.Order_code = id.ToString(); info.Total_amount = total.ToString(); info.fee_shipping = "0"; info.Discount_amount = "0"; info.order_description = "Thanh toán đơn hàng Myhands Store"; info.return_url = currentLink + "/hoan-thanh"; info.cancel_url = currentLink + "/loi-thanh-toan"; info.Buyer_fullname = sTenNguoiNhan; info.Buyer_email = sEmail; info.Buyer_mobile = sSoDienThoai; APICheckoutV3 objNLChecout = new APICheckoutV3(); ResponseInfo result = objNLChecout.GetUrlCheckout(info, FormOfPayment); if (result.Error_code == "00") { Response.Redirect(result.Checkout_url); //return Redirect("/hoan-thanh"); } else { return(Redirect("/loi-thanh-toan")); } } string content = System.IO.File.ReadAllText(Server.MapPath("~/Assets/Client/Templates/MailForm.html")); content = content.Replace("{{sTenNguoiNhan}}", sTenNguoiNhan); content = content.Replace("{{sSoDienThoai}}", sSoDienThoai); content = content.Replace("{{sEmail}}", sEmail); content = content.Replace("{{sDiaChi}}", sDiaChi + diachi); content = content.Replace("{{Total}}", total.ToString("N0")); var toEmail = ConfigurationManager.AppSettings["ToEmailAddress"].ToString(); new Mail().SendMail(sEmail, "Đơn hàng mới từ MyHandsStore", content); new Mail().SendMail(toEmail, "Đơn hàng mới từ MyHandsStore", content); } catch (Exception ex) { string script = "<script>alert('" + ex.Message + "');</script>"; return(Redirect("/loi-thanh-toan")); } Session[CartSession] = null; return(Redirect("/hoan-thanh")); }
public ActionResult CreateOrder(string orderViewModel) { Session["NotRegister"] = true; var order = new JavaScriptSerializer().Deserialize <OrderViewModel>(orderViewModel); var orderNew = new Order(); orderNew.UpdateOrder(order); if (Request.IsAuthenticated) { orderNew.CustomerId = User.Identity.GetUserId(); orderNew.CreatedBy = User.Identity.GetUserName(); } var cart = (List <ShoppingCartViewModel>)Session[CommonConstants.SessionCart]; List <OrderDetail> orderDetails = new List <OrderDetail>(); bool isEnough = true; foreach (var item in cart) { var detail = new OrderDetail(); detail.ProductID = item.Id; detail.Quantity = item.Quantity; detail.Price = item.SalePrice - (item.PromotionPrice.HasValue ? item.PromotionPrice.Value : 0); detail.Discount = item.PromotionPrice; orderDetails.Add(detail); //isEnough =_productService.SellProduct(item.ProductId, item.Quantity); isEnough = true; break; } if (isEnough) { orderNew.TotalAmount = orderDetails.Sum(x => x.Price); orderNew.TotalDiscount = orderDetails.Sum(x => x.Discount); var orderReturn = _orderService.Create(ref orderNew, orderDetails); //_productService.Save(); if (order.PaymentMethod == "CASH" || order.PaymentMethod == "CK") { return(Json(new { status = true })); } else { var currentLink = ConfigHelper.GetByKey("CurrentLink"); RequestInfo info = new RequestInfo(); info.Merchant_id = merchantId; info.Merchant_password = merchantPassword; info.Receiver_email = merchantEmail; info.cur_code = "vnd"; info.bank_code = order.BankCode; info.Order_code = orderReturn.ID.ToString(); info.Total_amount = orderDetails.Sum(x => x.Quantity * x.Price).ToString(); info.fee_shipping = "0"; info.Discount_amount = "0"; info.order_description = "Thanh toán đơn hàng tại"; info.return_url = currentLink + "xac-nhan-don-hang.html"; info.cancel_url = currentLink + "huy-don-hang.html"; info.Buyer_fullname = order.CustomerName; info.Buyer_email = order.CustomerEmail; info.Buyer_mobile = order.CustomerMobile; APICheckoutV3 objNLChecout = new APICheckoutV3(); ResponseInfo result = objNLChecout.GetUrlCheckout(info, order.PaymentMethod); if (result.Error_code == "00") { return(Json(new { status = true, urlCheckout = result.Checkout_url, message = result.Description })); } else { return(Json(new { status = false, message = result.Description })); } } } else { return(Json(new { status = false, message = "Không đủ hàng." })); } }
public ActionResult VeXeThanhToan(ThanhToanVeXeModel model, FormCollection form) { if (Session["DAT_MUA_VE_XE_ID"] == null) { return(Loi()); } var customer = _workContext.CurrentCustomer; Address address = null; if (model.diachigiaohang.Id > 0) { address = _addressService.GetAddressById(model.diachigiaohang.Id); } address = model.diachigiaohang.ToEntity(address); address.CreatedOnUtc = DateTime.UtcNow; //some validation if (address.CountryId == 0) { address.CountryId = null; } if (address.StateProvinceId == 0) { address.StateProvinceId = null; } if (address.QuanHuyenId == 0) { address.QuanHuyenId = null; } if (address.Id > 0) { _addressService.UpdateAddress(address); } else { customer.Addresses.Add(address); _customerService.UpdateCustomer(customer); } int OrderId = 0; if (model.HinhThucThanhToan == "CHONVE") { // Đơn hàng do chonve.vn xử lý // chờ xác nhận điện thoại // return vn.worldsms.wcf.APISMS apisms = new vn.worldsms.wcf.APISMS(); var Sender = "CHONVE.VN"; Random rdn = new Random(); Session["maXacThuc"] = rdn.Next(1000, 9999); var Msg = "Ma xac thuc cua ban la: " + Session["maXacThuc"]; var Phone = model.diachigiaohang.PhoneNumber; var Username = "******"; var Password = "******"; string result = apisms.PushMsg2Phone(Sender, Msg, Phone, Username, Password); int kq = Convert.ToInt32(result); if (kq == 1) { return(RedirectToAction("XacThucDatVe", "VeXeKhach")); } else { return(RedirectToAction("VeXeThanhToan", "VeXeKhach")); } } else { _phoiveService.ThanhToan(Session["DAT_MUA_VE_XE_ID"].ToString(), _workContext.CurrentCustomer.Id, address, out OrderId); //gửi đơn hàng cho ngân lượng.vn RequestInfo info = new RequestInfo(); info.Merchant_id = CommonHelper.Merchant_Id; info.Merchant_password = CommonHelper.Merchant_Password; info.Receiver_email = "*****@*****.**"; info.cur_code = "vnd"; info.bank_code = model.BankCode; info.Payment_method = model.HinhThucThanhToan; info.Order_code = OrderId.ToString(); info.Total_amount = model.TongTien.ToString(); info.time_limit = CommonHelper.Time_Limit; info.return_url = CommonHelper.Return_Url; info.cancel_url = CommonHelper.Cancel_Url; info.Buyer_fullname = model.diachigiaohang.FullName; info.Buyer_email = model.diachigiaohang.Email; info.Buyer_mobile = model.diachigiaohang.PhoneNumber; APICheckoutV3 objNLChecout = new APICheckoutV3(); ResponseInfo result = objNLChecout.GetUrlCheckout(info, model.HinhThucThanhToan); if (result.Error_code == "00") { Response.Redirect(result.Checkout_url); } else { model.ErrorSentOrder = objNLChecout.GetErrorMessage(result.Error_code); return(View(model)); } } return(null); }
public ActionResult ThanhToanThanhCong() { int orderId = 0; var model = new ThanhToanVeXeModel(); var _token = Request["token"]; if (!string.IsNullOrWhiteSpace(_token)) { RequestCheckOrder info = new RequestCheckOrder(); info.Merchant_id = CommonHelper.Merchant_Id; info.Merchant_password = CommonHelper.Merchant_Password; info.Token = _token; APICheckoutV3 objNLChecout = new APICheckoutV3(); ResponseCheckOrder result = objNLChecout.GetTransactionDetail(info); if (result.errorCode == "00") { orderId = Convert.ToInt32(result.order_code); model.HinhThucThanhToan = result.paymentMethod; if (result.paymentMethod != "CHONVE") { var _order = _orderService.GetOrderById(orderId); if (result.transactionStatus == "00") { _order.PaymentStatusId = (int)PaymentStatus.Paid; } else { _order.PaymentStatusId = (int)PaymentStatus.Authorized; } _orderService.UpdateOrder(_order); var phoives = _phoiveService.GetPhoiVeByOrderId(orderId); foreach (var item in phoives) { item.TrangThaiId = (int)ENTrangThaiPhoiVe.DaThanhToan; _phoiveService.UpdatePhoiVe(item); } } else { //update trang thai phoi vé về chưa thanh toán } } } //thiet dat thong tin noi nhan var countries = new List <Nop.Core.Domain.Directory.Country>(); countries.Add(_countryService.GetCountryById(NhaXesController.CountryID)); var diachigiaohang = _workContext.CurrentCustomer.ShippingAddress; if (_workContext.CurrentCustomer.Addresses.Count > 0) { diachigiaohang = _workContext.CurrentCustomer.Addresses.First(); } model.diachigiaohang.PrepareModel( address: diachigiaohang, excludeProperties: false, addressSettings: _addressSettings, localizationService: _localizationService, stateProvinceService: _stateProvinceService, diachiService: _diachiService, addressAttributeFormatter: _addressAttributeFormatter, loadCountries: () => countries); //lay thong tin ve xe var phoive = _phoiveService.GetPhoiVeByCustomer(_workContext.CurrentCustomer.Id); for (int i = 0; i < phoive.Count(); i++) { orderId = phoive[i].OrderId; } model.phoiveinfos = _phoiveService.GetPhoiVeByOrderId(orderId); //cho thanh toan qua lau, nen het han giu cho ve if (model.phoiveinfos.Count == 0) { return(RedirectToRoute("HomePage")); } model.nguonvexeinfo = _vexeService.GetNguonVeXeById(model.phoiveinfos[0].NguonVeXeId.GetValueOrDefault(0)); model.nhaxeinfo = _nhaxeService.GetNhaXeById(model.nguonvexeinfo.NhaXeId); model.NgayDi = model.phoiveinfos[0].NgayDi; model.NgayDi = model.NgayDi.AddHours(model.nguonvexeinfo.ThoiGianDi.Hour).AddMinutes(model.nguonvexeinfo.ThoiGianDi.Minute); model.NgayVe = model.NgayDi.AddHours(Convert.ToDouble(model.nguonvexeinfo.LichTrinhInfo.SoGioChay)); model.TongTien = decimal.Zero; model.KyHieuGhe = ""; foreach (var pv in model.phoiveinfos) { if (string.IsNullOrEmpty(model.KyHieuGhe)) { model.KyHieuGhe = pv.sodoghexequytac.Val; } else { model.KyHieuGhe += "," + pv.sodoghexequytac.Val; } model.TongTien += pv.GiaVeHienTai; } ViewBag.OrderId = orderId; return(View(model)); }
public void ProcessRequest(HttpContext context) { string rs = "0"; try { string op = context.Request["op"].ToLower(); string captcha = context.Request["captcha"]; int price = Convert.ToInt32(context.Request["price"]); int orderId = Convert.ToInt32(context.Request["orderId"]); string name = context.Request["name"]; string shipingFee = context.Request["shipingFee"]; string email = context.Request["email"]; string phone = context.Request["phone"]; Boolean valid = true; if (price <= 0 || orderId <= 0) { valid = false; rs = "Tiền thanh toán không hợp lệ"; } if (String.IsNullOrEmpty(captcha) && valid) { valid = false; rs = "Vui lòng click vào ô kiểm tra"; } if (valid) { switch (op) { case "nlcheckout": string payment_method = context.Request["payment_method"]; string str_bankcode = context.Request["bankcode"]; string order_description = context.Request["detail"]; string DomainName = HttpContext.Current.Request.Url.Scheme + @"://" + HttpContext.Current.Request.Url.Host; Anpero.PaymentApi.NganLuong.RequestInfo info = new Anpero.PaymentApi.NganLuong.RequestInfo(); info.Merchant_id = "36680"; info.Merchant_password = "******"; info.Receiver_email = "*****@*****.**"; //must be register email info.cur_code = "vnd"; info.bank_code = str_bankcode; info.Order_code = orderId.ToString(); info.Total_amount = price.ToString(); info.fee_shipping = "0"; info.Discount_amount = "0"; info.order_description = order_description; info.return_url = DomainName + "/API/NLCallback"; info.cancel_url = DomainName + "/API/NLCancel"; info.Buyer_fullname = name; info.Buyer_email = email; info.Buyer_mobile = phone; APICheckoutV3 objNLChecout = new APICheckoutV3(); ResponseInfo result = objNLChecout.GetUrlCheckout(info, payment_method); if (result.Error_code == "00") { rs = result.Checkout_url; } else { rs = result.Description + " (" + result.Error_code + ")"; } break; default: break; } } } catch (Exception) { } context.Response.ContentType = "text/plain"; context.Response.Write(rs); }
public async Task <System.Web.Mvc.ActionResult> BookingReceipt(string error_code, string token, int?canceledBookingID = null) { var userID = User.Identity.GetUserId(); var bookingService = this.Service <IBookingReceiptService>(); // If the customer cancel the booking, delete it and redirect him to homepage if (canceledBookingID != null) { var bookingReceipt = bookingService.Get(br => br.CustomerID == userID && br.ID == canceledBookingID && br.IsPending == true).FirstOrDefault(); if (bookingReceipt == null) { return(new HttpStatusCodeResult(400, "Invalid request")); } bookingService.Delete(bookingReceipt); return(RedirectToAction("Index", "Home")); } // If the transaction went smoothy, check the returned info + MD5 token var info = new RequestCheckOrderTestTemplate { Token = token }; var objNLCheckout = new APICheckoutV3(); var result = objNLCheckout.GetTransactionDetail(info); if (result.errorCode == "00") { // Try to get the bookingReceiptID try { var bookingID = int.Parse(result.order_code); var bookingReceipt = bookingService.Get(br => br.CustomerID == userID && br.ID == bookingID && br.IsPending == true).FirstOrDefault(); if (bookingReceipt == null) { return(new HttpStatusCodeResult(400, "Invalid request")); } bookingReceipt.IsPending = false; bookingService.Update(bookingReceipt); // Send alert email SystemService sysService = new SystemService(); await sysService.SendBookingAlertEmailToCustomer(bookingReceipt); await sysService.SendBookingAlertEmailToProvider(bookingReceipt); return(View("~/Areas/Customer/Views/Booking/BookingReceipt.cshtml", bookingReceipt)); } catch (FormatException e) { return(new HttpStatusCodeResult(400, "Invalid request")); } } return(new HttpStatusCodeResult(400, "Invalid request")); }
public System.Web.Mvc.ActionResult BookVehicle(BookingConfirmViewModel bookingModel, NganLuongPaymentModel nganLuongPayment) { var user = HttpContext.GetOwinContext() .GetUserManager <ApplicationUserManager>() .FindById(HttpContext.User.Identity.GetUserId()); // Check if the request contains all valid params if (bookingModel?.Action == null || bookingModel.Receipt?.ID == null || nganLuongPayment == null) { return(new HttpStatusCodeResult(400, "Invalid request")); } var bookingService = this.Service <IBookingReceiptService>(); var bookingReceipt = bookingService.Get(br => br.ID == bookingModel.Receipt.ID && br.CustomerID == user.Id && br.IsPending).FirstOrDefault(); if (bookingReceipt == null) { return(new HttpStatusCodeResult(400, "Invalid request")); } // Act based on the received action's name switch (bookingModel.Action) { case "delete": bookingService.Delete(bookingReceipt); return(RedirectToAction("Index", "Home")); case "change": var vehicleID = bookingReceipt.VehicleID; bookingService.Delete(bookingReceipt); return(RedirectToAction("VehicleInfo", "Home", new { id = vehicleID })); case "pay": break; default: return(new HttpStatusCodeResult(400, "Bad request")); } // Only "pay" action left to handle // Now validate nganluong params before redirect to nganluong var info = new RequestInfoTestTemplate { bank_code = nganLuongPayment.BankCode, Order_code = nganLuongPayment.OrderCode, order_description = "Test booking", return_url = "http://localhost:65358/bookingReceipt", cancel_url = "http://localhost:65358/bookingReceipt?canceledBookingID=" + bookingModel.Receipt.ID, Buyer_fullname = user.FullName, Buyer_email = user.Email, Buyer_mobile = user.PhoneNumber, time_limit = Constants.BOOKING_CONFIRM_TIMEOUT_IN_MINUTES.ToString() }; var objNLCheckout = new APICheckoutV3(); var result = objNLCheckout.GetUrlCheckout(info, nganLuongPayment.PaymentMethod); if (result.Error_code == "00") { return(Redirect(result.Checkout_url)); } return(new HttpStatusCodeResult(400, "Invalid request")); }
public async System.Threading.Tasks.Task <ActionResult> Success(string error_code, string token) { // Check the returned info + MD5 token var info = new RequestCheckOrderTestTemplate { Token = token }; var objNLCheckout = new APICheckoutV3(); var result = objNLCheckout.GetTransactionDetail(info); if (result.errorCode == "00") { // Try to get the new IsProviderUntil datetime try { // Separate the userID and IsProviderUntil Datetime from order_code var words = result.order_code.Split(new[] { " - " }, StringSplitOptions.None); if (words.Length != 2) { return(new HttpStatusCodeResult(400, "Invalid request")); } var userID = words[0]; // Get current user var userService = this.Service <IUserService>(); var user = await userService.GetAsync(userID); // Validate the user if (user == null) { return(new HttpStatusCodeResult(400, "Invalid request")); } var isProviderUntil = DateTime.Parse(words[1]); // Validate the new datetime if (isProviderUntil < DateTime.Now) { return(new HttpStatusCodeResult(400, "Invalid request")); } user.IsProviderUntil = isProviderUntil; // Add role provider if the user havent already had that role if (user.AspNetRoles.All(r => r.Name != "Provider")) { var providerRole = await this.Service <IRoleService>().GetAsync("2"); user.AspNetRoles.Add(providerRole); } userService.Update(user); // Send alert email var sysService = new SystemService(); await sysService.SendBecomeProviderAlertEmail(user.Email, user); return(View("~/Areas/Customer/Views/BecomeProvider/Success.cshtml", user)); } catch (FormatException e) { return(new HttpStatusCodeResult(400, "Invalid request")); } } return(new HttpStatusCodeResult(400, "Invalid request")); }
public JsonResult AgreeToPay(AgreementViewModel vm) { string redirectUrl = ""; string errorMessage = ""; var db = new DbContext(); try { //DEBUG //Logger.GetInstance().Write(JsonConvert.SerializeObject(vm)); var details = db.GetDetails(vm.CashKey); if (details != null) { details.AgreedDateTime = DateTime.UtcNow; var info = new RequestInfo(); info.Merchant_id = ConfigCode.GetInstance().MerchantID; info.Merchant_password = ConfigCode.GetInstance().MerchantPassword; info.Receiver_email = ConfigCode.GetInstance().ReceiverEmail; info.cur_code = "vnd"; info.Payment_method = vm.OptionPayment; info.bank_code = vm.BankCode; info.Order_code = details.InvoiceNo; info.Total_amount = details.Total; info.Buyer_fullname = vm.FullName; info.Buyer_email = vm.Email; info.Buyer_mobile = vm.Phone; //Optional fields info.fee_shipping = "0"; info.Discount_amount = "0"; info.order_description = ""; // End of optional fields string host = HttpContext.Request.Url.Scheme + "://" + HttpContext.Request.Url.Authority; string baseUrl = string.Format("{0}/nganluong/return?", host); info.return_url = baseUrl + "key=" + vm.CashKey; info.cancel_url = baseUrl + "key=" + vm.CashKey + "&type=" + ReturnType.Cancel.GetHashCode(); info.time_limit = baseUrl + "key=" + vm.CashKey + "&type=" + ReturnType.Timeout.GetHashCode(); //DEBUG //Logger.GetInstance().Write("RequestInfo"); //Logger.GetInstance().Write(JsonConvert.SerializeObject(info)); var objApiCheckout = new APICheckoutV3(); ResponseInfo checkoutRs = objApiCheckout.GetUrlCheckout(info, vm.OptionPayment); //DEBUG //Logger.GetInstance().Write("Check out response:"); //Logger.GetInstance().Write(JsonConvert.SerializeObject(checkoutRs)); if (checkoutRs.Error_code == "00") { details.ProviderTransRefId = checkoutRs.Token; bool result = db.SetDetails(vm.CashKey, details); if (result) { redirectUrl = checkoutRs.Checkout_url; } else { errorMessage = Resources.Application.CommonErrorMessage; Logger.GetInstance().Write(string.Format("[Key={0}] Check out succeeded but failed to update NL Token", vm.CashKey)); } } else { ; errorMessage = string.Format("Error Description: {0}. <br/> {1}", checkoutRs.Description, Resources.Application.CommonErrorMessage); Logger.GetInstance().Write(string.Format("[Key={0}] Failed to check out(Code={1};Desc={2})", vm.CashKey, checkoutRs.Error_code, checkoutRs.Description)); } } } catch (Exception ex) { Logger.GetInstance().Write(ex, string.Format("[Key={0}]Exception thrown in AgreeToPay", vm.CashKey)); ViewBag.ErrorMessage = ex.Message; redirectUrl = ""; } // Use js to redirect to NL check out URL. return(Json(new { result = redirectUrl, message = errorMessage }, JsonRequestBehavior.AllowGet)); }
public ActionResult Index(Morder order) { Random rand = new Random((int)DateTime.Now.Ticks); int numIterations = 0; numIterations = rand.Next(1, 100000); DateTime time = DateTime.Now; string orderCode = numIterations + "" + time; string sumOrder = Request["sumOrder"]; string payment_method = Request["option_payment"]; // Neu Ship COde if (payment_method.Equals("COD")) { // cap nhat thong tin sau khi dat hang thanh cong saveOrder(order, "COD", 2, orderCode); var cart = Session[SessionCart]; var list = new List <Cart_item>(); ViewBag.cart = (List <Cart_item>)cart; Session["SessionCart"] = null; var listProductOrder = db.Orderdetails.Where(m => m.orderid == order.ID); return(View("payment")); } //Neu Thanh toan MOMO else if (payment_method.Equals("MOMO")) { //request params need to request to MoMo system string endpoint = momoInfo.endpoint; string partnerCode = momoInfo.partnerCode; string accessKey = momoInfo.accessKey; string serectkey = momoInfo.serectkey; string orderInfo = momoInfo.orderInfo; string returnUrl = momoInfo.returnUrl; string notifyurl = momoInfo.notifyurl; string amount = sumOrder; string orderid = Guid.NewGuid().ToString(); string requestId = Guid.NewGuid().ToString(); string extraData = ""; //Before sign HMAC SHA256 signature string rawHash = "partnerCode=" + partnerCode + "&accessKey=" + accessKey + "&requestId=" + requestId + "&amount=" + amount + "&orderId=" + orderid + "&orderInfo=" + orderInfo + "&returnUrl=" + returnUrl + "¬ifyUrl=" + notifyurl + "&extraData=" + extraData; log.Debug("rawHash = " + rawHash); MoMoSecurity crypto = new MoMoSecurity(); //sign signature SHA256 string signature = crypto.signSHA256(rawHash, serectkey); log.Debug("Signature = " + signature); //build body json request JObject message = new JObject { { "partnerCode", partnerCode }, { "accessKey", accessKey }, { "requestId", requestId }, { "amount", amount }, { "orderId", orderid }, { "orderInfo", orderInfo }, { "returnUrl", returnUrl }, { "notifyUrl", notifyurl }, { "extraData", extraData }, { "requestType", "captureMoMoWallet" }, { "signature", signature } }; log.Debug("Json request to MoMo: " + message.ToString()); string responseFromMomo = PaymentRequest.sendPaymentRequest(endpoint, message.ToString()); JObject jmessage = JObject.Parse(responseFromMomo); saveOrder(order, "Cổng thanh toán MOMO", 2, orderid); return(Redirect(jmessage.GetValue("payUrl").ToString())); } //Neu Thanh toan Ngan Luong else if (payment_method.Equals("NL")) { string str_bankcode = Request["bankcode"]; RequestInfo info = new RequestInfo(); info.Merchant_id = nganluongInfo.Merchant_id; info.Merchant_password = nganluongInfo.Merchant_password; info.Receiver_email = nganluongInfo.Receiver_email; info.cur_code = "vnd"; info.bank_code = str_bankcode; info.Order_code = orderCode; info.Total_amount = sumOrder; info.fee_shipping = "0"; info.Discount_amount = "0"; info.order_description = "Thanh toán ngân lượng cho đơn hàng"; info.return_url = nganluongInfo.return_url; info.cancel_url = nganluongInfo.cancel_url; info.Buyer_fullname = order.deliveryname; info.Buyer_email = order.deliveryemail; info.Buyer_mobile = order.deliveryphone; APICheckoutV3 objNLChecout = new APICheckoutV3(); ResponseInfo result = objNLChecout.GetUrlCheckout(info, payment_method); // neu khong gap loi gi if (result.Error_code == "00") { saveOrder(order, "Cổng thanh toán Ngân Lượng", 2, orderCode); // chuyen sang trang ngan luong return(Redirect(result.Checkout_url)); } else { ViewBag.errorPaymentOnline = result.Description; return(View("payment")); } } //Neu Thanh Toán ATM online else if (payment_method.Equals("ATM_ONLINE")) { string str_bankcode = Request["bankcode"]; RequestInfo info = new RequestInfo(); info.Merchant_id = nganluongInfo.Merchant_id; info.Merchant_password = nganluongInfo.Merchant_password; info.Receiver_email = nganluongInfo.Receiver_email; info.cur_code = "vnd"; info.bank_code = str_bankcode; info.Order_code = orderCode; info.Total_amount = sumOrder; info.fee_shipping = "0"; info.Discount_amount = "0"; info.order_description = "Thanh toán ngân lượng cho đơn hàng"; info.return_url = nganluongInfo.return_url; info.cancel_url = nganluongInfo.cancel_url; info.Buyer_fullname = order.deliveryname; info.Buyer_email = order.deliveryemail; info.Buyer_mobile = order.deliveryphone; APICheckoutV3 objNLChecout = new APICheckoutV3(); ResponseInfo result = objNLChecout.GetUrlCheckout(info, payment_method); // neu khong gap loi gi if (result.Error_code == "00") { saveOrder(order, "ATM Online qua ngân lượng", 2, orderCode); return(Redirect(result.Checkout_url)); } else { ViewBag.errorPaymentOnline = result.Description; return(View("payment")); } } return(View("payment")); }
// tạo order khi click thanh toán public ActionResult CreatOrder(string orderViewModel) { // order(chứa thông tin người mua hàng) // orderDetail(chứ số lượng sp,sp) var order = new JavaScriptSerializer().Deserialize <OrderViewModel>(orderViewModel); var orderNew = new Order(); orderNew.UpdateOrder(order); if (Request.IsAuthenticated) { orderNew.CustomerID = User.Identity.GetUserId(); orderNew.CreatedBy = User.Identity.GetUserName(); } var cartSession = (List <ShoppingCartViewModel>)Session[CommonConstants.SessionCart]; List <OrderDetail> orderDetails = new List <OrderDetail>(); bool isEnough = true; foreach (var item in cartSession) { var detail = new OrderDetail(); detail.ProductID = item.ProductId; detail.Quantity = item.Quantity; orderDetails.Add(detail); isEnough = _productService.SellProduct(item.ProductId, item.Quantity); // tính số sp còn lại break; } if (isEnough == true) { //_orderService.Create(orderNew, orderDetails); var orderReturn = _orderService.Create(ref orderNew, orderDetails); _productService.Save(); // thanh toán tiền mặt if (order.PaymentMethod == "CASH") { return(Json(new { status = true })); } else { // thanh toán bằng ATM,Ngân Lượng var currentLink = ConfigHelper.GetByKey("CurrentLink"); RequestInfo info = new RequestInfo(); info.Merchant_id = merchantId; info.Merchant_password = merchantPassword; info.Receiver_email = merchantEmail; info.cur_code = "vnd"; info.bank_code = order.BankCode; info.Order_code = orderReturn.ID.ToString(); info.Total_amount = orderDetails.Sum(x => x.Quantity * x.Price).ToString(); info.fee_shipping = "0"; info.Discount_amount = "0"; info.order_description = "Thanh toán đơn hàng tại NonameShop"; info.return_url = currentLink + "xac-nhan-don-hang.html"; info.cancel_url = currentLink + "huy-don-hang.html"; info.Buyer_fullname = order.CustomerName; info.Buyer_email = order.CustomerEmail; info.Buyer_mobile = order.CustomerMobile; APICheckoutV3 objNLChecout = new APICheckoutV3(); ResponseInfo result = objNLChecout.GetUrlCheckout(info, order.PaymentMethod); if (result.Error_code == "00") { return(Json(new { status = true, urlCheckout = result.Checkout_url,// chuyển hướng qua ngân lượng message = result.Description })); } else { return(Json(new { status = false, message = result.Description })); } } } else { return(Json(new { status = false, message = "Không đủ hàng" })); } }