export async function getRatesFunction({ provider, order, dimensions }) {
if (!dimensions) {
throw new Error("Dimensions are required to get shipping rates");
}
// Create address first
const addressToResponse = await fetch(`${SHIPPO_API_URL}/addresses/`, {
method: "POST",
headers: {
Authorization: `ShippoToken ${provider.accessToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
name: `${order.shippingAddress.firstName} ${order.shippingAddress.lastName}`,
street1: order.shippingAddress.address1,
city: order.shippingAddress.city,
state: order.shippingAddress.province,
zip: order.shippingAddress.postalCode,
country: order.shippingAddress.country.iso2,
phone: order.shippingAddress.phone,
}),
});
const addressTo = await addressToResponse.json();
// Create shipment to get rates
const shipmentResponse = await fetch(`${SHIPPO_API_URL}/shipments/`, {
method: "POST",
headers: {
Authorization: `ShippoToken ${provider.accessToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
address_from: { /* warehouse address */ },
address_to: addressTo.object_id,
parcels: [{
length: dimensions.length,
width: dimensions.width,
height: dimensions.height,
distance_unit: dimensions.unit,
weight: dimensions.weight,
mass_unit: dimensions.weightUnit,
}],
}),
});
const shipment = await shipmentResponse.json();
return shipment.rates.map((rate) => ({
id: rate.object_id,
providerId: provider.id,
service: rate.servicelevel.name,
carrier: rate.provider,
price: rate.amount,
currency: rate.currency,
estimatedDays: rate.estimated_days,
}));
}