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")); }
/// <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); } }
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 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 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 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 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 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; }
// 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" })); } }
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 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 async Task <IActionResult> VerifyAndCheckout(CheckoutSum sum, String code, String bankcode) { //convert currency var currencyConvertAPI = _configuration["currencycovertApi:API"]; var cli = new HttpClient(); var fullApi = "https://free.currconv.com/api/v7/convert?q=USD_VND&compact=ultra&apiKey=" + currencyConvertAPI; HttpResponseMessage getConttent = await cli.GetAsync(fullApi); HttpContent respon = getConttent.Content; Debug.WriteLine(currencyConvertAPI + "cec"); using (var read = new StreamReader(await respon.ReadAsStreamAsync())) { var resss = await read.ReadToEndAsync(); Debug.WriteLine(resss + "cecc"); resss = @"[" + resss + "]"; dynamic ketqua = JArray.Parse(resss); dynamic kq = ketqua[0]; string convert = kq.USD_VND; ViewBag.tyso = convert; USDtoVND = float.Parse(convert); Debug.WriteLine(USDtoVND); } //end convert //---------------------- Mở ra khi Hoàn Tất Hết var clientt = new HttpClient(); // Add authentication header clientt.DefaultRequestHeaders.Add("X-Authy-API-Key", AuthyAPIKey); // https://api.authy.com/protected/json/phones/verification/check?phone_number=$USER_PHONE&country_code=$USER_COUNTRY&verification_code=$VERIFY_CODE var api = "https://api.authy.com/protected/json/phones/verification/check?phone_number=" + sum.khachhang.Sdt + "&country_code=84&verification_code=" + code; HttpResponseMessage response = await clientt.GetAsync(api); // Get the response content. HttpContent responseContent = response.Content; // Get the stream of the content. using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync())) { // Write the output. var result = await reader.ReadToEndAsync(); // parse json string to array result = @"[" + result + "]"; dynamic blogPosts = JArray.Parse(result); dynamic blogPost = blogPosts[0]; string isTrue = blogPost.success; //string isTrue = "True"; // dong lai khi hoan tat // -- End Mở ra if (isTrue == "True") // Code = Code : Success : True { if (_KhachHang.GetKhachHang(sum.khachhang.Email) != null) { _KhachHang.UpdateKhachHang(sum.khachhang); } _KhachHang.AddKhachHang(sum.khachhang, HttpContext.Session.GetInt32("Id")); _Donhang.UpdatePhuongThuc(HttpContext.Session.GetInt32("Id"), sum.PhuongThucThanhToan); _Donhang.UpdateDescription(HttpContext.Session.GetInt32("Id"), "Chưa Thanh Toán"); if (sum.PhuongThucThanhToan == "Thanh Toán Khi Nhận Hàng") { return(View("../Checkout/Success")); } // end thanh toan khi nhan hang else if (sum.PhuongThucThanhToan == "PayPal") { Double summ = 0; var PayPalAPI = new PayPalAPI(_configuration); var itemList = new ItemList() { Items = new List <Item>() }; IEnumerable <Chitietdonhang> a = _DonhangAdmin.GetChitietdonhang((int)HttpContext.Session.GetInt32("Id")); foreach (var item in a) { Decimal soluong = 0; string des = ""; Sanpham sp = _Sanpham.GetSanPham(item.IdSanPham); if (sp.IdLoaiSanPham == 4) { soluong = (Decimal)item.SoLuong; des = "unit: 1 cup"; } else { soluong = (Decimal)item.SoLuong / 100; des = "Unit: 100 gam"; } itemList.Items.Add(new Item() { Name = sp.Ten, Currency = "USD", Price = Math.Round(((Decimal)item.Gia / (Decimal)USDtoVND / soluong), 2).ToString(), Quantity = soluong.ToString(), Description = des }); } foreach (var item in itemList.Items) { Debug.WriteLine(item.Name + " " + item.Quantity + " " + item.Price); // debug log summ = summ + Math.Round((double.Parse(item.Price) * double.Parse(item.Quantity)), 2); } string URL = await PayPalAPI.getRedirectURLtoPayPal(summ, "USD", itemList); return(Redirect(URL)); } else if (sum.PhuongThucThanhToan == "Ví Ngân Lượng" || sum.PhuongThucThanhToan == "Thẻ VISA" || sum.PhuongThucThanhToan == "Thẻ ATM") { Double summ = 0; string payment_method = ""; string str_bankcode = bankcode; IEnumerable <Chitietdonhang> a = _DonhangAdmin.GetChitietdonhang((int)HttpContext.Session.GetInt32("Id")); if (sum.PhuongThucThanhToan == "Ví Ngân Lượng") { payment_method = "nl"; } else if (sum.PhuongThucThanhToan == "Thẻ VISA") { payment_method = "VISA"; } else if (sum.PhuongThucThanhToan == "Thẻ ATM") { payment_method = "ATM_ONLINE"; } else { payment_method = "ATM_ONLINE"; } RequestInfo info = new RequestInfo(); foreach (var item in a) { //Decimal soluong = 0; //string des = ""; //Sanpham sp = _Sanpham.GetSanPham(item.IdSanPham); //if (sp.IdLoaiSanPham == 4) //{ // soluong = (Decimal)item.SoLuong; // des = "unit: 1 cup"; //} //else //{ // soluong = (Decimal)item.SoLuong / 100; // des = "Unit: 100 gam"; //} summ = summ + ((double)item.Gia); } info.Merchant_id = _configuration["NganLuong:mechant_id"]; info.Merchant_password = _configuration["NganLuong:mechant_pass"]; info.Receiver_email = _configuration["NganLuong:seller_email"]; info.cur_code = "vnd"; info.bank_code = str_bankcode; info.Order_code = HttpContext.Session.GetInt32("Id").ToString(); info.Total_amount = summ.ToString(); info.order_description = "Đây Là Đơn Hàng Từ " + sum.khachhang.Ten + " có email là " + sum.khachhang.Email; info.return_url = _configuration["NganLuong:returnURL"]; info.cancel_url = _configuration["NganLuong:cancelURL"]; info.Buyer_fullname = sum.khachhang.Ten; info.Buyer_email = sum.khachhang.Email; info.Buyer_mobile = sum.khachhang.Sdt; info.Total_item = a.Count().ToString(); APICheckoutV3 objNLChecout = new APICheckoutV3(_configuration); ResponseInfo resultt = objNLChecout.GetUrlCheckout(info, payment_method); if (resultt.Error_code == "00") { return(Redirect(resultt.Checkout_url)); } else { Debug.WriteLine(resultt.Description); return(RedirectToAction("Fail", "Checkout", new { message = resultt.Description })); } } else { return(RedirectToAction("Fail")); } } else // Code != Code : Success : False { return(RedirectToAction("Fail", "Checkout", new { message = "Sai Mã Xác Nhận!!" })); } } //mở ra khi xong het }
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 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 = ShopCayCanh.nganluonAPI.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")); }
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 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) { 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 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")); }
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) { switch (op) { case "nlcheckout": 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); 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; default: break; } } } catch (Exception ex) { } context.Response.ContentType = "text/plain"; context.Response.Write(rs); }