This script is to save users current cart with a button, I tried my best and I am brand new too this, and cannot figure it out. It takes the current cart gets the data from the cart and maps it to the Collection form (at least I think it does).
Front end:
import { saveCartToDatabase, myDeleteCurrentCartFunction, myUpdateDataCollectionFunction } from 'backend/cartButton.web.js';
import { getCurrentCart } from 'wix-stores';
// Define the updated data collection schema
const updatedDataCollection = {
_id: "Carts",
fields: [
{
key: "priceOfCheckout",
displayName: "Price of Checkout",
description: "The total price of the checkout",
},
{
key: "items",
displayName: "Items",
description: "Items in cart",
required: true
},
{
key: "addresses",
displayName: "Addresses",
description: "Shipping addresses",
required: true
},
{
key: "creditCards",
displayName: "Discount",
description: "Discount applied",
required: true
}
],
revision: "1",
};
$w.onReady(function () {
$w('#CheckoutButton').onClick(async () => {
try {
// Get the current cart details
const cart = await getCurrentCart();
// Prepare the cart data
const cartData = {
items: cart.lineItems.map(item => ({
name: item.name,
price: item.price,
quantity: item.quantity,
totalPrice: item.totalPrice,
productId: item.productId
})),
total: cart.totals,
currency: cart.currency,
id: cart._id,
shipping: cart.shippingInfo,
discount: cart.appliedCoupon,
};
// Map cartData to the fields in updatedDataCollection
const mappedData = {
priceOfCheckout: cartData.total?.total, // Assuming totalPrice is part of totals object
items: JSON.stringify(cartData.items), // Stringify items array
addresses: JSON.stringify(cartData.shipping), // Assuming shipping contains address info
creditCards: JSON.stringify(cartData.discount) // Assuming discount is the coupon applied
};
// Call the backend function to save the mapped data
const result = await saveCartToDatabase(mappedData);
if (result) {
// Clear the cart after saving the data
await myDeleteCurrentCartFunction();
$w('#statusMessage').text = "Cart data saved and cart cleared successfully!";
} else {
$w('#statusMessage').text = "Failed to save cart data.";
}
} catch (error) {
console.error("Error retrieving or saving cart:", error);
$w('#statusMessage').text = "Failed to save cart data.";
}
});
});
Backend:
import wixData from 'wix-data';
import { Permissions, webMethod } from 'wix-web-module';
import { currentCart } from 'wix-ecom-backend';
import { collections } from 'wix-data.v2';
/**
* Updates a data collection's schema and permissions.
* @param {Object} updatedDataCollection - The collection schema and permissions to update.
* @returns {Object} The response from the update operation.
*/
export async function myUpdateDataCollectionFunction(updatedDataCollection) {
try {
const updateResponse = await collections.updateDataCollection(updatedDataCollection);
return updateResponse;
} catch (error) {
console.error("Error updating data collection:", error);
throw new Error("Failed to update data collection");
}
}
/**
* Deletes the current user's cart.
* @returns {void}
*/
export const myDeleteCurrentCartFunction = webMethod(Permissions.Anyone, async () => {
try {
await currentCart.deleteCurrentCart();
console.log("Cart successfully deleted");
} catch (error) {
console.error("Error deleting cart:", error);
throw new Error("Failed to delete cart");
}
});
/**
* Saves the current cart data to a Wix collection.
* @param {Object} cartData - The cart data to save.
* @returns {Object|null} The result of the insert operation, or null if failed.
*/
export async function saveCartToDatabase(cartData) {
const toInsert = {
items: JSON.stringify(cartData.items), // Save items as a JSON string
subtotal: cartData.subtotal,
total: cartData.total,
currency: cartData.currency,
tax: cartData.tax,
shipping: JSON.stringify(cartData.shipping), // Save shipping info as a JSON string
discount: cartData.discount,
createdAt: new Date()
};
try {
const result = await wixData.insert('CartCollection', toInsert); // Replace "CartCollection" with your collection ID
return result;
} catch (error) {
console.error("Error saving cart to database:", error);
return null;
}
}
Thank you 😀
Hi, I would be helpful to add a description or screenshot of what's not working, error messages you are getting and the url to your site with instructions how to test. Eitan