Yes, you can use Wix Velo backend APIs to calculate the subtotal, tax, shipping, and discount for a hypothetical cart in your store. Below is a sample implementation of how you can achieve this.
- Create a backend module (
cartCalculations.jsw
) to handle the calculations.
// backend/cartCalculations.jsw
import { fetch } from 'wix-fetch';
export async function calculateCart(cartItems) {
const taxRate = 0.08; // Example tax rate (8%)
const shippingRate = 10; // Example flat shipping rate
let subtotal = 0;
let discount = 0;
for (const item of cartItems) {
const productData = await getProductData(item.productId);
const itemTotal = productData.price * item.quantity;
subtotal += itemTotal;
discount += itemTotal * (productData.discount || 0);
}
const tax = subtotal * taxRate;
const shipping = shippingRate;
const total = subtotal + tax + shipping - discount;
return {
subtotal,
tax,
shipping,
discount,
total
};
}
async function getProductData(productId) {
const response = await fetch(`https://your-store.com/_functions/products/${productId}`, {
method: 'get'
});
if (response.ok) {
return await response.json();
} else {
throw new Error('Failed to fetch product data');
}
}
Create an API function to handle the client-side request (http-functions.js
).
// backend/http-functions.js
import { calculateCart } from 'backend/cartCalculations';
export async function post_calculateCart(request) {
const { cartItems } = await request.body.json();
const result = await calculateCart(cartItems);
return ok(result);
}
On the client side, call the API to get the calculations.
// public/cartQuote.js
import { fetch } from 'wix-fetch';
export function getQuote(cartItems) {
return fetch('https://your-site.com/_functions/calculateCart', {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ cartItems })
})
.then(response => response.json());
}
Use the getQuote
function in your page code to display the cart calculations.
// public/pageCode.js
import { getQuote } from 'public/cartQuote';
$w.onReady(function () {
const cartItems = [
{ productId: '12345', quantity: 2 },
{ productId: '67890', quantity: 1 }
];
getQuote(cartItems).then(quote => {
$w('#subtotal').text = quote.subtotal.toFixed(2);
$w('#tax').text = quote.tax.toFixed(2);
$w('#shipping').text = quote.shipping.toFixed(2);
$w('#discount').text = quote.discount.toFixed(2);
$w('#total').text = quote.total.toFixed(2);
});
});
This may not suit exactly your circumstance, but should help point you in the right direction.
I have not tested the code properly.