# Help Calculating a Price - Shipping script

## Recommended Posts

Hey guys,

I need some help with a simple script a friend wrote for me but isn't returning the correct values. I'm looking to get this script working but my PHP skills are abysmal and I can't for the life of me figure out whats the best way to do this. I've tried contacting my friend but he's moving cross-country so I'm hoping you guys can give me some advice.

The script is supposed to return a total shipping price based on the weight of products that are passed to it via an API and the location of the visitor. There are a total of 3 different products (Product A, Product B, Product C) each with it's own weight in grams and it's own shipping rate. The script is needs to follow the following rules:

• When 1 product (either Product A, B, or C) is in the cart it returns the full fixed shipping price for either US or International Shipping based on \$isInternational
• When 2 or more of Product A or B are added to the cart the full shipping is taken for the heaviest item and a fixed price is added for each additional item (Product and B each have their own fixed prices)
• When Product C is added to the cart it returns a fixed based on US or International (Product C ships separately and doesn't depend on the weight/prices of Product A or B)

The product weights/prices are:

Product A:
Weight (grams): 250
Us Shipping for first instance: \$6.00
International Shipping for first instance: \$10.00

Each additional instance: \$1.00

Product B:
Weight (grams): 300
Us Shipping for first instance: \$8.00
International Shipping for first instance: \$11.00
Each additional instance: \$2.50
Product C:
Weight (grams): 120
Us Shipping for each instance: \$8.00
International Shipping for each instance: \$20.00

An example would be if the cart contained 2 of Product B, 1 of Product A, and 2 of Product C shipping to the US:
The price would be 8+2.50+1+8+8=27.50

The script currently ignores the addition of more instances of the items and doesn't take into account US vs International:
```<?

\$json = file_get_contents('php://input');
\$request_body = json_decode(\$json, true);

if (is_null(\$request_body) or !isset(\$request_body['eventName'])) {
\$response = array(
"rates" => ""
);
die(json_encode(\$response));
}

switch (\$request_body['eventName']) {
case 'shippingrates.fetch':
// ============= recieve data from cart ==============
\$isInternational = (\$country_code != "US");

\$quantity = 0;
\$maxWeight = 0;
\$cost = 0;
\$description = "International Shipping";

if(\$request_body["content"] && \$request_body["content"]["items"]){
foreach (\$request_body["content"]["items"] as \$cart_item){
\$quantity += \$cart_item["quantity"];

if(\$cart_item["weight"] >= 300){
\$cost += 2.50;
} else if(\$cart_item["weight"] >= 200){
\$cost += 1.0;
} else if(\$cart_item >= 100){
\$cost += (\$isInternational)? 15.0 : 8.0;
}

if(\$cart_item["weight"] > \$maxWeight){
\$maxWeight = \$cart_item["weight"];
}
}
}

if(\$maxWeight >= 300) {
\$cost += (\$isInternational) ? 11.0 : 8.0;
\$cost -= 2.50;
} else  if (\$maxWeight >= 200) {
\$cost += (\$isInternational) ? 10.0 : 6.0;
\$cost -= 1;
}

if(\$isInternational){
\$description = "International Shipping";
} else {
\$description = "USPS Standard Shipping";
}

// =========== return data to cart ===============
\$rates = array(
array(
"cost" => \$cost,
"description" => \$description
),
);
\$response = array(
"rates" => \$rates
);

echo(json_encode(\$response));
break;

default:
break;
}
?>
```

Thanks for any help you guys can give!

##### Share on other sites

Good luck with this.  The code has no comments to help us get the context of what is going on (at least for me!).  An awful lot of stuff going here and if your friend wrote it and you accepted it, perhaps you should hold him or yourself responsible for fixing it.

##### Share on other sites

The code is basing the shipping solely on the weight of the products. So it is assuming that the product is either A, B or C base don the weight. That is a very poor way of doing this. You should identify the products explicitly using a product ID or something like that.

Plus, you should rethink how you define your logic. Instead of \$8.00 for the first instance and \$2.50 for each additional it would probably be easier to look it as a base rate of \$5.50 if there are any units and \$2.50 for every unit. You still get the same outcome, but the logic is a little easier to decipher in my opinion.

You can give this a try - I give no guarantees

```<?php

\$json = file_get_contents('php://input');
\$request_body = json_decode(\$json, true);

if (is_null(\$request_body) or !isset(\$request_body['eventName']))
{
\$response = array("rates" => "");
die(json_encode(\$response));
}

switch (\$request_body['eventName'])
{
case 'shippingrates.fetch':
// ============= recieve data from cart ==============
\$isInternational = (\$country_code != "US");

//Define description
\$description = (\$isInternational) ? "International Shipping" : "USPS Standard Shipping";

//Define needed variables
\$maxWeight = 0;
\$unitCost  = 0;
\$fixedCost = 0;

//Calculate per unit shipping cost
if(\$request_body["content"] && \$request_body["content"]["items"])
{
foreach (\$request_body["content"]["items"] as \$cart_item)
{
//Create variables for quantity and weight
\$quantity = \$cart_item["quantity"];
\$weight   = \$cart_item["weight"];

//Determine max weight of individual item
\$maxWeight = max(\$maxWeight, \$weight);

//Calculate unit shipping cost
if(\$weight >= 300)
{
//Add unit cost for 300g+ products
\$unitCost += \$quantity * 2.5;
}
else if(\$weight >= 200)
{
//Add unit cost for 200g+ products
\$unitCost += \$quantity * 1;
}
else
{
//Add unit cost for less than 200g products
\$unitCost += (\$isInternational)? 20 : 8;
}
}
}

//Calculate fixed shipping cost
if(\$maxWeight >= 300) {
\$fixedCost = (\$isInternational) ? 8.5 : 5.5;
} else if (\$maxWeight >= 200) {
\$fixedCost = (\$isInternational) ? 9 : 5;
}

//Calculate total cost
\$totalCost = \$fixedCost + \$unitCost;

// =========== return data to cart ===============
\$rates = array(
array(
"cost" => \$totalCost,
"description" => \$description
),
);
\$response = array(
"rates" => \$rates
);

echo(json_encode(\$response));
break;

default:
break;
}
?>```
##### Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

## Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Restore formatting

Only 75 emoji are allowed.