Add cart rule via webservice to order api - Core developers - PrestaShop

Jump to content

Photo

Add cart rule via webservice to order api

cartrule order webservice cart

#1

Posted 22 August 2015 - 07:46 AM

arjit

    PrestaShop Newbie

  • Members
  • Pip
  • 20 Active Posts

Hi , 

 

I have been trying to create an order with some cart_rules discount with webservices. I am unable to as I dont see cart_rule getting appiled either in cart or order. I have my site running on prestashop webserices. 

 

I explored I saw order_discount I wanted to know how should I apply this ? I see order_discount has order_Id in it so it has to be created after order and once the order is made I cant apply I the discount. Seems confusing to me. 
 

I want to know the steps in which we need to apply the discounts. 

 



#2

Posted 23 August 2015 - 09:10 AM

arjit

    PrestaShop Newbie

  • Members
  • Pip
  • 20 Active Posts

Any one please reply ! 



#3

Posted 23 August 2015 - 01:53 PM

arjit

    PrestaShop Newbie

  • Members
  • Pip
  • 20 Active Posts

I am sad to see the kind of community support given by prestashop. I will not advocate anyone to use prestashop now.



#4

Posted 26 August 2015 - 04:44 PM

arjit

    PrestaShop Newbie

  • Members
  • Pip
  • 20 Active Posts

Please help :) or Please let me if the question isnt clear



#5

Posted 11 September 2015 - 11:20 AM

B@JTík

    PrestaShop Newbie

  • Members
  • Pip
  • 17 Active Posts
Hi, did you find any solution, PLEASE, or anyone?
I have same problem, create succesfull order (new customer->new address->new cart->new order) in Prestashop (via webservice) from my external one-product microstore (order form), it works well, but I need apply some discounts (2pcs=free shipping, 4pcs=gift, discount vouchers) and it not works, cart rules is not applied for order created via webservice.
 
In webservice XML for creating order are items total_shipping and total_discounts, how it works? When I send any numbers in this items, Prestashop disregard it.
 
(sorry for my bad english)

Edited by B@JTík, 11 September 2015 - 11:59 AM.


#6

Posted 11 September 2015 - 12:56 PM

arjit

    PrestaShop Newbie

  • Members
  • Pip
  • 20 Active Posts

I was able to solve the problem by adding a field in the cart which is cart_rule_id. 

Adding that value to ps_cart_cart_rule. See the table for more details.

The id of coupon you add to the cart rule the order will be generated with that discount/freebee



#7

Posted 11 September 2015 - 03:44 PM

B@JTík

    PrestaShop Newbie

  • Members
  • Pip
  • 17 Active Posts
Thanks much for fast reply.
I'm not sure, if I understand good (sorry, it's my bad english). Do you create new cart via API (webservice), then write remotely direct to database (ps_cart_cart_rule) row with association cart-id -> cart-rule-id and after that you create new order (again via API)?


#8

Posted 11 September 2015 - 03:45 PM

arjit

    PrestaShop Newbie

  • Members
  • Pip
  • 20 Active Posts

Yes correct



#9

Posted 11 September 2015 - 04:03 PM

B@JTík

    PrestaShop Newbie

  • Members
  • Pip
  • 17 Active Posts

Thanks much again, it's very helpful for me.



#10

Posted 14 September 2015 - 03:02 AM

An'im Fahmy

    PrestaShop Newbie

  • Members
  • Pip
  • 23 Active Posts

I am read this thread, and now, I will try this,

Because, I have error when create order with webservice

 

{"status":"Other error

<br \/>Bad parameters given"}

 

 

Thank you



#11

Posted 14 September 2015 - 05:27 AM

An'im Fahmy

    PrestaShop Newbie

  • Members
  • Pip
  • 23 Active Posts

Thanks much again, it's very helpful for me.

 

Yes correct

 

Can you help me?

I was create cart,

And then, when I create order via webservice like this:

<?xml version="1.0" encoding="UTF-8"?>

<prestashop xmlns:xlink="http://www.w3.org/1999/xlink">

    <order>

        <id></id>

        <id_address_delivery>5047</id_address_delivery>

        <id_address_invoice>5047</id_address_invoice>

        <id_cart>35</id_cart>

        <id_currency>1</id_currency>

        <id_lang>1</id_lang>

        <id_customer>34</id_customer>

        <id_carrier>60</id_carrier>

        <current_state>59</current_state>

        <module>bca</module>

        <invoice_number></invoice_number>

        <invoice_date></invoice_date>

        <delivery_number></delivery_number>

        <delivery_date></delivery_date>

        <valid></valid>

        <date_add></date_add>

        <date_upd></date_upd>

        <shipping_number></shipping_number>

        <id_shop_group>1</id_shop_group>

        <id_shop>1</id_shop>

        <secure_key></secure_key>

        <payment>BCA</payment>

        <recyclable></recyclable>

        <gift></gift>

        <gift_message></gift_message>

        <mobile_theme></mobile_theme>

        <total_discounts></total_discounts>

        <total_discounts_tax_incl></total_discounts_tax_incl>

        <total_discounts_tax_excl></total_discounts_tax_excl>

        <total_paid>196000</total_paid>

        <total_paid_tax_incl></total_paid_tax_incl>

        <total_paid_tax_excl></total_paid_tax_excl>

        <total_paid_real>196000</total_paid_real>

        <total_products>196000</total_products>

        <total_products_wt>196000</total_products_wt>

        <total_shipping></total_shipping>

        <total_shipping_tax_incl></total_shipping_tax_incl>

        <total_shipping_tax_excl></total_shipping_tax_excl>

        <carrier_tax_rate></carrier_tax_rate>

        <total_wrapping></total_wrapping>

        <total_wrapping_tax_incl></total_wrapping_tax_incl>

        <total_wrapping_tax_excl></total_wrapping_tax_excl>

        <round_mode></round_mode>

        <round_type></round_type>

        <conversion_rate>1</conversion_rate>

        <reference></reference>

        <associations>

            <order_rows>

                <order_row>

                    <product_id>3</product_id>

                    <product_attribute_id>0</product_attribute_id>

                    <product_quantity>4</product_quantity>

                </order_row>

                <order_row>

                    <product_id>6</product_id>

                    <product_attribute_id>0</product_attribute_id>

                    <product_quantity>4</product_quantity>

                </order_row>

            </order_rows>

        </associations>

    </order>

</prestashop>



{"status":"Other error

<br \/>Bad parameters given"}

And than error: Bad parameters given

Any solutions?

 

 

Thank you



#12

Posted 14 September 2015 - 05:44 AM

arjit

    PrestaShop Newbie

  • Members
  • Pip
  • 20 Active Posts

Can you please tell me what exactly are you trying to do  ? If you are trying to place the order via webservices 

 

Creating the cart 

 

<prestashop xmlns:xlink="http://www.w3.org/1999/xlink">
<cart>
 
<id_address_delivery>5</id_address_delivery>
<id_address_invoice>5</id_address_invoice>
<id_currency >1</id_currency>
<id_customer>1</id_customer>
 
<id_lang >1</id_lang>
<id_shop>1</id_shop>
<delivery_option/>
<secure_key/>
<allow_seperated_package>0</allow_seperated_package>
<date_add>2015-06-23 14:45:08</date_add>
<date_upd>2015-06-23 14:45:08</date_upd>
<associations><cart_rows>
<cart_row>
<id_product >1</id_product>
<id_product_attribute >0</id_product_attribute>
<id_address_delivery >0</id_address_delivery>
<quantity>3</quantity>
</cart_row>
</cart_rows>
</associations>
</cart>
</prestashop>
 
 
 
<prestashop xmlns:xlink="http://www.w3.org/1999/xlink">
<order>
  <id_address_delivery>1</id_address_delivery>
  <id_address_invoice>1</id_address_invoice>
  <id_cart>14</id_cart>
  <id_currency>1</id_currency>
  <id_lang>1</id_lang>
  <id_customer>1</id_customer>
  <id_carrier>1</id_carrier>
  <shipping_number notFilterable="true"/>
  <total_products_wt>53</total_products_wt>
  <conversion_rate>1.000000</conversion_rate>
  <current_state>6</current_state>
 
  <module>cheque</module>
  <id_shop>1</id_shop>
  <payment>Payment by check</payment>
  <total_paid>3300</total_paid>
  <total_paid_tax_incl>3300</total_paid_tax_incl>
  <total_paid_tax_excl>3300</total_paid_tax_excl>
  <total_paid_real>3300</total_paid_real>
  <total_products>3</total_products>
  <total_shipping>2.000000</total_shipping>
<total_shipping_tax_incl>2.000000</total_shipping_tax_incl>
<total_shipping_tax_excl>2.000000</total_shipping_tax_excl>
<carrier_tax_rate>0.000</carrier_tax_rate>
<total_wrapping>0.000000</total_wrapping>
<total_wrapping_tax_incl>0.000000</total_wrapping_tax_incl>
<total_wrapping_tax_excl>0.000000</total_wrapping_tax_excl>
<round_mode>0</round_mode>
<conversion_rate>1.000000</conversion_rate>
 
<associations>
<order_rows>
<order_row>
  <product_id>1</product_id>
  <product_quantity>3</product_quantity>
    <product_name>sofa</product_name>
    <product_price>1100</product_price>
</order_row>
</order_rows>
</associations>
</order>
</prestashop>


#13

Posted 14 September 2015 - 06:36 AM

An'im Fahmy

    PrestaShop Newbie

  • Members
  • Pip
  • 23 Active Posts

Can you please tell me what exactly are you trying to do  ? If you are trying to place the order via webservices 

Thank you Sir,

And yes, I am try to create order via webservice,

I was successfully create customer, address and cart. And stuck in order.

 

I will try your suggestion.



#14

Posted 14 September 2015 - 08:06 AM

An'im Fahmy

    PrestaShop Newbie

  • Members
  • Pip
  • 23 Active Posts

Can you please tell me what exactly are you trying to do  ?

Do you have suggest for me?

<?php
require_once('config.php');
require_once('../PSWebServiceLibrary.php');

//default POST
$_POST['id_currency']=1;
$_POST['id_lang']=1; 
$_POST['id_shop_group']=1; 
$_POST['id_shop']=1;
$_POST['product_attribute_id']=0;
$_POST['current_state']=59;
$_POST['module']=strtolower($_POST['payment']);
$_POST['payment']=strtoupper($_POST['payment']);
$_POST['conversion_rate']=1.000000;
//end default

function getAddress($idCustomer){
	$xml_file = "https://".PS_WS_AUTH_KEY."@".PS_SHOP_PATH."/api/addresses?filter[id_customer]=".$idCustomer;
	$xml = file_get_contents($xml_file);
	$xml = XmlCleanStrips($xml);
	$xml = simplexml_load_string($xml,'SimpleXMLElement', LIBXML_NOCDATA);
	$xml = json_decode(json_encode($xml));
	$id_address = (isset($xml->addresses->address->{'@attributes'}->id) ? $xml->addresses->address->{'@attributes'}->id : $xml->addresses->address[0]->{'@attributes'}->id);
	return $id_address;
}

function getCart($idCart){
	$xml_file = "https://".PS_WS_AUTH_KEY."@".PS_SHOP_PATH."/api/carts/".$idCart;
	$xml = file_get_contents($xml_file);
	$xml = XmlCleanStrips($xml);
	$xml = simplexml_load_string($xml,'SimpleXMLElement', LIBXML_NOCDATA);
	$xml = json_decode(json_encode($xml));
	$id_customer  = $xml->cart->id_customer;
	$xml = $xml->cart->associations->cart_rows;
	unset($xml->{'@attributes'});
	$arr["id_customer"] = $id_customer;
	$arr["rows"] = $xml;
	return $arr;
}

function updateCartAddr($idCart){
	try{
		$webService = new PrestaShopWebservice(PS_SHOP_PATH, PS_WS_AUTH_KEY, DEBUG);
		$opt = array('resource' => 'carts');
		if (isset($idCart)){
			$opt['id'] = $idCart;
		}
		$xml = $webService->get($opt);

		// Here we get the elements from children of customer markup which is children of prestashop root markup
		$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"] = 'Other error<br />'.$e->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
		foreach ($resources as $nodeKey => $node){
			$resources->$nodeKey = $resources->$nodeKey;
		}
		try	{
			$cartRows = getCart($idCart)["rows"];
			$defaulAddr = getAddress(getCart($idCart)["id_customer"]);
			$default_id_address_delivery = (isset($_POST['id_address_delivery']) ? $_POST['id_address_delivery'] : $defaulAddr);
			$default_id_address_invoice = (isset($_POST['id_address_invoice']) ? $_POST['id_address_invoice'] : $defaulAddr);
			$resources->id_address_delivery = $default_id_address_delivery;
			$resources->id_address_invoice = $default_id_address_invoice;
			$orderke = 0;
			if(count($cartRows->cart_row)==1){
				foreach($cartRows as $key => $value){
					$resources->associations->cart_rows->cart_row[$orderke]->id_product = $value->id_product;
					$resources->associations->cart_rows->cart_row[$orderke]->id_product_attribute = 0;
					$resources->associations->cart_rows->cart_row[$orderke]->quantity = $value->quantity;
					$resources->associations->cart_rows->cart_row[$orderke]->id_address_delivery = $default_id_address_delivery;
					$orderke++;
				}
			}else if(count($cartRows->cart_row)>0){
				foreach($cartRows->cart_row as $key => $value){
					$resources->associations->cart_rows->cart_row[$orderke]->id_product = $value->id_product;
					$resources->associations->cart_rows->cart_row[$orderke]->id_product_attribute = 0;
					$resources->associations->cart_rows->cart_row[$orderke]->quantity = $value->quantity;
					$resources->associations->cart_rows->cart_row[$orderke]->id_address_delivery = $default_id_address_delivery;
					$orderke++;
				}
			}
			$opt = array('resource' => 'carts');
			$opt['putXml'] = $xml->asXML();
			
			//print_r($opt['putXml']);
			//return false;  //COMMENT THIS!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
			
			
			$opt['id'] = $idCart;
			$xml = $webService->edit($opt);
		}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);
		}
	}

}
//updateCartAddr(35);//DO BEFORE PLACE ORDER

function getProductInfo($idProduct){
	$xml_file = "https://".PS_WS_AUTH_KEY."@".PS_SHOP_PATH."/api/products/".$idProduct;
	$xml = file_get_contents($xml_file);
	$xml = XmlCleanStrips($xml);
	$xml = simplexml_load_string($xml,'SimpleXMLElement', LIBXML_NOCDATA);
	$discount = $xml->product->addChild('ina_discount');
	$inaapi = new inaAPI;
	$inadiscount = $inaapi->getProductDiscount($idProduct);
	$from_quantity 	= (isset($inadiscount[0]['from_quantity']) ? $inadiscount[0]['from_quantity'] : 0);
	$reduction 		= (isset($inadiscount[0]['reduction']) ? $inadiscount[0]['reduction'] : 0);
	$discount->addChild('reduction', $reduction);
	$discount->addChild('from_quantity', $from_quantity);
	$product = json_decode(json_encode($xml))->product;
	$info = array();
	$name = $product->name->language;
	$price = (float)$product->price;
	$_reduction = (float)$product->ina_discount->reduction;
	$_from_quantity = (integer)$product->ina_discount->from_quantity;
	$info['name']=$name;
	$info['price']=$price;
	$info['reduction']=$_reduction;
	$info['from_quantity']=$_from_quantity;
	return($info);
}
//print_r(getProductInfo(3));

function placeOrder($idCart){
	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"]);
		$_POST['id_address_delivery'] = (isset($_POST['id_address_delivery']) ? $_POST['id_address_delivery'] : $defaulAddr);
		$_POST['id_address_invoice'] = (isset($_POST['id_address_invoice']) ? $_POST['id_address_invoice'] : $defaulAddr);
		foreach ($resources as $nodeKey => $node){
			$resources->$nodeKey = $_POST[$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['putXml'] = $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);
		}
	}

}
if(isset($_POST['id_cart']) && ctype_digit($_POST['id_cart'])){
	placeOrder($_POST['id_cart']);
}


#15

Posted 14 September 2015 - 08:07 AM

An'im Fahmy

    PrestaShop Newbie

  • Members
  • Pip
  • 23 Active Posts

And this is the result

<?xml version="1.0" encoding="UTF-8"?>
<prestashop xmlns:xlink="http://www.w3.org/1999/xlink">
    <order>
        <id></id>
        <id_address_delivery>5047</id_address_delivery>
        <id_address_invoice>5047</id_address_invoice>
        <id_cart>37</id_cart>
        <id_currency>1</id_currency>
        <id_lang>1</id_lang>
        <id_customer>34</id_customer>
        <id_carrier>60</id_carrier>
        <current_state>59</current_state>
        <module>bca</module>
        <invoice_number></invoice_number>
        <invoice_date></invoice_date>
        <delivery_number></delivery_number>
        <delivery_date></delivery_date>
        <valid></valid>
        <date_add></date_add>
        <date_upd></date_upd>
        <shipping_number></shipping_number>
        <id_shop_group>1</id_shop_group>
        <id_shop>1</id_shop>
        <secure_key></secure_key>
        <payment>BCA</payment>
        <recyclable></recyclable>
        <gift></gift>
        <gift_message></gift_message>
        <mobile_theme></mobile_theme>
        <total_discounts></total_discounts>
        <total_discounts_tax_incl></total_discounts_tax_incl>
        <total_discounts_tax_excl></total_discounts_tax_excl>
        <total_paid>816000</total_paid>
        <total_paid_tax_incl>816000</total_paid_tax_incl>
        <total_paid_tax_excl>816000</total_paid_tax_excl>
        <total_paid_real>825000</total_paid_real>
        <total_products>816000</total_products>
        <total_products_wt>816000</total_products_wt>
        <total_shipping>0</total_shipping>
        <total_shipping_tax_incl>0</total_shipping_tax_incl>
        <total_shipping_tax_excl>0</total_shipping_tax_excl>
        <carrier_tax_rate>0</carrier_tax_rate>
        <total_wrapping>0</total_wrapping>
        <total_wrapping_tax_incl>0</total_wrapping_tax_incl>
        <total_wrapping_tax_excl>0</total_wrapping_tax_excl>
        <round_mode>0</round_mode>
        <round_type></round_type>
        <conversion_rate>1</conversion_rate>
        <reference></reference>
        <associations>
            <order_rows>
                <order_row>
                    <product_id>3</product_id>
                    <product_attribute_id>0</product_attribute_id>
                    <product_quantity>1</product_quantity>
                    <product_name>Raflesia Yellow ggwp</product_name>
                    <product_price>30000</product_price>
                </order_row>
                <order_row>
                    <product_id>6</product_id>
                    <product_attribute_id>0</product_attribute_id>
                    <product_quantity>1</product_quantity>
                    <product_name>Good Night</product_name>
                    <product_price>795000</product_price>
                </order_row>
            </order_rows>
        </associations>
    </order>
</prestashop>
{"status":"Other error
<br \/>Bad parameters given"}


#16

Posted 15 September 2015 - 12:35 PM

B@JTík

    PrestaShop Newbie

  • Members
  • Pip
  • 17 Active Posts

Do you have suggest for me?

It's very nice piece of code, thank you for share it.

 

And this is the result

I have my "stupid newbee" way for learning how-it-works. This working fine for me. Perhaps it may be useful for you.

<?php
header('Content-type: text/html; charset=utf-8');



// POST Data simulation {for testing}

$_POST['firstname'] = 'Firstname';
$_POST['lastname'] = 'Lastname';
$_POST['address1'] = 'MyStreet 321';
$_POST['postcode'] = '654321';
$_POST['city'] = 'MyCity';
$_POST['email'] = 'my.email@mydomain.tld';
$_POST['phone'] = '987654321';
$_POST['quantity'] = '1';



// SETings

define('DEBUG', true);
define('PS_SHOP_PATH', 'http://127.0.0.1/_presta');
define('PS_WS_AUTH_KEY', 'QRDL6DG7P7RMU26UT5T1GWIQC43MX2TV');

require_once('./PSWebServiceLibrary.php');
$webService = new PrestaShopWebservice(PS_SHOP_PATH, PS_WS_AUTH_KEY, DEBUG);

$id['country'] = '1';
$id['lang'] = '2';
$id['currency'] = '1';
$id['carrier'] = '6';

$product['id'] = '1';
$product['price'] = '399';

$product['total'] = $product['price'] * $_POST['quantity'];



// CREATE Customer

$xml = $webService->get(array('url' => PS_SHOP_PATH.'/api/customers?schema=blank'));

$xml->customer->firstname = $_POST['firstname'];
$xml->customer->lastname = $_POST['lastname'];
$xml->customer->email = $_POST['email'];
$xml->customer->newsletter = '1';
$xml->customer->optin = '1';
$xml->customer->active = '1';

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

// ID of created customer

$id['customer'] = $xml->customer->id; 



// CREATE Address

$xml = $webService->get(array('url' => PS_SHOP_PATH.'/api/addresses?schema=blank'));

$xml->address->id_customer = $id['customer'];
$xml->address->firstname = $_POST['firstname'];
$xml->address->lastname = $_POST['lastname'];
$xml->address->address1 = $_POST['address1'];
$xml->address->postcode = $_POST['postcode'];
$xml->address->city = $_POST['city'];
$xml->address->phone = $_POST['phone'];
$xml->address->id_country = $id['country'];
$xml->address->alias = '-';

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

// ID of created address

$id['address'] = $xml->address->id;



// CREATE Cart

$xml = $webService->get(array('url' => PS_SHOP_PATH.'/api/carts?schema=blank'));

$xml->cart->id_customer = $id['customer'];
$xml->cart->id_address_delivery = $id['address'];
$xml->cart->id_address_invoice = $id['address'];
$xml->cart->id_currency = $id['currency'];
$xml->cart->id_lang = $id['lang'];
$xml->cart->id_carrier = $id['carrier'];

$xml->cart->associations->cart_rows->cart_row->id_product = $product['id'];
$xml->cart->associations->cart_rows->cart_row->quantity = $_POST['quantity'];

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

// ID of created cart

$id['cart'] = $xml->cart->id;



// CREATE Order

$xml = $webService->get(array('url' => PS_SHOP_PATH.'/api/orders?schema=blank'));

$xml->order->id_customer = $id['customer'];
$xml->order->id_address_delivery = $id['address'];
$xml->order->id_address_invoice = $id['address'];
$xml->order->id_cart = $id['cart'];
$xml->order->id_currency = $id['currency'];
$xml->order->id_lang = $id['lang'];
$xml->order->id_carrier = $id['carrier'];
$xml->order->payment = 'Cash on delivery';
$xml->order->module = 'cashondelivery';
$xml->order->total_paid = $product['total'];
$xml->order->total_paid_real = '0';
$xml->order->total_products = $product['total'];
$xml->order->total_products_wt = $product['total'];
$xml->order->conversion_rate = '1';

$xml->order->associations->order_rows->order_row->product_id = $product['id'];
$xml->order->associations->order_rows->order_row->product_quantity = $_POST['quantity'];

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

?>

It needs yet something like

if (email exist) update customer and address
else create customer and address

and other things for production use, it's really only for learning.


Edited by B@JTík, 15 September 2015 - 04:59 PM.


#17

Posted 15 September 2015 - 07:10 PM

An'im Fahmy

    PrestaShop Newbie

  • Members
  • Pip
  • 23 Active Posts
$opt['postXml'] = $xml->asXML();

Thank you very much for your reply.

My code wrong here:

$opt = array('resource' => 'orders');
$opt['putXml'] = $xml->asXML();

print_r($opt['putXml']);
//return false;  //COMMENT THIS!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

I type 'putXml' for placing order, after I change to postXml, all running well without change everything after that, order successfully added to database.

But, one more problem,

With your code or my code, not showing to back office because nothing address input in database, actually I was added the address.

 

Once again

 

Thank you  :D  :D  :D



#18

Posted 11 December 2015 - 11:08 AM

Alexandre de Lyon

    PrestaShop Newbie

  • Members
  • Pip
  • 24 Active Posts

Hello and thank you for your share ! 
 
I'm begginer. I tried your code and I still have this result :

Fatal error: Uncaught exception 'PrestaShopWebserviceException' with message 'This call to PrestaShop Web Services failed and returned an HTTP status of 500. That means: Internal Server Error.' in C:\xampp\htdocs\prestashop\demo\inc\PSWebServiceLibrary.php:87 Stack trace: #0 C:\xampp\htdocs\prestashop\demo\inc\PSWebServiceLibrary.php(217): PrestaShopWebservice->checkStatusCode(500) #1 C:\xampp\htdocs\prestashop\demo\test.php(133): PrestaShopWebservice->add(Array) #2 {main} thrown in C:\xampp\htdocs\prestashop\demo\inc\PSWebServiceLibrary.php on line 87

The customer is created. I can see the product bought in the customer page (BO) but no order placed!

 

Maybe you know why ?


Edited by alexandre.chapey@free.fr, 11 December 2015 - 11:30 AM.


#19

Posted 16 December 2015 - 09:21 PM

B@JTík

    PrestaShop Newbie

  • Members
  • Pip
  • 17 Active Posts

I tried your code and I still have this result :

Check ID's of carrier, country, lang, currency, payment module ... all must exist and be enabled.

My actual and working code with NEW/EXIST customer testing and with cart rules:

<?php
header('Content-type: text/html; charset=utf-8');



//------------------------------------
// POST Data simulation (for testing)

// $_GET['pf_firstname'] = 'Firstname';
// $_GET['pf_lastname'] = 'Lastname';
// $_GET['pf_address1'] = 'MyStreet 321';
// $_GET['pf_postcode'] = '54321';
// $_GET['pf_city'] = 'MyCity';
// $_GET['pf_email'] = 'firstname.lastname@domain.tld';
// $_GET['pf_phone'] = '987654321';
// $_GET['pf_quantity'] = '4';

// $_GET['pf_cart_rule_free_shipping'] = 'true';
// $_GET['pf_cart_rule_free_gift'] = 'true';
// $_GET['pf_cart_rule_discount_code'] = 'true';



//---------------
// Configuration

define('DEBUG', false);
define('PS_SHOP_PATH', 'http://'.$_SERVER['HTTP_HOST'].'/_presta');
define('PS_WS_AUTH_KEY', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ123456');

require_once('PSWebServiceLibrary.php');
$webService = new PrestaShopWebservice(PS_SHOP_PATH, PS_WS_AUTH_KEY, DEBUG);

$id['country'] = '16';
$id['lang'] = '1';
$id['currency'] = '1';
$id['carrier'] = '3';

$product['id'] = '1';
$product['price'] = '399';

$shipping = '117';

include ("../_presta/config/settings.inc.php");  // nastavení databáze prestashopu (jen kvůli Cart Rules)
if ($_GET['pf_cart_rule_free_gift'] == 'true') $_GET['pf_quantity']++;

$product['total'] = $product['price'] * $_GET['pf_quantity'];



//-----------------
// CREATE/UPDATE Customer and Address

$xml = $webService->get(array('resource' => 'customers', 'filter[email]' => $_GET['pf_email'], 'display' => '[id]', 'limit' => '1'));
if ($id['customer'] = $xml->customers->customer->id){ // If e-mail registered UPDATE (Customer and Address)

  $xml = $webService->get(array('resource' => 'customers', 'id' => $id['customer'])); // UPDATE Customer 
  $xml->customer->firstname = $_GET['pf_firstname'];
  $xml->customer->lastname = $_GET['pf_lastname'];
  $xml = $webService->edit(array('resource' => 'customers', 'id' => $id['customer'], 'putXml' => $xml->asXML())); 

  $xml = $webService->get(array('resource' => 'addresses', 'filter[id_customer]' => '['.$id['customer'].']', 'display' => '[id]', 'limit' => '1'));  
  $id['address'] = $xml->addresses->address->id;
  $xml = $webService->get(array('resource' => 'addresses', 'id' => $id['address'])); // UPDATE Address
  $xml->address->firstname = $_GET['pf_firstname'];
  $xml->address->lastname = $_GET['pf_lastname'];
  $xml->address->address1 = $_GET['pf_address1'];
  $xml->address->postcode = $_GET['pf_postcode'];
  $xml->address->city = $_GET['pf_city'];
  $xml->address->phone = $_GET['pf_phone'];
  $xml->address->id_country = $id['country'];
  $xml = $webService->edit(array('resource' => 'addresses', 'id' => $id['address'], 'putXml' => $xml->asXML()));  

} else { // If e-mail NOT registered CREATE (Customer and Address)

  $xml = $webService->get(array('url' => PS_SHOP_PATH.'/api/customers?schema=blank')); // CREATE Customer
  $xml->customer->firstname = $_GET['pf_firstname'];
  $xml->customer->lastname = $_GET['pf_lastname'];
  $xml->customer->email = $_GET['pf_email'];
  $xml->customer->newsletter = '1';
  $xml->customer->optin = '1';
  $xml->customer->active = '1';
  $xml->customer->associations->groups->group->id = '3';
  $xml = $webService->add(array('resource' => 'customers', 'postXml' => $xml->asXML()));
  $id['customer'] = $xml->customer->id; // ID of created customer 

  $xml = $webService->get(array('url' => PS_SHOP_PATH.'/api/addresses?schema=blank')); // CREATE Address
  $xml->address->id_customer = $id['customer'];
  $xml->address->firstname = $_GET['pf_firstname'];
  $xml->address->lastname = $_GET['pf_lastname'];
  $xml->address->address1 = $_GET['pf_address1'];
  $xml->address->postcode = $_GET['pf_postcode'];
  $xml->address->city = $_GET['pf_city'];
  $xml->address->phone = $_GET['pf_phone'];
  $xml->address->id_country = $id['country'];
  $xml->address->alias = '-';
  $xml = $webService->add(array('resource' => 'addresses', 'postXml' => $xml->asXML()));
  $id['address'] = $xml->address->id; // ID of created address
}



//-------------
// CREATE Cart

$xml = $webService->get(array('url' => PS_SHOP_PATH.'/api/carts?schema=blank'));

$xml->cart->id_customer = $id['customer'];
$xml->cart->id_address_delivery = $id['address'];
$xml->cart->id_address_invoice = $id['address'];
$xml->cart->id_currency = $id['currency'];
$xml->cart->id_lang = $id['lang'];
$xml->cart->id_carrier = $id['carrier'];

$xml->cart->associations->cart_rows->cart_row->id_product = $product['id'];
$xml->cart->associations->cart_rows->cart_row->quantity = $_GET['pf_quantity'];

$xml = $webService->add(array('resource' => 'carts', 'postXml' => $xml->asXML()));
$id['cart'] = $xml->cart->id; // ID of created cart



//---------------
// SET Cart rules

$pdo = new PDO("mysql:dbname="._DB_NAME_.";host="._DB_SERVER_, _DB_USER_, _DB_PASSWD_);    
$pdo->exec("set names utf8");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$query = $pdo->prepare("INSERT into "._DB_PREFIX_."cart_cart_rule (id_cart, id_cart_rule) VALUES(?, ?)");
unset($pdo);

$discounts = 0;

if ($_GET['pf_cart_rule_free_shipping'] == 'true'){
  $query->execute(array($id['cart'], "1"));
  $shipping = 0;
}
if ($_GET['pf_cart_rule_free_gift'] == 'true'){
  $query->execute(array($id['cart'], "2"));  
  $discounts += 399;
}
if ($_GET['pf_cart_rule_discount_code'] == 'true'){
  $query->execute(array($id['cart'], "3"));  
  $discounts += 80;
}



//--------------
// CREATE Order

$xml = $webService->get(array('url' => PS_SHOP_PATH.'/api/orders?schema=blank'));

$xml->order->id_customer = $id['customer'];
$xml->order->id_address_delivery = $id['address'];
$xml->order->id_address_invoice = $id['address'];
$xml->order->id_cart = $id['cart'];
$xml->order->id_currency = $id['currency'];
$xml->order->id_lang = $id['lang'];
$xml->order->id_carrier = $id['carrier'];
$xml->order->payment = 'Dobírka';
$xml->order->module = 'cashondelivery';
$xml->order->total_discounts = $discounts;
$xml->order->total_paid = $product['total'] + $shipping - $discounts;
$xml->order->total_paid_real = '0';
$xml->order->total_products = $product['total'];
$xml->order->total_products_wt = $product['total'];
$xml->order->conversion_rate = '1';

$xml->order->associations->order_rows->order_row->product_id = $product['id'];
$xml->order->associations->order_rows->order_row->product_quantity = $_GET['pf_quantity'];

$xml = $webService->add(array('resource' => 'orders', 'postXml' => $xml->asXML()));
$id['order'] = $xml->order->id; // ID of created order



//--------------
// CHANGE Order State

$xml = $webService->get(array('resource' => 'orders', 'id' => $id['order']));
$xml->order->current_state = '3';
$xml = $webService->edit(array('resource' => 'orders', 'id' => $id['order'], 'putXml' => $xml->asXML()));



//--------------
// THANK YOU!

header('Location: ../dekujeme.php');
exit;
?>


#20

Posted 31 December 2015 - 03:05 PM

AbdullahBasit

    PrestaShop Newbie

  • Members
  • Pip
  • 13 Active Posts

Are you sure you need to write "putXml" instead of "postXml" ?





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

Cookies help us deliver our services. By using our services, you agree to use our cookies.     Learn more