Update cart

Make sure you read Get Started before you go on with this tutorial. The update cart functionality is only compatible when Ecster Pay is integrated within an iframe.

Once Ecster Pay has been started, the Update Cart functionality should be executed whenever the cart changes, i.e. whenever the cart or the customer is modified. This is to account for the new information altering prices, totals, addresses, etc. The Update cart will trigger a reload of Ecster Pay including the latest changes.

Note: Most checkouts enables the customer to change its cart through AJAX requests without the page reloading, but if a change triggers the entire page to reload – just create a new cart.

Prerequisites:

Before attempting to update the order, Ecster Pay must have been started. For more details see Get Started.

A brief summary of the steps in this tutorial are:

  1. Handle cart changes
  2. Execute Update cart via Ecster Pay REST API
  3. Reload Ecster Pay in your sites frontend to include the latest changes
  4. Save order details

Handle cart changes

Events that require you to update cart are:

  • The user makes changes to the cart, e.g. add or remove an item, in your application
  • More information about the customer, e.g. customer authorization
  • The user selects a delivery method in the store checkout page
  • The user changes address information in Ecster Pay

Update cart via REST API

This example shows when a customer has changed delivery method on the store checkout page.

Call your applications backend which in turn will update Ecster Pay with the new delivery method. 

Compose and execute an update cart request according to the API reference. The parameters are quite similar to create cart, but with some modifications. In this case you should send the new delivery method in Update cart.

You need to pass the current cart key in the URL when executing Update cart. The call will return a new cart key which is simply a reference to your updated cart. Return the key to your sites frontend. You don’t need to persist old cart keys as only the latest retains importance.

public class Parameters
{
    public string DeliveryMethod { get; set; } 
}

[System.Web.Http.HttpPost]
[Route("api/ecster/update/{cartKey}", 1)]
public async Task<IHttpActionResult> UpdateCart(string cartKey, [FromBody]Parameters parameters)
{
    var request = GetCartRequest();
    request.DeliveryMethods.First(x => x.Id == parameters.DeliveryMethod).Selected = true;
    var cartResponse = await Execute(cartKey, request);
    return Ok(cartResponse.Response.Key);
}

private async Task<EcsterResponse<CartKeyResponse>> Execute(string cartKey, CartRequest request)
{
   var httpClient = new HttpClient();
   httpClient.BaseAddress = new Uri("https://labs.ecster.se/rest/");
   httpClient.DefaultRequestHeaders.Add("X-Ecster-origin", "checkout");
   httpClient.DefaultRequestHeaders.Add("X-Ecster-username", "<username>"); // replace
   httpClient.DefaultRequestHeaders.Add("X-Ecster-password", "<password>"); // replace

   var jsonSerializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
   var jsonMediaTypeFormatter = new JsonMediaTypeFormatter { SerializerSettings = jsonSerializerSettings };
   var response = await httpClient.PutAsync("eps/v1/cart/" + cartKey, request, jsonMediaTypeFormatter);
   var content = await response.Content.ReadAsStringAsync();
   return JsonConvert.DeserializeObject<EcsterResponse<CartKeyResponse>>(content);
}

Reload Ecster Pay

As stated above, changes like selecting a delivery method will probably alter the order total sum. The JavaScript function Update Cart reloads the Ecster Pay frame when called.

The function call is executed using the current cart key which returns a function. Call the web service you created using AJAX to get a new cart key. The returned function is executed using the new cart key. When the returned function is executed, Ecster Pay reloads its checkout frame to include the latest order changes.

//This is executed on shop checkout page when the 
//customer changes delivery method
var handleChangedDeliveryMethod = function (selectedDeliveryMethod) {
    var callback = EcsterPay.updateCart(cartKey);
    $.post('/api/ecster/update/' + orderReference, { deliveryMethod: selectedDeliveryMethod.id }, function (newCartKey) {
        callback(newCartKey);
        cartKey = newCartKey;
    });
};

Save order details

In order to get information about the order when a payment is completed, you need to create a web service that Ecster Pay communicates with. When you’ve created the web service, you need to pass the web service’s URL to Ecster Pay via the parameter notification URL in createCart. Whenever an order’s status changes, Ecster Pay will execute a call to the notification URL containing internal and external order reference, as well as the new order status. This function is called Order status notification.

When Ecster Pay executes OSN, you execute Get order, as this provides you with a complete order summary. This enables you to store the order in your own database. If necessary, use the external reference to find the cart in your application.

You also want to make sure that the cart is cleared. If the customers browser is active throughout the entire checkout process, you can empty it when onPaymentSuccess() is triggered. You could also make sure the cart is cleared in the OSN. You can use the internal or external reference to find your cart and then clear it.

Done

After executing all the steps above, try to select a delivery method to verify that you get a new order reference and that Ecster Pay recalculates the order total.

Request test account