/** CREATE ASYNC */ public async Task <CreateResult <Order> > CreateAsync( Order order, int requestedUserId, string stripeSecretKey) { var customer = await _context.Customers .Where(c => c.UserId == requestedUserId) .Include(c => c.Cart) .Include(c => c.User) .FirstOrDefaultAsync(); var chosenPaymentMethod = await _context.PaymentMethods .SingleOrDefaultAsync(x => x.Id == order.PaymentMethodId); /** Get all products in cart of customer to create order */ var cartDetails = await GetListCartDetailToPay(customer.Cart.Id); if (cartDetails.Count() == 0) { return(new CreateResult <Order> { IsSuccess = false, Errors = new List <string>() { "Bạn không có sản phẩm trong giỏ hàng để thanh toán" } }); } /** Get all product tiers in order items from db to use */ var productTiers = await GetListProductTierFromCartDetails(cartDetails); List <OrderItem> orderItems = CreateListOrderItemFromProductsInCart( cartDetails, productTiers ); PrepareOrderInfo( order, orderItems, productTiers, customer.Id); using (var transaction = _context.Database.BeginTransaction()) { try { /** Handle stripe payment (if choose) */ HandleStripePaymentIfPaymentMethodIsStripe( chosenPaymentMethod, order, stripeSecretKey ); /** Create order */ await _context.Orders.AddAsync(order); var orderCreated = await _context.SaveChangesAsync(); if (!(orderCreated > 0)) { transaction.Dispose(); throw new Exception("Thanh toán giỏ hàng thất bại, xin thử lại"); } /** Create order items */ bool isCreateOrderItemsSuccess = await CreateOrderItemsOfOrder( orderItems, order, productTiers ); if (!isCreateOrderItemsSuccess) { transaction.Dispose(); throw new Exception("Thanh toán giỏ hàng thất bại, xin thử lại"); } /** Clear all cart items after pay cart (after create order) */ var areAllCartDetailsCleared = await ClearAllCartItemsAfterPayCart( cartDetails ); if (!areAllCartDetailsCleared) { transaction.Dispose(); throw new Exception("Thanh toán giỏ hàng thất bại, xin thử lại"); } await transaction.CommitAsync(); } catch (Exception e) { return(new CreateResult <Order> { IsSuccess = false, Errors = new List <string>() { e.Message.ToString() } }); } } /** Send mail to user */ string orderMailTemplate = _emailTemplateService .CreateOrderHtmlTempalteToSendMailToCustomer( order.Code, order.TotalAmount, order.CreatedAt, orderItems, productTiers, customer.Name, customer.User.Email ); _emailService.SendMail( customer.User.Email, customer.Name, $"Đơn hàng của khách hàng '{customer.Name}' vào {order.CreatedAt.ToString("dd/MM/y yyy HH:mm:ss")}", orderMailTemplate ); return(new CreateResult <Order> { IsSuccess = true, EntityReturn = order }); }