public string SignCheckoutRequest(CheckoutRequest checkoutRequest) { string data = JsonConvert.SerializeObject(checkoutRequest, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore }); var signature = _signService.Sign(data); return(Convert.ToBase64String(Encoding.UTF8.GetBytes(signature + "|" + data))); }
public async Task <ActionResult <CheckoutResponse> > Checkout(Guid cartId) { var request = new CheckoutRequest { Id = cartId }; request.Headers = HttpContext.Request.GetOpenTracingInfo(); var response = await _cartService.CheckoutAsync(request); return(Ok(response)); }
/// <summary> /// Asks to checkout a vehicle won on an auction. /// </summary> /// <returns>The checkout.</returns> public async Task <CommonResponse> PostCheckout(CheckoutRequest pCheckoutRequest) { var request = new RestRequest(Method.POST); request.RequestFormat = DataFormat.Json; request.Resource = GlobalSetting.Instance.Vehicle_PostCheckout; // Add body parameters request.AddJsonBody(pCheckoutRequest); // Execute return(await _requestProvider.ExecuteAsync <CommonResponse>(request)); }
public GatewayCheckoutResponse InitiateGatewayChechout(CheckoutRequest request, GatewayToken token) { GatewayCheckoutResponse gatewayResponse = null; try { var gatewayCheckoutRequest = _translatorService.GetGatewayCheckoutRequest(request); var url = _httpContextService.Request.Url; var server = $"{url.Scheme}://{url.Authority}/"; int requestid = _repository.SaveCheckoutRequest(request); if (requestid > 0) { var randomKey = Guid.NewGuid().ToString("N"); var key = Md5Helper.GetMd5Hash(requestid + randomKey + randomKey + requestid); var checkoutCompleteUrl = $"{server}{"checkoutresponse"}?id={requestid}&rk={randomKey}&k={key}"; gatewayCheckoutRequest.checkout_complete_url = checkoutCompleteUrl; gatewayCheckoutRequest.order_reference_id = requestid.ToString() + "_" + request.orderid.ToString(); var baseUrl = ConfigurationManager.AppSettings["BaseURLWebAPIService"]; var response = _webApiClient.HTTPPostRequest(baseUrl, "checkouts", gatewayCheckoutRequest, token.token); if (response == null) { _repository.UpdateCheckoutRequestStatus(request.id, Status.Failed); } else { if (response.StatusCode == HttpStatusCode.Created) { using (var streamReader = new StreamReader(response.GetResponseStream())) { var responseText = streamReader.ReadToEnd(); gatewayResponse = JsonConvert.DeserializeObject <GatewayCheckoutResponse>(responseText); } } } } } catch (Exception ex) { _repository.UpdateCheckoutRequestStatus(request.id, Status.Failed); throw ex; } return(gatewayResponse); }
public async Task <IActionResult> CheckoutAsync(CheckoutRequest checkoutRequest) { if (!ModelState.IsValid) { return(BadRequest(ModelState.GetErrorMessages())); } var UserId = HttpContext.GetUserId(); var result = await _checkoutService.CheckoutBooksAsync(checkoutRequest, UserId); return(Ok(result)); }
public async Task <CheckoutResponse> CheckoutAsync(CheckoutRequest request) { var cart = await GetCart(request.Id); cart.IsCheckout = true; var checkoutCart = await _mutateRepository.UpdateAsync(cart); return(new CheckoutResponse { IsSucceed = checkoutCart != null }); }
public HttpResponseMessage InitiatePayUCheckout() { HttpResponseMessage httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK); string strRequest = string.Empty; try { strRequest = Request.Content.ReadAsStringAsync().Result; if (string.IsNullOrWhiteSpace(strRequest)) { httpResponseMessage.StatusCode = System.Net.HttpStatusCode.InternalServerError; httpResponseMessage.Content = new StringContent(Constants.INVALID_REQUEST); return(httpResponseMessage); } JsonSerializerHelper serializer = new JsonSerializerHelper(); CheckoutRequest checkoutRequest = (CheckoutRequest)serializer.Deserialize(strRequest, typeof(CheckoutRequest)); if (checkoutRequest == null) { httpResponseMessage.StatusCode = System.Net.HttpStatusCode.InternalServerError; httpResponseMessage.Content = new StringContent(Constants.INVALID_REQUEST); return(httpResponseMessage); } Configuration config = new Configuration(); config.PayUFailureUrl = "FailureUrl"; config.PayUSuccessUrl = "SuccessUrl"; config.PayUSalt = "Salt"; config.PayUKey = "Key"; PayUManager payUManager = new PayUManager(config); CheckoutResponse response = payUManager.InitiateCheckout(checkoutRequest); if (response != null && response.Status == Status.Success) { string responseContent = serializer.Serialize(response); httpResponseMessage.Content = new StringContent(responseContent, Encoding.UTF8, "application/json"); } else { httpResponseMessage.StatusCode = System.Net.HttpStatusCode.InternalServerError; httpResponseMessage.Content = new StringContent(Constants.PROCESSING_ERROR); } } catch (Exception ex) { this.HandleException(ex, strRequest); httpResponseMessage.StatusCode = System.Net.HttpStatusCode.InternalServerError; httpResponseMessage.Content = new StringContent(Constants.PROCESSING_ERROR); } return(httpResponseMessage); }
public async Task <bool> CreateOrder(CheckoutRequest request) { var client = _httpClientFactory.CreateClient(); client.BaseAddress = new Uri(_configuration["BaseAddress"]); var json = JsonConvert.SerializeObject(request); var httpContent = new StringContent(json, Encoding.UTF8, "application/json"); var response = await client.PostAsync($"/api/carts/", httpContent); return(response.IsSuccessStatusCode); }
public async Task <IActionResult> Checkout(CheckoutViewModel request) { string userId = ""; var model = GetCheckOutViewModel(); request.CartItems = model.CartItems; var orderDetails = new List <OrderDetailViewModel>(); var checkoutRequest = new CheckoutRequest() { Name = request.CheckoutRequest.Name, Address = request.CheckoutRequest.Address, Email = request.CheckoutRequest.Email, PhoneNumber = request.CheckoutRequest.PhoneNumber, OrderDetailViewModel = orderDetails }; if (User.Identity.IsAuthenticated) { userId = User.FindFirst(ClaimTypes.NameIdentifier).Value; checkoutRequest.UserId = Guid.Parse(userId); } else { TempData["LoginRequired"] = "Please login before check out!"; return(View(request)); } foreach (var item in model.CartItems) { orderDetails.Add(new OrderDetailViewModel() { ProductId = item.ProductId, Quantity = item.Quantity, Price = item.Price }); } //TODO: send request to API var result = await _orderApiClient.CreateOrder(checkoutRequest); if (result) { TempData["Success"] = "Order purchase successful!"; } return(View(request)); }
protected BaseItemUpdateRequest( string category, CheckoutRequest checkout, CompletionStatusReference completionStatus, string countryOfOrigin, string countryPurchased, string genre, string imageUrl, bool isNew, bool isPhysical, bool isReissue, ItemStorageRequest itemStorage, string locationPurchased, string notes, DateTimeOffset purchasedOn, int?reissueYear, int timesCompleted, string title, ApplicationUser user, int yearReleasedOn) { Guard.Against.NullOrWhiteSpace(title, nameof(title)); Guard.Against.Null(user, nameof(user)); Guard.Against.Default(user.Id, nameof(user.Id)); if (isReissue) { Guard.Against.Null(reissueYear, nameof(reissueYear)); Guard.Against.NegativeOrZero(reissueYear.GetValueOrDefault(), nameof(reissueYear)); } Category = category; Checkout = checkout; CompletionStatus = completionStatus; CountryOfOrigin = countryOfOrigin; CountryPurchased = countryPurchased; Genre = genre; ImageUrl = imageUrl; IsNew = isNew; IsPhysical = isPhysical; IsReissue = isReissue; ItemStorage = itemStorage; LocationPurchased = locationPurchased; Notes = notes; PurchasedOn = purchasedOn; ReissueYear = reissueYear; TimesCompleted = timesCompleted; Title = title; User = user; YearReleasedOn = yearReleasedOn; }
protected void CreditCardButton_Click(object sender, EventArgs e) { if (Page.IsValid && CustomValidation()) { //CREATE THE PAYMENT OBJECT Payment payment = GetPayment(); //PROCESS CHECKING OUT EVENT bool checkOut = true; if (CheckingOut != null) { CheckingOutEventArgs c = new CheckingOutEventArgs(payment); CheckingOut(this, c); checkOut = !c.Cancel; } if (checkOut) { //PROCESS A CHECKOUT ICheckoutService checkoutService = AbleContext.Resolve <ICheckoutService>(); CheckoutRequest checkoutRequest = new CheckoutRequest(_Basket, payment); CheckoutResponse checkoutResponse = checkoutService.ExecuteCheckout(checkoutRequest, false); if (checkoutResponse.Success) { if (CheckedOut != null) { CheckedOut(this, new CheckedOutEventArgs(checkoutResponse)); } Response.Redirect(AbleCommerce.Code.NavigationHelper.GetReceiptUrl(checkoutResponse.Order.OrderNumber)); } else { IList <string> warningMessages = checkoutResponse.WarningMessages; if (warningMessages.Count == 0) { warningMessages.Add("The order could not be submitted at this time. Please try again later or contact us for assistance."); } if (CheckedOut != null) { CheckedOut(this, new CheckedOutEventArgs(checkoutResponse)); } } } } else { CreditCardButton.Text = "Pay With Card"; } // IF NOT SUCCESSFULL / ENABLE THE CHECKOUT BUTTON CreditCardButton.Enabled = true; FormIsSubmitted.Value = "0"; }
public decimal CheckoutProducts([FromBody] CheckoutRequest checkoutRequest) { List <Product> products = _productData.Get(); List <PricingRule> pricingRules = _pricingService.GetPricingRules(checkoutRequest.CustomerID); Checkout checkout = Checkout.New(pricingRules); foreach (string productID in checkoutRequest.ProductIDs) { Product product = products.FirstOrDefault(p => p.Id == productID); checkout.Add(product); } return(checkout.Total()); }
private void InitializeCheckoutCommand(ref SqlCommand c, CheckoutRequest m) { c.CommandType = System.Data.CommandType.StoredProcedure; c.CommandText = "Book.CheckOutBook"; c.Parameters.AddWithValue("@Email", m.Payload.Email); c.Parameters.AddWithValue("@BookID", m.Payload.IDs[0]); SqlParameter p = new SqlParameter("@DueDate", System.Data.SqlDbType.DateTime2); SqlParameter cID = new SqlParameter("@CheckOutID", System.Data.SqlDbType.Int); p.Direction = System.Data.ParameterDirection.Output; cID.Direction = System.Data.ParameterDirection.Output; c.Parameters.Add(p); c.Parameters.Add(cID); }
public override async Task <CheckoutResponse> Checkout(CheckoutRequest request, ServerCallContext context) { var cartCommander = _commandFactory.RepositoryAsync <Domain.Cart>(); var cartQuery = _queryFactory.QueryEfRepository <Domain.Cart>(); var cart = await cartQuery.GetFullCartAsync(request.CartId.ConvertTo <Guid>()); var checkoutCart = await cartCommander.UpdateAsync(cart.Checkout()); return(new CheckoutResponse { IsSucceed = checkoutCart != null }); }
public async Task <IActionResult> Create([FromBody] CheckoutRequest request) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var result = await _orderService.Create(request); if (result != 0) { return(BadRequest(result)); } return(Ok(result)); }
private void DoRequest(CheckoutRequest req) { var resp = new Url().Post(req); if (resp.Error != null) { DataError = resp.Error.ErrorMessage; Data = resp.Error.RequestId; } else { Response.Redirect(resp.checkout_url); } }
public async Task <IActionResult> Checkout([FromBody] CheckoutRequest request) { Cart cart = await _cartRepository.FindByUser(User.Identity.Name); if (cart == null) { return(StatusCode((int)HttpStatusCode.NotFound, new ErrorResponse(ErrorReasons.NotFound, "Cart not found."))); } var discounts = await _discountRepository.GetDiscounts(); var cartVm = cart.GetCartVM(); _discountService.CalculateDiscountsForItems(cartVm.Items, discounts); request.Amount = Convert.ToInt64(cartVm.Items.Sum(i => (i.Discount == 0 ? i.Price : i.Discount) * i.Count * 100)); var user = await _userManager.FindByNameAsync(User.Identity.Name); var order = new Order { User = user, Items = cartVm.Items.Select(i => new OrderItem() { Count = i.Count, Price = i.Discount == 0 ? i.Price : i.Discount, ItemID = i.ItemID }).ToList(), DeliveryAddress = JsonConvert.SerializeObject(request.Address), Status = OrderStatus.Accepted }; order = await _orderRepository.Insert(order); request.Number = request.Number.Replace(" ", string.Empty); var paymentResponse = await _paymentService.ProcessPaymentAsync(request); if (paymentResponse.IsSuccessfullResponse) { await _orderRepository.SaveChanges(); await _emailSender.SendOrderCreationEmailAsync(user.Email, order.OrderNumber.ToString()); await _cartRepository.ClearCart(cart); return(StatusCode((int)HttpStatusCode.OK, "Email sent")); } return(StatusCode(paymentResponse.ResponseCode, paymentResponse)); }
public async Task <IActionResult> Checkout(CheckOutViewModel request) { var userId = _userService.GetUserId(); var user = await _userManager.FindByIdAsync(userId); var model = GetCheckoutViewModel(); var checkoutRequest = new CheckoutRequest() { Address = request.CheckoutModel.Address, FirstName = request.CheckoutModel.FirstName, LastName = request.CheckoutModel.LastName, Email = request.CheckoutModel.Email, Phone = request.CheckoutModel.Phone, //OrderDetails = orderDetails }; var order = new Order() { TotalMoney = model.CartItems.Sum(m => m.Price) - model.CartItems.Sum(m => m.Value_Discount), Address = checkoutRequest.Address, Receiver = checkoutRequest.FirstName + ' ' + checkoutRequest.LastName, SDT = checkoutRequest.Phone, User = user, Process = "Mới đặt" }; _context.Add(order); await _context.SaveChangesAsync(); var order_success = _context.Order.ToList().LastOrDefault(); foreach (var item in model.CartItems) { if (item.Color_Product != null) { OrderDetail orderdetail = new OrderDetail() { ID_Color_Product = item.Color_Product.ID_Color_Product, Size = item.Size, Quantity = item.Amount, ID_Order = order_success.ID_Order, }; _context.Add(orderdetail); await _context.SaveChangesAsync(); } } ClearCart(); TempData["SuccessMsg"] = "Order puschased successful"; return(RedirectToAction("HistoryOrder", "Client_Orders")); }
public async Task <ActionResult> Create([FromBody] CheckoutRequest checkoutRequest) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var order = await _orderService.Create(checkoutRequest); if (order == 0) { return(BadRequest(order)); } return(Ok(order)); }
private void DoRequest(CheckoutRequest req) { var resp = new Url().Post(req); if (resp.Error != null) { DataError = resp.Error.ErrorMessage; Data = resp.Error.RequestId; } else { Data = resp.payment_id.ToString(); DataUri = resp.checkout_url; } }
public async Task <bool> CreateOrder(CheckoutRequest request) { var jsonRequest = System.Text.Json.JsonSerializer.Serialize(request); var httpContent = new StringContent(jsonRequest, Encoding.UTF8, "application/json"); var client = _httpClientFactory.CreateClient(); client.BaseAddress = new Uri(_configuration[SystemConstant.AppSettings.BaseAddress]); using var response = await client.PostAsync($"/api/Orders/create", httpContent); if (response.IsSuccessStatusCode) { return(true); } return(false); }
public CheckoutRequest GetCurrentRequest(int id) { CheckoutRequest currentRequest = null; var requests = _repository.GetCheckoutRequests(id); if (requests.Count > 0) { if (requests[0].id == id) { currentRequest = requests[0]; } } return(currentRequest); }
public HttpResponseMessage PostCheckOut(CheckoutRequest request) { if (request == null) { return base.CreateErrorEmptyResponse(); }//if User u = new User { username = request.username, sessionToken = request.sessionToken, }; LocationResponse response = this.LocationService.CheckOut(u); return this.Request.CreateResponse(HttpStatusCode.OK, response); }
private Safe2Pay_Request(Config config) { this.config = config; client = new Client(config); Account = new AccountRequest(this.config); Carnet = new CarnetRequest(this.config); Invoice = new InvoiceRequest(this.config); Marketplace = new MarketplaceRequest(this.config); Payment = new CheckoutRequest(this.config); //Plan = new PlanRequest(this.config); //Subscription = new SubscriptionRequest(this.config); Token = new TokenRequest(this.config); Transfer = new TransferRequest(this.config); Transaction = new TransactionRequest(this.config); }
protected void CheckButton_Click(object sender, EventArgs e) { if (Page.IsValid) { //CREATE THE PAYMENT OBJECT Payment payment = GetPayment(); //PROCESS CHECKING OUT EVENT bool checkOut = true; if (CheckingOut != null) { CheckingOutEventArgs c = new CheckingOutEventArgs(payment); CheckingOut(this, c); checkOut = !c.Cancel; } if (checkOut) { //PROCESS THE CHECKOUT ICheckoutService checkoutService = AbleContext.Resolve <ICheckoutService>(); CheckoutRequest checkoutRequest = new CheckoutRequest(_Basket, payment); CheckoutResponse checkoutResponse = checkoutService.ExecuteCheckout(checkoutRequest, false); if (checkoutResponse.Success) { if (CheckedOut != null) { CheckedOut(this, new CheckedOutEventArgs(checkoutResponse)); } Response.Redirect(AbleCommerce.Code.NavigationHelper.GetReceiptUrl(checkoutResponse.Order.OrderNumber)); } else { IList <string> warningMessages = checkoutResponse.WarningMessages; if (warningMessages.Count == 0) { warningMessages.Add("The order could not be submitted at this time. Please try again later or contact us for assistance."); } if (CheckedOut != null) { CheckedOut(this, new CheckedOutEventArgs(checkoutResponse)); } } } } else { CheckButton.Text = string.Format("Pay by {0}", _PaymentMethod.Name); } }
public async Task <IActionResult> CheckoutAsync(CheckoutRequest checkoutRequest) { ShoppingCartItem[] items = await _shoppingCart.GetShoppingCartItems(); _shoppingCart.ShoppingCartItems = items; if (_shoppingCart.ShoppingCartItems.Count() == 0) { ModelState.AddModelError(string.Empty, "Your cart is empty, add some merchandises first!"); } Order order = new Order { AddressLine1 = checkoutRequest.AddressLine, AddressLine2 = checkoutRequest.AddressLine2, City = checkoutRequest.City, FirstName = checkoutRequest.FirstName, LastName = checkoutRequest.LastName, Country = checkoutRequest.Country, PhoneNumber = checkoutRequest.PhoneNumber, State = checkoutRequest.State, ZipCode = checkoutRequest.Zipcode, Email = checkoutRequest.Email, }; if (ModelState.IsValid) { string username = _userManager.GetUserId(HttpContext.User); AppUser user = await _userManager.FindByNameAsync(username); order.UserId = user.Id; Task <Order> orderTask = _orderRepository.CreateOrder(order); order = await orderTask; Task <bool> mailTask = _mailService.SendOrderCreatedEmailAsync(user, order); await mailTask; Task clearCartTask = _shoppingCart.ClearCart(); await clearCartTask; return(Ok(new BaseResponse <Order> { Data = order, Success = true })); } return(BadRequest(new BaseResponse <string> { Data = null, Errors = ModelState.Values.SelectMany(err => err.Errors.Select(errm => errm.ErrorMessage)), Success = false, })); }
public async Task <IActionResult> Create(CheckoutRequest request) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var order = await _orderService.CreateOrder(request); if (order == 0) { return(BadRequest()); } return(Ok(order)); }
public async Task <IActionResult> CreateOrder([FromBody] CheckoutRequest request) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var orderId = await _orderService.CreateOrder(request); if (orderId == 0) { return(BadRequest()); } var order = await _orderService.GetOrderById(orderId); return(CreatedAtAction(nameof(GetOrderById), new { id = orderId }, orderId)); }
public void TestCheckoutCustomerDoesntExist() { CheckoutRequest request = new CheckoutRequest() { BookIdentifier = 1, CustomerIdentifier = 1 }; try { myLogic.CheckoutABook(request); } catch (Exception e) { Assert.IsTrue(e != null); Assert.IsTrue(e.Message.Contains("The customer does not exist in this system")); } }
public ActionResult Checkout([FromBody] CheckoutRequest checkoutRequest) { if (ModelState.IsValid) { try { bool success = _libraryLogic.CheckoutABook(checkoutRequest); if (success) { return(Ok(new Response <bool> { Status = "200", ResponseMessage = "Book Checked out successfully.", ResponseData = success })); } else { return(BadRequest(new Response <bool> { Status = "500", ResponseMessage = "Book Checkout did not succeed. Please try again later", ResponseData = success })); } } catch (Exception e) { return(BadRequest(new Response <string> { Status = "500", ResponseMessage = "Book Checkout did not succeed. Please try again later", ResponseData = e.Message })); } } else { return(BadRequest(new Response <bool> { Status = "400", ResponseMessage = string.Join(" | ", ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage)), ResponseData = false })); } }
private void Submit(object sender, EventArgs e) { int amount = Convert.ToInt32(Request.Form["amount"].Substring(0, Request.Form["amount"].IndexOf('.') > 0 ? Request.Form["amount"].IndexOf('.') : Request.Form["amount"].Length)); var req = new CheckoutRequest { order_id = Request.Form["order_id"], amount = amount * 100, order_desc = "checkout reverse demo", currency = "USD", response_url = Request.Url.Scheme + "://" + Request.Url.Authority + "/order_reverse.aspx" }; DoRequest(req); }
public void create_customer_checkout() { var api = new CoinbaseApi(ApiKey, ApiSecretKey, useSandbox: true, proxy: proxy, useTimeApi: true); var purchaseId = Guid.NewGuid().ToString("n"); var request = new CheckoutRequest { Amount = 10.00m, Currency = "USD", Name = "Test Order", Metadata = { {"purchaseId", purchaseId} }, NotificationsUrl = "" }; request.Dump(); var checkout = api.CreateCheckout(request); checkout.Dump(); if( checkout.Errors.Length == 0 ) { var redirectUrl = api.GetCheckoutUrl(checkout); //do redirect with redirectUrl } else { //Error making checkout page. } var checkoutUrl = api.GetCheckoutUrl(checkout); checkoutUrl.Should().StartWith("https://sandbox.coinbase.com/checkouts"); }