private bool CheckCartIsChangeInStock(CartDetailsModel cart) { bool result = false; List <ProductInCartDetailsModel> productsInCart = cart.ProductsInCart; foreach (ProductInCartDetailsModel p in productsInCart) { ProductsInBill prodInBill = new ProductsInBill(); prodInBill.BillID = cart.BillID; prodInBill.ProductID = p.ProductID; prodInBill.ProductName = productRepo.GetProductName(p.ProductID); prodInBill.Quantity = p.Quantity; if (p.Price != productRepo.GetUnitPrice(p.ProductID)) { // double oldPrice = p.Price; prodInBill.Price = productRepo.GetUnitPrice(p.ProductID); p.Price = prodInBill.Price; prodInBill.Total = p.Quantity * prodInBill.Price; p.Total = prodInBill.Total; } else { prodInBill.Price = p.Price; prodInBill.Total = p.Total; } result = productsInBillRepo.UpdateProductInBill(prodInBill); } UpdateBillDetails(cart.BillID); return(result); }
public async Task <HttpResponse> CreateOrderPaypal(string fullname, string address, string street, string city, int IDBill) { try { //string strHost = HttpContext.Current.Request.Url.Host.ToString(); CartDetailsModel cart = LoadCartDetailsModel(IDBill); // string host = Request.Url.Host; // string urlReturn = "https://" + host; // if (host.Equals("localhost")) // { // urlReturn = urlReturn + ":" + HttpContext.Request.Url.Port; // } // MessageBox.Show(urlReturn); var request = new OrdersCreateRequest(); request.Prefer("return=representation"); request.RequestBody(CreateOrderSample.BuildRequestBody(fullname, address, street, city, cart)); var response = await PayPalClient.client().Execute(request); var createOrderResult = response.Result <Order>(); string orderId = createOrderResult.Id; string url = "https://www.sandbox.paypal.com/checkoutnow?token=" + orderId; Response.Redirect(url); return(response); } catch (Exception e) { SendMailSSL.SendErrorToAdmin("Error at CreateOrderPaypal: " + e.ToString()); } return(null); }
public ActionResult FinishOrderPaypal(CartDetailsModel cart) { //update product foreach (ProductInCartDetailsModel pro in cart.ProductsInCart) { Product p = productRepo.GetProduct(pro.ProductID); int newQuantity = p.Quantity - pro.Quantity; p.Quantity = newQuantity; if (newQuantity == 0) { p.StatusCode = "OUTS"; } productRepo.UpdateOrderedProduct(p); } //update bill status ->payed billRepo.UpdateBillStatus(cart.BillID, "PAY"); //send mail for user here Session.Remove("CartDetails"); TempData["PaymentMessage"] = "Your bill(bill ID:" + cart.BillID + ") is ordered success!!"; TempData["BillID"] = cart.BillID; string username = HttpContext.User.Identity.Name; User user = userRepo.GetUser(username); //send mail to user SendMailSSL.SendOrderedBillPayPalToUser(user.Email, cart, user.FullName); return(RedirectToAction("Index", "Product")); }
public CartDetailsModel GetCart(Guid CartID) { using (_context = new karrykartEntities()){ var cartModel = new CartDetailsModel(); var cart = _context.Carts.Find(CartID); var productHelper = new ProductHelper(); if (cart != null) { cartModel.CartID = cart.ID; cartModel.CartCount = cart.CartProducts.Sum(x => x.Quantity).Value; foreach (var prod in cart.CartProducts) { var product = productHelper.GetProductDetail(prod.ProductID.Value); if (product != null) { cartModel.Products.Add(new CartProductModel(product, prod.Quantity.Value)); cartModel.CartTotal += Convert.ToDouble(product.Prices.FirstOrDefault().Price *prod.Quantity.Value); } } cartModel.TaxPercentage = 5; cartModel.SubTotal = ((double)(cartModel.TaxPercentage) / 100) * cartModel.CartTotal; cartModel.GrandTotal = cartModel.CartTotal + cartModel.SubTotal; cartModel.User = cart.CartUserID.Value; cartModel.Username = (_context.Users.Any(x => x.UserID == cart.CartUserID))?"Registered User":"******"; return(cartModel); } } return(null); }
public async Task <IHttpActionResult> AddToCart(CartDetailsModel cartDetails) { if (cartDetails == null) { return(BadRequest("Please provide valid inputs!")); } CommonResponse validatedResponse = await AuthService.ValidateUserAndToken(); if (!validatedResponse.IsError) { if (await CartService.AddToCart(cartDetails)) { var cartDetailsList = await CartService.GetCartDetails(cartDetails); if (cartDetailsList.Count > 0) { return(Ok(cartDetailsList)); } else { return(BadRequest("No Inventory record Exists!")); } } else { return(BadRequest("Transaction Cannot be Processed!")); } } else { return(Unauthorized()); } }//end of add
public async Task RefundOrderPaypal(string captureOrderId) { try { CartDetailsModel cart = (CartDetailsModel)Session["CartDetails"]; double total = cart.Total; var request = new CapturesRefundRequest(captureOrderId); request.Prefer("return=representation"); RefundRequest refundRequest = new RefundRequest() { Amount = new PayPalCheckoutSdk.Payments.Money { Value = "" + total, CurrencyCode = "USD" } }; request.RequestBody(refundRequest); var response = await PayPalClient.client().Execute(request); var result = response.Result <PayPalCheckoutSdk.Payments.Refund>(); if (result.Status.Equals("COMPLETED")) { TempData["RefundMess"] = "Refund money success !!"; } } catch (Exception e) { SendMailSSL.SendErrorToAdmin("Error at RefundOrderPaypal: " + e.ToString()); } }
private static List <Item> GetListItems(CartDetailsModel cart) { List <Item> result = new List <Item>(); foreach (ProductInCartDetailsModel p in cart.ProductsInCart) { result.Add( new Item { Name = p.ProductName, Description = p.ShortDescription, Sku = p.ProductID + "", UnitAmount = new Money { CurrencyCode = "USD", Value = p.Price + "" }, Tax = new Money { CurrencyCode = "USD", Value = (p.Price / 10) + "" }, Quantity = p.Quantity + "", Category = "PHYSICAL_GOODS" } ); } return(result); }
}//end of display method public static async Task <bool> DeleteCartDetail(CartDetailsModel cartDetails) { String SQL = "DELETE from CartDetails WHERE CartDetailID = '" + cartDetails.CartDetailID + "'"; using (SqlConnection dbConn = new SqlConnection(connectionString)) { try { dbConn.Open(); SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = SQL; cmd.Connection = dbConn; await cmd.ExecuteNonQueryAsync(); dbConn.Close(); return(true); } catch (Exception ex) { Console.WriteLine(ex); return(false); } finally { dbConn.Close(); } } }//end of delete
}//end of search public static async Task <bool> CartDetailExistToVoid(CartDetailsModel cartDetails) { using (SqlConnection dbConn = new SqlConnection(connectionString)) { var isReportExist = "SELECT * from CartDetails WHERE CartHeaderID = '" + cartDetails.CartHeaderID + "'"; SqlDataReader reader; try { dbConn.Open(); SqlCommand cmd = new SqlCommand(isReportExist, dbConn); reader = await cmd.ExecuteReaderAsync(); if (reader.HasRows) { return(true); } else { return(false); } } catch (Exception ex) { reader = null; Console.WriteLine(ex); return(false); } finally { dbConn.Close(); } } }//end of search
public static async Task <bool> AddToCart(CartDetailsModel cartDetails) { var dateAdded = DateTime.Now; String SQL = "INSERT INTO CartDetails(UserID, CartHeaderID, ProductID, Quantity, UnitPrice, TotalPrice, DateAdded)" + "VALUES('" + cartDetails.UserID + "', '" + cartDetails.CartHeaderID + "', '" + cartDetails.ProductID + "', '" + cartDetails.Quantity + "', '" + cartDetails.UnitPrice + "', '" + cartDetails.TotalPrice + "', '" + dateAdded + "')"; using (SqlConnection dbConn = new SqlConnection(connectionString)) { try { dbConn.Open(); SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = SQL; cmd.Connection = dbConn; await cmd.ExecuteNonQueryAsync(); dbConn.Close(); return(true); } catch (Exception ex) { Console.WriteLine(ex); return(false); } finally { dbConn.Close(); } } }//end of add
public async Task <IHttpActionResult> DeleteCartDetail(CartDetailsModel cartDetails) { if (cartDetails == null) { return(BadRequest("Please provide valid inputs!")); } CommonResponse validatedResponse = await AuthService.ValidateUserAndToken(); if (!validatedResponse.IsError) { if (await CartService.CartDetailExists(cartDetails)) { if (await CartService.DeleteCartDetail(cartDetails)) { return(Ok("Inventory Record Deleted Successfully!")); } else { return(BadRequest("Failed to Delete Inventory Record !")); } } else { return(BadRequest("No Such Inventory Record Exisits!")); } } else { return(Unauthorized()); } }//end of Delete
}//end of display method public static async Task <bool> UpdateInventoryAfterSales(int cartHeaderID) { List <CartDetailsModel> cartDetailsToDelete = new List <CartDetailsModel>(); var query = "SELECT * FROM CartDetails WHERE CartHeaderID ='" + cartHeaderID + "'"; SqlDataReader reader; using (SqlConnection dbConn = new SqlConnection(connectionString)) { try { dbConn.Open(); SqlCommand cmd = new SqlCommand(query, dbConn); reader = await cmd.ExecuteReaderAsync(); if (reader.HasRows) { while (reader.Read()) { CartDetailsModel cartDetailItem = new CartDetailsModel(); cartDetailItem.CartDetailID = reader.GetInt32(0); cartDetailItem.UserID = reader.GetInt32(1); cartDetailItem.CartHeaderID = reader.GetInt32(2); cartDetailItem.ProductID = reader.GetInt32(3); cartDetailItem.Quantity = reader.GetDecimal(4); cartDetailItem.UnitPrice = reader.GetDecimal(5); cartDetailItem.TotalPrice = reader.GetDecimal(6); cartDetailsToDelete.Add(cartDetailItem); } } dbConn.Close(); foreach (var item in cartDetailsToDelete) { InventoryModel inventoryToAdd = new InventoryModel() { ProductID = item.ProductID, Quantity = item.Quantity * (-1), Description = "Sales" }; await InventoryService.AddInventory(inventoryToAdd); } return(true); } catch (Exception ex) { Console.WriteLine(ex); return(false); } finally { dbConn.Close(); } } }//end of delete
private static string GetHtmlOrderedBillWithPayPal(CartDetailsModel cart, string fullName) { string content = "<br><font>The payment has been authorized and approved.<br>" + "<br>Have a good day.<br>" + "From Hana Shop</font>"; string messageBody = "<font>Dear " + fullName + ", <br><br>" + "Thank for your shopping !<br>" + "We have received $" + cart.Total + " that you submitted by PayPal at " + cart.LastTimeChange + ".<br></font>"; string htmlTableStart = "<table style=\"border-collapse:collapse; text-align:center;\" >"; string htmlTableEnd = "</table>"; string htmlHeaderRowStart = "<tr style=\"background-color:#6FA1D2; color:#ffffff;\">"; string htmlHeaderRowEnd = "</tr>"; string htmlTrStart = "<tr style=\"color:#555555;\">"; string htmlTrEnd = "</tr>"; string htmlTdStart = "<td style=\" border-color:#5c87b2; border-style:solid; border-width:thin; padding: 5px;\">"; string htmlTdStartMerge = "<td colspan=\"4\" style=\" border-color:#5c87b2; border-style:solid; border-width:thin; padding: 5px;\">"; string htmlTdEnd = "</td>"; messageBody += htmlTableStart; messageBody += htmlHeaderRowStart; messageBody += htmlTdStart + "STT" + htmlTdEnd; messageBody += htmlTdStart + "Product Name" + htmlTdEnd; messageBody += htmlTdStart + "Quantity" + htmlTdEnd; messageBody += htmlTdStart + "Unit Price" + htmlTdEnd; messageBody += htmlTdStart + "Total" + htmlTdEnd; messageBody += htmlHeaderRowEnd; int i = 1; foreach (ProductInCartDetailsModel p in cart.ProductsInCart) { messageBody = messageBody + htmlTrStart; messageBody = messageBody + htmlTdStart + i + htmlTdEnd; messageBody = messageBody + htmlTdStart + p.ProductName + htmlTdEnd; messageBody = messageBody + htmlTdStart + p.Quantity + htmlTdEnd; messageBody = messageBody + htmlTdStart + "$" + p.Price + htmlTdEnd; messageBody = messageBody + htmlTdStart + "$" + p.Total + htmlTdEnd; messageBody = messageBody + htmlTrEnd; i++; } //show total, tax, subTotal messageBody = messageBody + htmlTrStart; messageBody = messageBody + htmlTdStartMerge + "Subtotal: " + htmlTdEnd; messageBody = messageBody + htmlTdStart + "$" + cart.SubTotal + htmlTdEnd + htmlTrEnd; messageBody = messageBody + htmlTrStart; messageBody = messageBody + htmlTdStartMerge + "Tax: " + htmlTdEnd; messageBody = messageBody + htmlTdStart + "$" + cart.Tax + htmlTdEnd + htmlTrEnd; messageBody = messageBody + htmlTrStart; messageBody = messageBody + htmlTdStartMerge + "Total: " + htmlTdEnd; messageBody = messageBody + htmlTdStart + "$" + cart.Total + htmlTdEnd + htmlTrEnd; //end messageBody = messageBody + htmlTableEnd; messageBody = messageBody + content; return(messageBody); }
}//end of delete public static async Task <bool> VoidBill(CartDetailsModel cartDetails) { List <CartDetailsModel> cartDetailsToDelete = new List <CartDetailsModel>(); var query = "SELECT * FROM CartDetails WHERE CartHeaderID ='" + cartDetails.CartHeaderID + "'"; SqlDataReader reader; using (SqlConnection dbConn = new SqlConnection(connectionString)) { try { dbConn.Open(); SqlCommand cmd = new SqlCommand(query, dbConn); reader = await cmd.ExecuteReaderAsync(); if (reader.HasRows) { while (reader.Read()) { CartDetailsModel cartDetailItem = new CartDetailsModel(); cartDetailItem.CartDetailID = reader.GetInt32(0); cartDetailsToDelete.Add(cartDetailItem); } } dbConn.Close(); foreach (var item in cartDetailsToDelete) { dbConn.Open(); String SQL = "DELETE from CartDetails WHERE CartDetailID = '" + item.CartDetailID + "'"; SqlCommand cmd2 = new SqlCommand(); cmd2.CommandType = CommandType.Text; cmd2.CommandText = SQL; cmd2.Connection = dbConn; await cmd2.ExecuteNonQueryAsync(); dbConn.Close(); } return(true); } catch (Exception ex) { Console.WriteLine(ex); return(false); } finally { dbConn.Close(); } } }//end of delete
public ActionResult AddToCart(int productID, int quantity = 1) { CartDetailsModel cartDetailsModel = null; Bill userBill; try { Product product = GetProduct(productID); string username = HttpContext.User.Identity.Name; userBill = billRepo.GetUsersLastBillIsNotPay(username); if (userBill == null) { userBill = CreateBillUser(username); } int totalQuantity = quantity; if (productsInBillRepo.CheckBillContainProduct(userBill.BillID, productID)) { totalQuantity = totalQuantity + productsInBillRepo.GetQuantityAProductInBill(userBill.BillID, productID); } int statusProdInStock = CheckProductIsAvailableWithQuantity(product, totalQuantity); if (statusProdInStock == 1) { ProductsInBill productsInBill = new ProductsInBill(); productsInBill.BillID = userBill.BillID; productsInBill.ProductID = productID; productsInBill.ProductName = product.ProductName; productsInBill.Quantity = quantity; productsInBill.Price = product.Price; productsInBill.Total = product.Price * quantity; bool result = productsInBillRepo.InsertProductToBill(productsInBill); if (result) { UpdateBillDetails(userBill.BillID); TempData["MessageAddToCart"] = "Add to cart success!!"; } else { TempData["MessageAddToCart"] = "Error to Add to cart!!"; } } else { TempData["ErrorAddToCart"] = "Error to Add to cart!!"; } cartDetailsModel = LoadCartDetailsModel(userBill.BillID); }catch (Exception ex) { SendMailSSL.SendErrorToAdmin("Error at AddToCart: " + ex.ToString()); } return(Json(cartDetailsModel, JsonRequestBehavior.AllowGet)); }
public ActionResult LoadCartDetails(int IDBill = 0, string returnUrl = null) { CartDetailsModel cart = (CartDetailsModel)Session["CartDetails"]; if (!string.IsNullOrEmpty(returnUrl)) { TempData["returnUrl"] = returnUrl; } if (IDBill == 0 && cart != null) { IDBill = cart.BillID; } try { if (IDBill == 0) { ViewBag.CartNull = "You have no product in cart !!"; } else { //if session timeout if (cart == null) { LoadCartDetailsModel(IDBill); } if (cart != null) { if (cart.ProductsInCart != null) { CheckCartIsChangeInStock(cart); cart = LoadCartDetailsModel(IDBill); } else { ViewBag.CartNull = "You have no product in cart !!"; } } else { ViewBag.CartNull = "You have no product in cart !!"; } } } catch (Exception ex) { SendMailSSL.SendErrorToAdmin("Error at LoadCartDetails: " + ex.ToString()); } return(View("ShoppingCart", cart)); }
//public Task<PayPalHttp.HttpResponse> CreateOrderPaypal2() //{ // return CreateOrderSample.CreateOrder(true); // } private bool CheckProductInCart(CartDetailsModel cart) { bool result = true; foreach (ProductInCartDetailsModel pInCart in cart.ProductsInCart) { Product prod = productRepo.Products.FirstOrDefault(p => p.ProductID == pInCart.ProductID); if (prod.StatusCode.Equals("OUTS") || prod.StatusCode.Equals("STOP") || prod.Quantity < pInCart.Quantity || prod.Price != pInCart.Price) { result = false; break; } } return(result); }
}//end of search public static async Task <List <CartDetailsModel> > GetCartDetails(CartDetailsModel cartDetail) { List <CartDetailsModel> cartDetails = new List <CartDetailsModel>(); using (SqlConnection dbConn = new SqlConnection(connectionString)) { var query = "SELECT * FROM CartDetails WHERE CartHeaderID ='" + cartDetail.CartHeaderID + "'"; SqlDataReader reader; try { dbConn.Open(); SqlCommand cmd = new SqlCommand(query, dbConn); reader = await cmd.ExecuteReaderAsync(); if (reader.HasRows) { while (reader.Read()) { CartDetailsModel cartDetailItem = new CartDetailsModel(); cartDetailItem.CartDetailID = reader.GetInt32(0); cartDetailItem.UserID = reader.GetInt32(1); cartDetailItem.CartHeaderID = reader.GetInt32(2); cartDetailItem.ProductID = reader.GetInt32(3); cartDetailItem.Quantity = reader.GetDecimal(4); cartDetailItem.UnitPrice = reader.GetDecimal(5); cartDetailItem.TotalPrice = reader.GetDecimal(6); cartDetailItem.DateAdded = reader.GetDateTime(7); cartDetails.Add(cartDetailItem); } } } catch (Exception ex) { reader = null; Console.WriteLine(ex); } finally { dbConn.Close(); } return(cartDetails); } }//end of display method
private CartDetailsModel LoadCartDetailsModel(int IDBill) { CartDetailsModel cart = new CartDetailsModel(); try { Bill bill = billRepo.GetBillDetails(IDBill); IEnumerable <ProductsInBill> productsInBills = productsInBillRepo.GetListProductInBill(IDBill); cart.BillID = IDBill; cart.SubTotal = bill.SubTotal; cart.Tax = bill.Tax; cart.Total = bill.Total; cart.LastTimeChange = bill.LastTimeChange.ToString("dd/MM/yyyy HH:mm:ss"); int numProd = 0; if (productsInBills != null && productsInBills.Any()) { foreach (ProductsInBill p in productsInBills) { ProductInCartDetailsModel pInCart = new ProductInCartDetailsModel(); pInCart.ProductID = p.ProductID; pInCart.ProductName = p.ProductName; pInCart.Category = GetProductCategoryName(p.ProductID); pInCart.Kind = GetProductKindName(p.ProductID); pInCart.Quantity = p.Quantity; pInCart.Price = p.Price; pInCart.Total = p.Total; pInCart.ShortDescription = productRepo.GetShortDescription(p.ProductID); pInCart.StatusCode = productRepo.GetStatus(p.ProductID); if (cart.ProductsInCart == null) { cart.ProductsInCart = new List <ProductInCartDetailsModel>(); } cart.ProductsInCart.Add(pInCart); numProd = numProd + p.Quantity; } } cart.QuantityProduct = numProd; Session["CartDetails"] = cart; } catch (Exception e) { SendMailSSL.SendErrorToAdmin("Error at LoadCartDetailsModel: " + e.ToString()); } return(cart); }
public static void SendOrderedBillCODToUser(string mailReceive, CartDetailsModel cart, string fullname) { try { string content = GetHtmlOrderedBillWithCOD(cart, fullname); SmtpClient smtp = new SmtpClient(); smtp.Port = 587; smtp.Host = "smtp.gmail.com"; //for gmail host smtp.EnableSsl = true; smtp.UseDefaultCredentials = false; smtp.Credentials = new NetworkCredential("*****@*****.**", "sondep1809"); smtp.DeliveryMethod = SmtpDeliveryMethod.Network; MailMessage message = new MailMessage(); message.From = new MailAddress("*****@*****.**", "Hana Shop"); message.To.Add(new MailAddress(mailReceive)); message.Subject = "Orders are ready to ship to you"; message.IsBodyHtml = true; //to make message body as html message.Body = content; smtp.Send(message); } catch (Exception) { } }
public async Task <IHttpActionResult> GetCartDetails(CartDetailsModel cartDetails) { CommonResponse validatedResponse = await AuthService.ValidateUserAndToken(); if (!validatedResponse.IsError) { var cartDetailsList = await CartService.GetCartDetails(cartDetails); if (cartDetailsList.Count > 0) { return(Ok(cartDetailsList)); } else { return(BadRequest("No Cart Detail record Exists!")); } } else { return(Unauthorized()); } }//end of get
public int GetMaxQuantityCanAddToCart(int productID) { int result = 0; CartDetailsModel cart = (CartDetailsModel)Session["CartDetails"]; if (cart != null) { if (productsInBillRepo.CheckBillContainProduct(cart.BillID, productID)) { int quantityInCart = productsInBillRepo.GetQuantityAProductInBill(cart.BillID, productID); result = productRepo.GetQuantity(productID) - quantityInCart; } else { result = productRepo.GetQuantity(productID); } } else { result = productRepo.GetQuantity(productID); } return(result); }
private string BuildOrderHtml(CartDetailsModel cartDetails, Order order, Cart cart, UserDetails address, string OrderStatus) { StringBuilder orderHtml = new StringBuilder(); var productHelper = new ProductHelper(); orderHtml.Append("<p>Your Order has been placed successfully. Please find your order details below: </p>"); orderHtml.Append("<div class='well'>"); orderHtml.Append("<p>"); orderHtml.Append("<span><strong>OrderID </strong>: " + order.ID + "</span> <br>"); orderHtml.Append("<span><strong>PaymentMode </strong>: " + ((order.Payment.Type.Value == 1) ? "Cash On Delivery" : string.Empty) + "</span> <br>"); orderHtml.Append("<span><strong>Order Status </strong>: " + OrderStatus + "</span> <br>"); orderHtml.Append("</p>"); orderHtml.Append("<p>"); orderHtml.Append("Delivery Details:<br>"); orderHtml.Append(address.AddressList.FirstOrDefault().AddressLine1 + "<br>"); orderHtml.Append(address.AddressList.FirstOrDefault().AddressLine2 + "<br>"); orderHtml.Append(address.AddressList.FirstOrDefault().City + "," + address.AddressList.FirstOrDefault().State + "," + address.AddressList.FirstOrDefault().Country + "<br>"); orderHtml.Append("Pincode - " + address.AddressList.FirstOrDefault().PinCode + "<br>"); orderHtml.Append("Phone - " + address.Phone + "<br>"); if (!string.IsNullOrEmpty(address.AddressList.FirstOrDefault().LandMark)) { orderHtml.Append("LandMark - " + address.AddressList.FirstOrDefault().LandMark + "<br>"); } orderHtml.Append("</p>"); orderHtml.Append("<table style='border-collapse: collapse;border:1px solid #fcfcfc'><thead style='background-color:#06B4F0;color:#fff;font-weight:bold'>"); orderHtml.Append("<td>Product</td>"); orderHtml.Append("<td>Quantity</td>"); orderHtml.Append("<td>Price (INR)</td>"); orderHtml.Append("<td>Total Price (INR)</td>"); orderHtml.Append("</th>"); orderHtml.Append("</thead>"); orderHtml.Append("<tbody>"); foreach (var product in cart.CartProducts) { var productDetails = productHelper.GetProductDetail(product.ProductID.Value); orderHtml.Append("<tr style='padding:5px'>"); orderHtml.Append("<td>" + productDetails.Name + "</td>"); orderHtml.Append("<td>" + product.Quantity + "</td>"); orderHtml.Append("<td>" + productDetails.Prices.FirstOrDefault().Price.ToString() + "</td>"); orderHtml.Append("<td>" + (product.Quantity * productDetails.Prices.FirstOrDefault().Price).ToString() + "</td>"); orderHtml.Append("</tr>"); } orderHtml.Append("<tr style='padding:5px'>"); orderHtml.Append("<td>Tax(" + cartDetails.TaxPercentage + "%) </td>"); orderHtml.Append("<td></td>"); orderHtml.Append("<td></td>"); orderHtml.Append("<td>" + cartDetails.SubTotal + "</td>"); orderHtml.Append("</tr>"); orderHtml.Append("<tr style='padding:5px'>"); orderHtml.Append("<td><b>Grand Total</b></td>"); orderHtml.Append("<td></td>"); orderHtml.Append("<td></td>"); orderHtml.Append("<td><b>" + cartDetails.GrandTotal + "</b></td>"); orderHtml.Append("</tr>"); orderHtml.Append("</tbody>"); orderHtml.Append("</table>"); return(orderHtml.ToString()); }
//Below function can be used to build the create order request body with complete payload. public static OrderRequest BuildRequestBody(string fullname, string address, string street, string city, CartDetailsModel cart) { OrderRequest orderRequest = new OrderRequest() { CheckoutPaymentIntent = "AUTHORIZE", ApplicationContext = new ApplicationContext { BrandName = "Hana Shop", LandingPage = "BILLING", CancelUrl = "https://hanashop1.azurewebsites.net/Cart/LoadCartDetails", ReturnUrl = "https://hanashop1.azurewebsites.net/CheckOut/AuthorizeCaptureOrderPaypal", UserAction = "CONTINUE", ShippingPreference = "SET_PROVIDED_ADDRESS" }, PurchaseUnits = new List <PurchaseUnitRequest> { new PurchaseUnitRequest { ReferenceId = "PUHF", Description = "Sporting Goods", CustomId = "CUST-HighFashions", SoftDescriptor = "HighFashions", AmountWithBreakdown = new AmountWithBreakdown { CurrencyCode = "USD", Value = cart.Total + "", AmountBreakdown = new AmountBreakdown { ItemTotal = new Money { CurrencyCode = "USD", Value = cart.SubTotal + "" }, Shipping = new Money { CurrencyCode = "USD", Value = "00.00" }, Handling = new Money { CurrencyCode = "USD", Value = "00.00" }, TaxTotal = new Money { CurrencyCode = "USD", Value = cart.Tax + "" }, ShippingDiscount = new Money { CurrencyCode = "USD", Value = "00.00" } } }, Items = GetListItems(cart), ShippingDetail = new ShippingDetail { Name = new Name { FullName = fullname }, AddressPortable = new AddressPortable { AddressLine1 = address, AddressLine2 = street, AdminArea2 = city, AdminArea1 = "CA", PostalCode = "94107", CountryCode = "US" } } } } }; return(orderRequest); }
public async Task <ActionResult> AuthorizeCaptureOrderPaypal() { CartDetailsModel cart = (CartDetailsModel)Session["CartDetails"]; try { if (CheckProductInCart(cart)) { //neu on het thi tien hanh thanh toan string orderId = Request["token"]; var requestAuthorization = new OrdersAuthorizeRequest(orderId); requestAuthorization.Prefer("return=representation"); requestAuthorization.RequestBody(new AuthorizeRequest()); var responseAuthorization = await PayPalClient.client().Execute(requestAuthorization); var resultAuthorization = responseAuthorization.Result <Order>(); if (resultAuthorization.Status.Equals("COMPLETED")) { //if success //get authorizationID string AuthorizationId = resultAuthorization.PurchaseUnits[0].Payments.Authorizations[0].Id; var requestCapture = new AuthorizationsCaptureRequest(AuthorizationId); requestCapture.Prefer("return=representation"); requestCapture.RequestBody(new CaptureRequest()); //execute capture var responseCapture = await PayPalClient.client().Execute(requestCapture); var captureOrderResult = responseCapture.Result <PayPalCheckoutSdk.Payments.Capture>(); if (captureOrderResult.Status.Equals("PENDING"))//success { //check lai xem con hang trong kho k sau khi customer da thanh toan xong //neu k thi refund tien r tra ve trang shopping-cart if (!CheckProductInCart(cart)) { await RefundOrderPaypal(captureOrderResult.Id); return(RedirectToAction("LoadCartDetails", "Cart")); } else { return(FinishOrderPaypal(cart)); } } else { TempData["ErrorOrder"] = "Error to order by PayPal!!"; return(RedirectToAction("LoadCartDetails", "Cart")); } } else { TempData["ErrorOrder"] = "Error to order by PayPal!!"; return(RedirectToAction("LoadCartDetails", "Cart")); } } else { TempData["ErrorOrder"] = "Error to order by PayPal!!"; return(RedirectToAction("LoadCartDetails", "Cart")); } } catch (Exception e) { SendMailSSL.SendErrorToAdmin("Error at AuthorizeCaptureOrderPaypal: " + e.ToString()); } return(RedirectToAction("LoadCartDetails", "Cart")); }