user3408005
user3408005

Reputation: 73

Building a custom module using PHP

I am currently building a module for an ecommerce website (Lemonstand). My shop sells both normal books and ebooks, and charge different rates of for shipping based on the subtotal of all items in the cart ($7 shipping cost for subtotal of less than $20, $14 shipping cost for between $20 and $50..etc). Currently the website just uses the subtotal of all items in the cart to determine which rate should be applied. The problem is, I want only the subtotal of normal books to be used for calculating shipping, because obviously ebooks don't need shipping.

Lemonstand platform has some built_in functions that I'm using to help with this. update_shipping_quote function is called just before shipping cost is calculated. It will be used to change the subtotal of cart items so that shipping cost can be calculated using the subtotal of non-ebooks instead.

Here is the API documentation for the function: https://v1.lemonstand.com/api/event/shop:onupdateshippingquote/

Here is the bit of code that's giving me trouble. I want to know if the value I get at the end ($non_ebook_subtotal) actually contains the value it's supposed to.

If anyone can come up with a better method for doing what I'm trying to do, please share.

            //$params is an array containing things like individual item price
            //Here I get the cart items and put them into var

public function update_shipping_quote($shipping_option, $params) {

    $cart_items = $params['cart_items'];


    //find all products that are ebooks

    foreach ($cart_items-> items as $item) 
    {
        $product = $item->product;
        if($product->product_type->code == 'ebook') {
            $isEbook = true;
        }
    }

    //add price of all ebooks into $ebook_subtotal

    foreach ($cart_items as $item) {
        $product = $item -> product;
        if ($isEbook == true) {
            $ebook_subtotal = $ebook_subtotal + total_price($product);
        }
    }

            //Calculating the subtotal of only the non-ebook products
    $non_ebook_subtotal = $params['total_price'] - $ebook_subtotal;


    //This returns the non_ebook_subtotal to be used for calculating shipping cost
    return array('total_price' => $non_ebook_subtotal);


}

Thanks

Upvotes: 0

Views: 110

Answers (1)

Joshua Bixler
Joshua Bixler

Reputation: 531

// get all variables needed
$totalprice = $params['total_price'];
$items = $params['cart_items'];

foreach ($items AS $item) {
    // if is ebook
    if ($item->product->product_type->code == 'ebook') {
        // minus price of the item from total
        $totalprice -= total_price($item->product);
    } 
}

return $totalprice;

Upvotes: 1

Related Questions