Triggering Magento 2 Checkout Shipping Rates Recollection via Custom JavaScript
As a senior developer, I understand that customizing the checkout process using third-party JavaScript can be challenging. In this post, we’ll explore how to trigger shipping rates recollection on checkout without using Knockout.js.
The Problem: Triggering Shipping Rates Recollection
You’ve replaced the default onepage.phtml template with a custom one and tried triggering shipping address changes via jQuery. However, the shipping rates aren’t being recalculated as expected:
require([
'jquery',
'Magento_Checkout/js/model/quote'
], function($, quote) {
$('#target').on('click', function(e) {
console.log(quote.shippingAddress(quote.shippingAddress()));
});
});
The issue lies in the way Magento 2 handles shipping rates calculation. It’s tightly coupled with the Knockout.js model used by default.
A Better Approach
To trigger shipping rates recollection without relying on Knockout, you’ll need to manually dispatch events and update the quote using the Magento 2 REST API. Here’s a step-by-step guide:
-
Get the current quote ID: You can find the quote ID in the URL or retrieve it from the
quoteobject. -
Update the shipping address: Create an AJAX request to the
/V1/carts/mine/addresses/shippingendpoint with the new shipping data. -
Recalculate the shipping rates: After updating the address, dispatch a “shipping_address_changed” event using RequireJS:
require([
'jquery',
'Magento_Checkout/js/model/quote'
], function($, quote) {
$('#target').on('click', function(e) {
// Update the shipping address via AJAX (not shown)
$.ajax({
url: '/V1/carts/mine/addresses/shipping',
type: 'PUT',
dataType: 'json',
contentType: 'application/json',
success: function(response) {
quote.setShippingAddress(response);
require(['Magento_Checkout/js/model/quote'], function(quote) {
quote.setShippingMethod(null);
requirejs(['jquery', 'Magento_Customer/js/customer-data'], function($, customerData) {
var section = customerData.get('cart');
section.invalidate();
});
});
}
});
});
});
- Clear the cart data: After invalidating the
cartsection, Magento 2 will automatically fetch fresh data and recalculate the shipping rates.
Conclusion
While Magento’s default checkout process is tightly integrated with Knockout.js, you can still trigger shipping rate recollection using custom JavaScript by following these steps:
- Update the shipping address via the
/V1/carts/mine/addresses/shippingAPI endpoint. - Manually set the updated shipping address in the quote model.
- Clear the cart data and wait for Magento to fetch fresh data.
Remember, this approach requires a good understanding of Magento’s REST API and RequireJS event dispatching. If you find these customizations complex or time-consuming, consider using extensions like Laravel Company’s One Step Checkout for an easier checkout experience.
With this approach, you can successfully trigger shipping rates recollection in your custom Magento 2 checkout process.