Esempio n. 1
0
        public ActionResult Index(string emailAddress = "*****@*****.**")
        {
            var loadCartRequest = new LoadCartRequest("CommerceEngineDefaultStorefront", "Default", "1234");
            var loadCartResult  = _cartServiceProvider.LoadCart(loadCartRequest);

            var cart = loadCartResult.Cart as CommerceCart;

            cart.Email = emailAddress;

            // Save the cart as an order
            var submitVisitorOrderRequest = new SubmitVisitorOrderRequest(cart);
            var submitVisitorOrderResult  = _orderServiceProvider.SubmitVisitorOrder(submitVisitorOrderRequest);

            return(View("Order", submitVisitorOrderResult));
        }
        public ManagerResponse <SubmitVisitorOrderResult, CommerceOrder> SubmitVisitorOrder(string userId, SubmitOrderInputModel inputModel)
        {
            Assert.ArgumentNotNull(inputModel, nameof(inputModel));

            var errorResult = new SubmitVisitorOrderResult {
                Success = false
            };

            var response = CartManager.GetCart(userId, true);

            if (!response.ServiceProviderResult.Success || response.Result == null)
            {
                response.ServiceProviderResult.SystemMessages.ToList().ForEach(m => errorResult.SystemMessages.Add(m));
                return(new ManagerResponse <SubmitVisitorOrderResult, CommerceOrder>(errorResult, null));
            }

            var cart = (CommerceCart)response.ServiceProviderResult.Cart;

            if (cart.Lines.Count == 0)
            {
                errorResult.SystemMessages.Add(new SystemMessage
                {
                    Message = DictionaryPhraseRepository.Current.Get("/System Messages/Orders/Submit Order Has Empty Cart", "Cannot submit and order with an empty cart.")
                });
                return(new ManagerResponse <SubmitVisitorOrderResult, CommerceOrder>(errorResult, null));
            }

            cart.Email = inputModel.UserEmail;

            var request = new SubmitVisitorOrderRequest(cart);

            RefreshCartOnOrdersRequest(request);
            errorResult = OrderServiceProvider.SubmitVisitorOrder(request);
            if (errorResult.Success && errorResult.Order != null && errorResult.CartWithErrors == null)
            {
                CartCacheHelper.InvalidateCartCache(userId);

                try
                {
                    var wasEmailSent = MailManager.SendMail("PurchaseConfirmation", inputModel.UserEmail, string.Join(" ", cart.Parties.FirstOrDefault()?.FirstName, cart.Parties.FirstOrDefault()?.LastName), errorResult.Order.TrackingNumber, errorResult.Order.OrderDate, string.Join(", ", cart.Lines.Select(x => x.Product.ProductName)), cart.Total.Amount.ToCurrency(cart.Total.CurrencyCode));
                    if (!wasEmailSent)
                    {
                        var message = DictionaryPhraseRepository.Current.Get("/System Messages/Orders/Could Not Send Email Error", "Sorry, the email could not be sent");
                        //errorResult.SystemMessages.Add(new SystemMessage(message));
                    }
                }
                catch (Exception ex)
                {
                    Log.Error("Could not send Purchase Confirmation mail message", ex, this);
                    var message = DictionaryPhraseRepository.Current.Get("/System Messages/Orders/Could Not Send Email Error", "Sorry, the email could not be sent");
                    errorResult.SystemMessages.Add(new SystemMessage(message));
                }
            }

            errorResult.WriteToSitecoreLog();
            return(new ManagerResponse <SubmitVisitorOrderResult, CommerceOrder>(errorResult,
                                                                                 errorResult.Order as CommerceOrder));
        }
        public PipelineExecutionResult Execute(PurchaseOrder subject)
        {
            var    cartServiceProvider = new CartServiceProvider();
            var    contactFactory      = new ContactFactory();
            string userId            = contactFactory.GetContact();
            var    createCartRequest = new CreateOrResumeCartRequest(Context.GetSiteName(), userId);

            var cart = cartServiceProvider.CreateOrResumeCart(createCartRequest).Cart;

            var orderService = new OrderServiceProvider();

            var request = new SubmitVisitorOrderRequest(cart);

            // Pass the PurchaseOrder object to Commerce Connect, so it can set use the data for
            // the page events, etc.
            request.Properties.Add("UCommerceOrder", subject);

            var result = orderService.SubmitVisitorOrder(request);

            return(PipelineExecutionResult.Success);
        }
Esempio n. 4
0
        public ActionResult RequestPayment()
        {
            // If you are OK with calling a uCommerce API at this point, you can simply call:

            // --- BEGIN uCommerce API.

            // TransactionLibrary.RequestPayments();
            // return Redirect("/confirmation"); // This line is only required when using the DefaultPaymentMethod for the demo store.

            // --- END uCommerce API.

            // If you want to use the FederatedPayment parts of Commerce Connect. This is what you need to do, to make it work
            var cart = GetCart();

            // For this demo store, it is assumed, that there is only one payment info associated with the order.

            // 1. You need to get the payment service URL for the payment
            var paymentService = new PaymentServiceProvider();
            var baseUrl        = HttpUtility.UrlDecode(paymentService.GetPaymentServiceUrl(new GetPaymentServiceUrlRequest()).Url) ?? string.Empty;

            // 2. You then need to add the payment method id and the payment id to the Url returned from the service.
            var paymentInfo = cart.Payment.First();
            var completeUrl = string.Format(baseUrl, paymentInfo.PaymentMethodID, paymentInfo.ExternalId);

            // 3. In an IFrame set the url to the url from step 2.
            // Because this is a demo store, there is no actual payment gateway involved
            // Therefore at this point we need to manually set the status of the payment to Authorized.

            // ONLY CALLED FOR DEMO PURPOSES
            SetPaymentStatusToAuthorized(paymentInfo.ExternalId);
            // You should redirect the IFrame to the "completeUrl".

            // If you have configured your payment method to run the Checkout pipeline,
            // upon completion, then you do not need to do anything else.
            // The uCommerce framework takes care of the rest.
            // It checks that the transaction was authorized, and it redirects the customer to the accept url.
            // And it calls the Commerce Connect. SubmitVisitorOrder pipeline.
            // So you are done!

            // If you insist on doing the payment in the full Commerce Connect experience,
            // you should configure the uCommerce payment method to not run any pipeline on completion.

            // And in that case, you need to check that the payment was OK, and do the SubmitVisitorOrder calls yourself.
            // These steps are described below.

            // 4. When you believe that the transaction has been completed on the hosted page, you need to check if the payment is OK.
            // In the uCommerce implementation of the Commerce Connect API, this is done by passing the payment id as the access code.
            var actionResult = paymentService.GetPaymentServiceActionResult(new GetPaymentServiceActionResultRequest()
            {
                PaymentAcceptResultAccessCode = paymentInfo.ExternalId
            });
            var paymentWasOk = actionResult.AuthorizationResult == "OK";

            // 5. If the payment is OK, then you can Submit the Order. This corresponds to running the "Checkout" pipeline in uCommerce.
            if (paymentWasOk)
            {
                var orderService = new OrderServiceProvider();
                var request      = new SubmitVisitorOrderRequest(cart);
                orderService.SubmitVisitorOrder(request);
            }

            return(Redirect("/confirmation"));
        }
Esempio n. 5
0
        public ActionResult SubmitPayment(string paymentNonce)
        {
            var loadCartRequest = new LoadCartRequest("CommerceEngineDefaultStorefront", "Default", "1234");
            var loadCartResult  = _cartServiceProvider.LoadCart(loadCartRequest);
            var cart            = loadCartResult.Cart as CommerceCart;

            // Add a shipping address
            CommerceParty shippingAddress = new CommerceParty();

            shippingAddress.ExternalId    = "Shipping";
            shippingAddress.PartyId       = shippingAddress.ExternalId;
            shippingAddress.Name          = "Shipping";
            shippingAddress.Address1      = "Barbara Strozzilaan 201";
            shippingAddress.Company       = "Sitecore";
            shippingAddress.Country       = "Canada";
            shippingAddress.State         = "NB"; // State is checked by commerce engine: you can configure it in Commerce
            shippingAddress.CountryCode   = "CA"; // Country is checked by commerce engine
            shippingAddress.LastName      = "Werkman";
            shippingAddress.FirstName     = "Erwin";
            shippingAddress.City          = "Amsterdam";
            shippingAddress.ZipPostalCode = "1030AC";

            var cartParties = cart.Parties.ToList();

            cartParties.Add(shippingAddress);
            cart.Parties = cartParties;

            ShippingOptionType shippingOptionType = ShippingOptionType.ShipToAddress;

            ICollection <CommerceShippingInfo> shippingInfoList = new List <CommerceShippingInfo>();

            var commerceShippingInfo = new CommerceShippingInfo();

            commerceShippingInfo.ShippingOptionType = ShippingOptionType.ShipToAddress;
            commerceShippingInfo.PartyID            = shippingAddress.ExternalId;
            commerceShippingInfo.ShippingMethodID   = "B146622D-DC86-48A3-B72A-05EE8FFD187A"; // Ship Items > Ground
            commerceShippingInfo.ShippingMethodName =
                "Ground";                                                                     // Method id and name have to match what is configured in Sitecore Commerce Control Panel

            shippingInfoList.Add(commerceShippingInfo);

            var csShippingInfoList = new List <ShippingInfo>();

            foreach (var shippingInfo in shippingInfoList)
            {
                csShippingInfoList.Add(shippingInfo);
            }

            // Add a shipping address and shipping method
            var addShippingInfoRequest =
                new Sitecore.Commerce.Engine.Connect.Services.Carts.AddShippingInfoRequest(cart, csShippingInfoList,
                                                                                           shippingOptionType);
            var result = _cartServiceProvider.AddShippingInfo(addShippingInfoRequest);

            Assert.IsTrue(result.Success, String.Join("|", result.SystemMessages.Select(e => e.Message)));

            // Reload the cart so we have the latest information on how much we need to pay
            var reloadCartRequest  = new LoadCartRequest("CommerceEngineDefaultStorefront", "Default", "1234");
            var reloadedCartResult = _cartServiceProvider.LoadCart(reloadCartRequest);

            Assert.IsTrue(reloadedCartResult.Success,
                          String.Join("|", reloadedCartResult.SystemMessages.Select(e => e.Message)));

            cart = reloadedCartResult.Cart as CommerceCart;

            CommerceParty billingAddress = new CommerceParty();

            billingAddress.ExternalId    = "Billing";   // This should correspond to the PartyId you are setting for the payment info
            billingAddress.PartyId       = billingAddress.ExternalId;
            billingAddress.Name          = "Billing";
            billingAddress.Address1      = "Dorpsstraat 50";
            billingAddress.Company       = "Sitecore";
            billingAddress.Country       = "Canada";
            billingAddress.State         = "NB";           // State is checked: you can configure it in Commerce
            billingAddress.CountryCode   = "CA";
            billingAddress.LastName      = "Werkman";
            billingAddress.FirstName     = "Erwin";
            billingAddress.City          = "Amsterdam";
            billingAddress.ZipPostalCode = "1234AK";

            cart.Parties.Add(billingAddress);

            var payments = new List <PaymentInfo>();

            var federatedPaymentInfo = new FederatedPaymentInfo();

            federatedPaymentInfo.PartyID         = billingAddress.ExternalId;
            federatedPaymentInfo.PaymentMethodID = "0CFFAB11-2674-4A18-AB04-228B1F8A1DEC"; // Federated Payment
            federatedPaymentInfo.Amount          = cart.Total.Amount;                      // Total payment (of all payment methods for a cart) should always be the same as the total amount of the order
            federatedPaymentInfo.CardToken       = paymentNonce;

            payments.Add(federatedPaymentInfo);

            var addPaymentInfoRequest = new AddPaymentInfoRequest(cart, payments);
            var addPaymentInfoResult  = _cartServiceProvider.AddPaymentInfo(addPaymentInfoRequest);

            Assert.IsTrue(addPaymentInfoResult.Success,
                          String.Join("|", addPaymentInfoResult.SystemMessages.Select(e => e.Message)));

            cart.Email = "*****@*****.**"; // This is necessary otherwise the cart will not become an order

            // Save the cart as an order
            var submitVisitorOrderRequest = new SubmitVisitorOrderRequest(cart);
            var submitVisitorOrderResult  = _orderServiceProvider.SubmitVisitorOrder(submitVisitorOrderRequest);

            Assert.IsTrue(submitVisitorOrderResult.Success,
                          String.Join("|", submitVisitorOrderResult.SystemMessages.Select(e => e.Message)));

            return(View(submitVisitorOrderResult));
        }