Jump to content

How to put another product in cart programmatically via web servce, API


Alex

Recommended Posts

Hy, i have a problem. A have a problem, i find how to put a product into a cart but i dont know haw to put another product.

 

    $webService = new PrestaShopWebservice(PS_SHOP_PATH, PS_WS_AUTH_KEY, DEBUG);
    $xml = $webService->get(array('url' => PS_SHOP_PATH.'/api/carts?schema=blank'));
    
    /*Add details*/
    $xml->cart->id_address_delivery = $_POST['id_address_delivery'];
    $xml->cart->id_address_invoice = $_POST['id_address_invoice'];
    $xml->cart->id_currency = $_POST['id_currency'];
    $xml->cart->id_customer = $_POST['id_customer'];
    $xml->cart->id_guest = $_POST['id_guest'];
    $xml->cart->id_lang = $_POST['id_lang'];
    $xml->cart->id_shop_group = $_POST['id_shop_group'];
    $xml->cart->id_shop = $_POST['id_shop'];
    $xml->cart->id_carrier = $_POST['id_carrier'];
    $xml->cart->recyclable = $_POST['recyclable'];
    $xml->cart->gift = $_POST['gift'];
    $xml->cart->mobile_theme = $_POST['mobile_theme'];
    $xml->cart->allow_seperated_package = $_POST['allow_seperated_package'];
    /*add prduct*/
    $xml->cart->associations->cart_rows->cart_row->id_product = $_POST['id_product'];
    $xml->cart->associations->cart_rows->cart_row->id_product_attribute = $_POST['id_product_attribute'];
    $xml->cart->associations->cart_rows->cart_row->id_address_delivery = $_POST['id_address_delivery'];
    $xml->cart->associations->cart_rows->cart_row->quantity = $_POST['quantity'];

    $opt = array('resource' => 'carts');
    $opt['postXml'] = $xml->asXML();
    $xml = $webService->add($opt);

 

i'm using "PSWebServiceLibrary.php" and basically i don't know how to create a new <cart_row> in a cart blank schema.

 

<cart>
	<id></id>
	<id_address_delivery></id_address_delivery>
	<id_address_invoice></id_address_invoice>
	<id_currency></id_currency>
	<id_customer></id_customer>
	<id_guest></id_guest>
	<id_lang></id_lang>
	<id_shop_group></id_shop_group>
	<id_shop></id_shop>
	<id_carrier></id_carrier>
	<recyclable></recyclable>
	<gift></gift>
	<gift_message></gift_message>
	<mobile_theme></mobile_theme>
	<delivery_option></delivery_option>
	<secure_key></secure_key>
	<allow_seperated_package></allow_seperated_package>
	<date_add></date_add>
	<date_upd></date_upd>
<associations>
<cart_rows>
	<cart_row>
	<id_product></id_product>
	<id_product_attribute></id_product_attribute>
	<id_address_delivery></id_address_delivery>
	<quantity></quantity>
	</cart_row>
</cart_rows>
</associations>
</cart>
</prestashop>

Thx.

Link to comment
Share on other sites

I find my answer.I made a loop for each product :) .

    for ($i=0; $i <= $_POST['number_of_products'] ; $i++) { 
        $xml->cart->associations->cart_rows->cart_row[$i]->id_product = $_POST['id_product'.$i];
        $xml->cart->associations->cart_rows->cart_row[$i]->id_product_attribute = $_POST['id_product_attribute'.$i];
        $xml->cart->associations->cart_rows->cart_row[$i]->id_address_delivery = $_POST['id_address_delivery'.$i];
        $xml->cart->associations->cart_rows->cart_row[$i]->quantity = $_POST['quantity'.$i];
    }

 

I will have id_product0 id_product1 id_product2 and so on.

Edited by Alex (see edit history)
  • Haha 1
Link to comment
Share on other sites

  • 2 years later...

I have checked same you have done, but for me first row of product only getting create into cart. Can you please help me on this?

//associations

            for ($i=0; $i < sizeof($data->products); $i++) { 
                $xml->cart->associations->cart_rows->cart_row[$i]->id_product = $data->products[$i]->id_product;
                $xml->cart->associations->cart_rows->cart_row[$i]->id_product_attribute =$data->products[$i]->id_product_attribute;
                $xml->cart->associations->cart_rows->cart_row[$i]->id_address_delivery = $data->products[$i]->id_address_delivery;
                $xml->cart->associations->cart_rows->cart_row[$i]->quantity = $data->products[$i]->quantity;
            }
            $opt = array( 'resource' => 'carts' );
            $opt['postXml'] = $xml->asXML();
            $xml = $webService->add( $opt );
            $id_cart = $xml->cart->id; 
            echo json_encode(array("success" => TRUE, "message" => ' Item added to cart successfully.', 'id_cart' => $id_cart));

 

My request payload sample,

{"id_address_delivery" : 48, "id_address_invoice" : 48, "id_customer" : 48, "id_carrier" : 61, "products" : [{"id_product" : 3078, "id_product_attribute" : 0, "id_address_delivery" : 48, "quantity" : 1},{"id_product" : 119, "id_product_attribute" : 59, "id_address_delivery" : 48, "quantity" : 1},{"id_product" : 3204, "id_product_attribute" : 0, "id_address_delivery" : 48, "quantity" : 1}]}

 

Edited by rvkvino (see edit history)
Link to comment
Share on other sites

  • 3 weeks later...

I have used below request to create order,

{"id_cart" : 389, "payment" : "payubiz", "id_carrier" : 61, "id": "389",

        "id_address_delivery": "48",

        "id_address_invoice": "48",

        "id_currency": "1",

        "id_customer": "48",

        "id_guest": {},

        "id_lang": "1",

        "current_state" : "3",

        "valid " : 0,

        "id_shop_group": {},

        "id_shop": "1",

        "recyclable": {},

        "gift": {},

        "gift_message": {},

        "mobile_theme": {},

        "delivery_option": {},

        "secure_key": {},

        "allow_seperated_package": {},

        "date_add": "2020-07-24 11:35:58",

        "date_upd": "2020-07-24 11:35:58",

        "associations": {

            "cart_rows": {

                "@attributes": {

                    "nodeType": "cart_row",

                    "virtualEntity": "true"

                },

                "cart_row": [

                    {

                        "id_product": "117",

                        "id_product_attribute": "0",

                        "id_address_delivery": "48",

                        "quantity": "1"

                    },

                    {

                        "id_product": "119",

                        "id_product_attribute": "59",

                        "id_address_delivery": "48",

                        "quantity": "1"

                    },

                    {

                        "id_product": "1166",

                        "id_product_attribute": "0",

                        "id_address_delivery": "48",

                        "quantity": "1"

                    }

                ]

            }

        }} 

Used the below code 

function placeOrder($idCart, $data){
    try    {
        $webService = new PrestaShopWebservice(PS_SHOP_PATH, PS_WS_AUTH_KEY, DEBUG);
        $opt = array('resource' => 'orders');
        $xml = $webService->get(array('url' => PS_SHOP_PATH.'/api/orders?schema=blank'));
        $resources = $xml->children()->children();
    } catch (PrestaShopWebserviceException $e){
        // Here we are dealing with errors
        $trace = $e->getTrace();
        if ($trace[0]['args'][0] == 404) $status["status"] = 'Bad ID';
        else if ($trace[0]['args'][0] == 401) $status["status"] = 'Bad auth key';
        else $status["status"] = "Orders - Other error1".$ex->getMessage();
        echo json_encode($status);    
    }

    // Second : We update the data and send it to the web service
    if (isset($idCart)) {
        // Here we have XML before update, lets update XML with new values
        
        $defaulAddr = getAddress(getCart($idCart)["id_customer"]);
        $data->id_address_delivery = (!empty($data->id_address_delivery) ? $data->id_address_delivery : $defaulAddr);
        $data->id_address_invoice = (isset($data->id_address_invoice) ? $data->id_address_invoice : $defaulAddr);
        //print_r($resources);exit;
        foreach ($resources as $nodeKey => $node){
            if(!empty($data->$nodeKey))
            $resources->$nodeKey = $data->$nodeKey;
        }
        try    {
            $total=0;
            $totalreal=0;
            $cartRows = getCart($idCart)["rows"];
            $orderke = 0;
            if(count($cartRows->cart_row)==1){
                foreach($cartRows as $key => $value){
                    $resources->associations->order_rows->order_row[$orderke]->product_id = $value->id_product;
                    $resources->associations->order_rows->order_row[$orderke]->product_attribute_id = 0;
                    $resources->associations->order_rows->order_row[$orderke]->product_quantity = $value->quantity;
                    $resources->associations->order_rows->order_row[$orderke]->product_name = getProductInfo($value->id_product)['name'];
                    $resources->associations->order_rows->order_row[$orderke]->product_price = getProductInfo($value->id_product)['price'];
                    $total+= getProductInfo($value->id_product)['reduction']>0 ? (getProductInfo($value->id_product)['price']-(getProductInfo($value->id_product)['price']*getProductInfo($value->id_product)['reduction']))*$value->quantity : getProductInfo($value->id_product)['price']*$value->quantity;
                    $totalreal+=getProductInfo($value->id_product)['price']*$value->quantity;;
                    $orderke++;
                }
            }else if(count($cartRows->cart_row)>0){
                foreach($cartRows->cart_row as $key => $value){
                    $resources->associations->order_rows->order_row[$orderke]->product_id = $value->id_product;
                    $resources->associations->order_rows->order_row[$orderke]->product_attribute_id = 0;
                    $resources->associations->order_rows->order_row[$orderke]->product_quantity = $value->quantity;
                    $resources->associations->order_rows->order_row[$orderke]->product_name = getProductInfo($value->id_product)['name'];
                    $resources->associations->order_rows->order_row[$orderke]->product_price = getProductInfo($value->id_product)['price'];
                    $total+= getProductInfo($value->id_product)['reduction']>0 ? (getProductInfo($value->id_product)['price']-(getProductInfo($value->id_product)['price']*getProductInfo($value->id_product)['reduction']))*$value->quantity : getProductInfo($value->id_product)['price']*$value->quantity;
                    $totalreal+=getProductInfo($value->id_product)['price']*$value->quantity;;
                    $orderke++;
                }
            }
            $resources->total_paid = $total;
            $resources->total_paid_tax_incl = $total;
            $resources->total_paid_tax_excl = $total;
            $resources->total_paid_real = $totalreal;
            $resources->total_products = $total;
            $resources->total_products_wt = $total;
            $resources->total_shipping = 0.000000;
            $resources->total_shipping_tax_incl=0.000000;
            $resources->total_shipping_tax_excl=0.000000;
            $resources->carrier_tax_rate=0.000;
            $resources->total_wrapping=0.000000;
            $resources->total_wrapping_tax_incl=0.000000;
            $resources->total_wrapping_tax_excl=0.000000;
            $resources->round_mode=0;
            
            $opt = array('resource' => 'orders');
            $opt['postXml'] = $xml->asXML();
            
            //print_r($opt['putXml']);
            //return false;  //COMMENT THIS!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            
            $xml = $webService->add($opt);
            $idOrder = (array)$xml->order->id;
            $status["id"] = $idOrder[0];
            $status["status"] = "success";
            echo json_encode($status);
        }catch (PrestaShopWebserviceException $ex){
            $trace = $ex->getTrace();
            if ($trace[0]['args'][0] == 404) $status["status"] = 'Bad ID';
            else if ($trace[0]['args'][0] == 401) $status["status"] = 'Bad auth key';
            else $status["status"] = 'Other error<br />'.$ex->getMessage();
            echo json_encode($status);
        }
    }

}

But this is showing the error like,

<br />
<b>Warning</b>:  It is not yet possible to assign complex types to properties in <b>/home/asdarmavanima/public_html/mobapi/placeorder.php</b> on line <b>171</b><br />
<br />
<b>Warning</b>:  It is not yet possible to assign complex types to properties in <b>/home/asdarmavanima/public_html/mobapi/placeorder.php</b> on line <b>171</b><br />
<br />
<b>Warning</b>:  It is not yet possible to assign complex types to properties in <b>/home/asdarmavanima/public_html/mobapi/placeorder.php</b> on line <b>171</b><br />
<br />
<b>Warning</b>:  It is not yet possible to assign complex types to properties in <b>/home/asdarmavanima/public_html/mobapi/placeorder.php</b> on line <b>171</b><br />
<br />
<b>Warning</b>:  It is not yet possible to assign complex types to properties in <b>/home/asdarmavanima/public_html/mobapi/placeorder.php</b> on line <b>171</b><br />
<br />
<b>Warning</b>:  It is not yet possible to assign complex types to properties in <b>/home/asdarmavanima/public_html/mobapi/placeorder.php</b> on line <b>171</b><br />
<br />
<b>Fatal error</b>:  Uncaught Error: Class 'inaAPI' not found in /home/asdarmavanima/public_html/mobapi/placeorder.php: 126
Stack trace:
#0 /home/asdarmavanima/public_html/mobapi/placeorder.php(194): getProductInfo('117')
#1 /home/asdarmavanima/public_html/mobapi/placeorder.php(239): placeOrder(389, Object(stdClass))
#2 {main
}
  thrown in <b>/home/asdarmavanima/public_html/mobapi/placeorder.php</b> on line <b>126</b><br />

Can you please help me on this to create order via web service. I need to to know exact request payload data to this service.

Link to comment
Share on other sites

If i dont know what you have in "/home/asdarmavanima/public_html/mobapi/placeorder.php" at line 171 i can't help you. The problem is on line 171 in "/home/asdarmavanima/public_html/mobapi/placeorder.php".

Link to comment
Share on other sites

I'm having the code in that line $resources->$nodeKey = $data->$nodeKey;

foreach ($resources as $nodeKey => $node){
            if(!empty($data->$nodeKey))
            $resources->$nodeKey = $data->$nodeKey;
        }

This only i'm having

Link to comment
Share on other sites

i dont know what value you have in $resources and $data. What i do in your place. I make an order via desktop after that i load the order via webservice and after that i check every $nodekey value of the order made via desktop to be the same type of the $resources->$nodekey after line 171 (after foreach statement). This si for worning messages.

For "Fatal error" (Class 'inaAPI' not found in /home/asdarmavanima/public_html/mobapi/placeorder.php: 126) check that you load the class before you call the class.

Link to comment
Share on other sites

@Alex Can you please help me the best way of doing order placement using prestashop  web services.

I mean which way I need to do crate successive order checkout using prestashop web service. I need steps from first to last step by steps.

1.Customer Creation

2.customer address

3.Create cart

4.Create Order 

5.Order Payment

Is this correct way? I'm getting confusion on Order create and payment gate way process after that update the status on order.

Link to comment
Share on other sites

  • 3 weeks later...

Hello,

Can you please update the code to show cart details against cart id. In this need to show all the products in the cart, I'm having trouble on getting the product details using web service. Please help me on this to get product all inner details  like combination price, discount, product weight and discount etc

Link to comment
Share on other sites

  • 2 weeks later...

My solution is:

$carriers = Carrier::getCarriersForOrder(Country::getIdZone($address_delivery->id_country), $id_group, $cart);
foreach ($carriers as $value) {
    if($value["id_carrier"] == $cart->id_carrier){  //if is my carrier
        $total_shipping_tax_incl = $value["price"];
        $total_shipping_tax_excl = $value["price_tax_exc"];
        $carrier_tax_rate = Tax::getCarrierTaxRate($value["id_carrier"]);
    }
}

Where $id_group is user group id.

Edited by Alex (see edit history)
Link to comment
Share on other sites

In you file where you include PSWebServiceLibrary you can include all prestashop classes with require_once ('../config/config.inc.php');

 

EX:

require_once('.././PSWebServiceLibrary.php');
require_once ('../config/config.inc.php');

And then you can call 

Carrier::getCarriersForOrder(Country::getIdZone($address_delivery->id_country), $id_group, $cart);

So you will have something like:

$cart = new Cart($cart_id);
$id_group = Customer::getDefaultGroupId($cart->id_customer);
$address_delivery = new Address($cart->id_address_delivery);

$carriers = Carrier::getCarriersForOrder(Country::getIdZone($address_delivery->id_country), $id_group, $cart);
foreach ($carriers as $value) {
    if($value["id_carrier"] == $cart->id_carrier){  //if is my carrier
        $total_shipping_tax_incl = $value["price"];
        $total_shipping_tax_excl = $value["price_tax_exc"];
        $carrier_tax_rate = Tax::getCarrierTaxRate($value["id_carrier"]);
    }
}

PS: For prestahsop 1.7.

Link to comment
Share on other sites

@Alex Thanks for your help, it's helped me lot. I have tried same in my service but it showing below error,

<br />
<b>Fatal error</b>:  Uncaught PrestaShopException: Fatal error in /home/asdarmavanima/public_html/classes/Tools.php: 1109
Stack trace:
#0 /home/asdarmavanima/public_html/classes/Product.php(3208): ToolsCore: :displayError()
#1 /home/asdarmavanima/public_html/classes/Product.php(4804): ProductCore: :getPriceStatic(1154,
false,
0,
6, NULL,
false,
true,
1)
#2 /home/asdarmavanima/public_html/classes/Cart.php(811): ProductCore: :getProductProperties(1, Array)
#3 /home/asdarmavanima/public_html/classes/Cart.php(1916): CartCore->getProducts()
#4 /home/asdarmavanima/public_html/classes/Carrier.php(738): CartCore->getOrderTotal(true,
4)
#5 /home/asdarmavanima/public_html/mobapi/shippingcharge.php(18): CarrierCore: :getCarriersForOrder(3, '3', Object(Cart))
#6 {main
}
  thrown in <b>/home/asdarmavanima/public_html/classes/Tools.php</b> on line <b>1109</b><br />


When I check this line by line it's getting issue on  the line on Carrier.php class. !Carrier::checkDeliveryPriceByPrice($row['id_carrier'], $cart->getOrderTotal(true, Cart::BOTH_WITHOUT_SHIPPING), $id_zone, $id_currency)

$cart->getOrderTotal(true, Cart::BOTH_WITHOUT_SHIPPING) this method call getting issue.

 

Edited by rvkvino (see edit history)
Link to comment
Share on other sites

@Alex Thanks for your help, I have included init.php

require_once ('../init.php');

Then the above error not coming now. Now this is working fine. 

Now I have another problem like if I use file_get_-contents,

require_once ('../config/config.inc.php');
require_once ('../init.php');

$json = file_get_contents('php://input');
$data = json_decode($json);

Now I couldn't access the $data variable, it's showing empty. I have checked without include config on this case this file_get_contents is working fine.

Edited by rvkvino (see edit history)
Link to comment
Share on other sites

  • 5 months later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...