Jump to content

[Webservice Api] How To Create A Full Order (Customer, Cart And Order)


Pierre.CIHOLAS

Recommended Posts

Hello again,

 

I tried to do my own customer creation script, but I have an error "Bad request", here is the full logfile line :

[Wed Feb 27 11:20:27 2013] [error] [client 82.127.150.84] PHP Fatal error:  Uncaught exception 'PrestaShopWebserviceException' with message 'Bad parameters given' in /home/flyzone/venir/inc/PSWebServiceLibrary.php:218\nStack trace:\n#0 /home/flyzone/venir/test.php(37): PrestaShopWebservice->add(Array)\n#1 {main}\n  thrown in /home/flyzone/venir/inc/PSWebServiceLibrary.php on line 218

 

And here is my script :

 

<?php
// Vars & includes required to use the lib
define('DEBUG', true);
define('PS_SHOP_PATH', 'http://myshop.fr/');
define('PS_WS_AUTH_KEY', '0000000000000000000000000000000000000');
require_once('./inc/PSWebServiceLibrary.php');

// Getting the empty XML document to send back completed
$webService = new PrestaShopWebservice(PS_SHOP_PATH, PS_WS_AUTH_KEY, DEBUG);
$xml = $webService->get( array( 'url' => 'http://myshop.fr/api/customers?schema=blank' ) );
$resources = $xml->children()->children();

// Information about the customer to create
$infos = array(
'active' => '1',
'birthday' => '2011-12-02',
'deleted' => '0',
'email' => '[email protected]',
'firstname' => 'ILOL',
'id' => '845',
'id_default_group' => '1',
'id_gender' => '1',
'ip_registration_newsletter' => '',
'is_guest' => '0',
'last_passwd_gen' => '2011-12-02 16:15:22',
'lastname' => 'Lol',
'newsletter' => '0',
'newsletter_date_add' => '',
'note' => '',
'optin' => '0',
'passwd' => '97d1b585e6f86d2e1fe74f95961487df',
'secure_key' => '47ce86627c1f3c792a80773c5d2deaf8'
);

// Completing the XML document
foreach ( $resources as $nodeKey => $node ) {
 $resources->$nodeKey = $infos[ $nodeKey ];
}

// Send !
$opt = array( 'resource' => 'customers' );
$opt[ 'xml' ] = $xml->asXML();
print_r($opt);
$xml = $webService->add( $opt );
?>

 

Anyone got an idea of what is wrong ? Or anyone has an exemple script, on a detailed list of parameters and values to send to make it work ?

 

Thank you.

Edited by Pierre.CIHOLAS (see edit history)
Link to comment
Share on other sites

And one more repost to provide a better solution !

 

To create customers I found, it was just a variables problem, but for carts & orders, the XML is on multiple levels, so I made a script taking pure XML as imput so you can use it on all the parts of the shop !!

 

Enjoy :

 

<?php
define('DEBUG', true);
define('PS_SHOP_PATH', 'http://myshop.fr');
define('PS_WS_AUTH_KEY', '00000000000000000000000000000000');
require_once('../inc/PSWebServiceLibrary.php');
$psXML = <<<XML
<prestashop>
<cart>
 <id/>
 <id_address_delivery>3</id_address_delivery>
 <id_address_invoice>3</id_address_invoice>
 <id_currency>1</id_currency>
 <id_customer>2</id_customer>
 <id_guest>0</id_guest>
 <id_lang>2</id_lang>
 <id_carrier>8</id_carrier>
 <recyclable>1</recyclable>
 <gift>0</gift>
 <gift_message/>
 <associations>
  <cart_rows>
   <cart_row>
 <id_product>10</id_product>
 <id_product_attribute>39</id_product_attribute>
 <quantity>1</quantity>
   </cart_row>
  </cart_rows>
 </associations>
</cart>
</prestashop>
XML;
$webService = new PrestaShopWebservice(PS_SHOP_PATH, PS_WS_AUTH_KEY, DEBUG);
$xml = new SimpleXMLElement($psXML);
$opt = array( 'resource' => 'carts' );
$opt['postXml'] = $xml->asXML();
$xml = $webService->add( $opt );
?>

  • Like 1
Link to comment
Share on other sites

  • 2 weeks later...

Hi alexvs1980 !

 

I had some other projects to develop before so I didn't tried this script in production yet but I will finish it next week.

I need to do a one PHP file taking POST variables and creating the prestashop order in one shot, so if I have the same problem I'll get back to you with the solution, otherwise I will send you my full script so you can check want's wrong with yours.

 

First of all, you should be aware that the webservice doesn't run any tests on the XML sent, so be sure off all informations, check that products added to the carts are existing, activated, buyable by everyone.

Next, go to the prestashop carts viewer and try to investigate what's wrong by comparing it to a fully functionnal cart with a price.

 

If you find the solution, please share it.

Edited by Pierre.CIHOLAS (see edit history)
Link to comment
Share on other sites

  • 2 months later...

Hi! i'm able to create an order with webservice but imposed a discount I get an error in the order detail. "xxx yyy paid instead of [full_price]". In order list, however, the amount seems correct.

I noticed that you can not recover the discounted price.

Solutions?

 

Thanks in advance

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

  • 1 month later...
  • 10 months later...

Hi! i'm able to create an order with webservice but imposed a discount I get an error in the order detail. "xxx yyy paid instead of [full_price]". In order list, however, the amount seems correct.

I noticed that you can not recover the discounted price.

Solutions?

 

Thanks in advance

Hi Loreian,

 

I am trying to create an order in webservice of prestashop but not able to figure out any workaround for that.

Can you please help me do that. or share relevant files somehow.??

 

Thanks in advance.

Link to comment
Share on other sites

  • 2 months later...
  • 1 year later...
            $webService = new PrestaShopWebservice(PS_SHOP_PATH, PS_WS_AUTH_KEY, DEBUG);

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

 

            $customer = array();

            $product = array();

 

            if (!empty(Tools::getValue('c_email')))

                $customer['email'] = Tools::getValue('c_email');

            else

                $customer['email'] = '[email protected]';

 

            $customer['firstname'] = Tools::getValue('fname');

            $customer['lastname'] = Tools::getValue('lname');

            $customer['address1'] = Tools::getValue('c_address');

            $customer['city'] = Tools::getValue('c_city');

            $customer['phone'] = Tools::getValue('c_phone');

 

            $id['country'] = '165';

            $id['lang'] = '1';

            $id['currency'] = '1';

            $id['carrier'] = '3';

 

            $product['quantity'] = Tools::getValue('c_qty');

            $product['id'] = $id_product;

            $product['price'] = Product::getPriceStatic($product['id']);

            $product['name'] = Product::getProductName($product['id']);

 

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

 

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

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

            $xml->customer->email = $customer['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=synopsis'));

 

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

            $xml->address->firstname = $customer['firstname'];

            $xml->address->lastname = $customer['lastname'];

            $xml->address->address1 = $customer['address1'];

            $xml->address->city = $customer['city'];

            $xml->address->phone_mobile = $customer['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 = $product['quantity'];

            if(!empty(Tools::getValue('product_attr')))

                $xml->cart->associations->cart_rows->cart_row->id_product_attribute = Tools::getValue('product_attr');

 

            $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 = 3;

            $xml->order->current_state = 3;

            $xml->order->valid = 0;

            $xml->order->payment = 'Cash on delivery';

            $xml->order->module = 'cashondelivery';

            $xml->order->total_paid = $product['total'];

            $xml->order->total_paid_tax_incl = $product['total'];

            $xml->order->total_paid_tax_excl = $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 = $product['quantity'];

 

 

            $opt = array('resource' => 'orders');

            $opt['postXml'] = $xml->asXML();

            $xml = $webService->add($opt);

 

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

            $id['secure_key'] = $xml->order->secure_key;

 

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

 

            $xml->order_history->id_order = $id['order'];

            $xml->order_history->id_order_state = '3';

 

            $opt = array('resource' => 'order_histories');

            $opt['postXml'] = $xml->asXML();

            $xml = $webService->add($opt);

Edited by AbdullahBasit (see edit history)
  • Like 3
Link to comment
Share on other sites

  • 1 month later...
Hi,

I'm using the Prestashop API to create a mobile version of my site, and I want to insert an order.

My problem is that the order is inserted correctly but the total price don't include taxes (if I use the web page, the order is inserted OK, but with the web services it is wrong). I have tried to modify the total price with the PUT method but Prestashop still put the same value.

Image attached with the problem

 

Can anyone help me? or advice me with a solution?

Thanks

Federico

post-1080838-0-70992500-1455550148_thumb.png

  • Like 1
Link to comment
Share on other sites

  • 2 months later...
  • 5 months later...

Hi there!

 

I also would like to share my code. It works fine and I hope it would be useful for anyone who starts working with Prestashop WebServices:

<?php
/*
 *
 * 1) create Customer (opt.)
 * 2) create Address (opt.)
 * 3) create Cart with order_rows and with product id's and quantities
 * 4) create the Order
 * 
*/
// Vars & includes required to use the lib
define('DEBUG', true);
define('PS_SHOP_PATH', 'http://ps.myserver.int/');
define('PS_WS_AUTH_KEY', 'xxxxx');
require_once('lib/PSWebServiceLibrary.php');
 
// If != 0, we don't create the corresponding structure
$id_customer    = 0;
$id_address     = 0;
$id_cart        = 0;
 
try {
$webService = new PrestaShopWebservice(PS_SHOP_PATH, PS_WS_AUTH_KEY, DEBUG);
 
        /*
         *  1. Create new customer
         */
        if(!$id_customer){
            // Getting the empty XML document to send back completed
            $xml = $webService->get( array( 'url' => PS_SHOP_PATH .'api/customers?schema=blank' ) );
            
            // Adding dinamic values
            // Required
            $xml->customer->passwd              = $passwd;
            $xml->customer->lastname            = $lastname;
            $xml->customer->firstname           = $firstname;
            $xml->customer->email               = $email;
            // Others
            $xml->customer->id_lang             = $id_lang;
            $xml->customer->id_shop             = 1;
            $xml->customer->id_shop_group       = 1;
            $xml->customer->id_default_group    = $id_group; // Customers    
            $xml->customer->active              = 1; 
            $xml->customer->newsletter          = 1;
            $xml->customer->newsletter_date_add = $date_now;
            $xml->customer->last_passwd_gen     = $date_now;
            $xml->customer->date_add            = $date_now;
            $xml->customer->date_upd            = $date_now;
            $xml->customer->id_gender           = $id_gender;
            $xml->customer->associations->groups->group[0]->id = $id_group; // customers
 
             // Adding the new customer
            $opt = array( 'resource' => 'customers' );
            $opt['postXml'] = $xml->asXML();
            $xml = $webService->add( $opt );
            $id_customer = $xml->customer->id;
        }
        
        
        /*
        * 2. Create an address
        */
        if(!$id_address){
            // Getting the empty XML document to send back completed
            $xml = $webService->get( array( 'url' => PS_SHOP_PATH .'api/addresses?schema=blank' ) );
 
            // Adding dinamic and mandatory fields
            // Required
            $xml->address->id_customer  = $id_customer;
            $xml->address->id_country   = $id_country;
            $xml->address->alias        = $firstname.' '.$lastname.'\'alias';
            $xml->address->lastname     = $lastname;
            $xml->address->firstname    = $firstname;
            $xml->address->city         = $city;
            $xml->address->address1     = $address1;
            // Others
            $xml->address->phone_mobile = $phone_mobile;
            $xml->address->postcode     = $ZIP;
            $xml->address->date_add     = $date_now;
            $xml->address->date_upd     = $date_now;
 
            // Adding the new Customer's Addresss
            $opt = array( 'resource' => 'addresses' );
            $opt['postXml'] = $xml->asXML();
            $xml = $webService->add( $opt );
            $id_address = $xml->address->id;   
        }
 
 
 
        /*
         * 3. Create new cart
         * 
         */
        if(!$id_cart){
            // Getting the empty XML document to send back completed
            $xml = $webService->get( array( 'url' => PS_SHOP_PATH .'api/carts?schema=blank' ) );
 
            // Adding dinamic and mandatory fields
            // Required
            $xml->cart->id_currency         = $id_currency;
            $xml->cart->id_lang             = $id_lang;
            $xml->cart->associations->cart_rows->cart_row[0]->id_product            = $products[0]['id_product'];
            $xml->cart->associations->cart_rows->cart_row[0]->id_product_attribute  = $products[0]['id_product_attribute'];
            $xml->cart->associations->cart_rows->cart_row[0]->id_address_delivery   = $id_address;
            $xml->cart->associations->cart_rows->cart_row[0]->quantity              = $products[0]['quantity'];
            // Others
            $xml->cart->id_address_delivery = $id_address;
            $xml->cart->id_address_invoice  = $id_address;
            $xml->cart->id_customer         = $id_customer;
            $xml->cart->carrier             = $id_carrier;
            $xml->cart->date_add            = $date_now;
            $xml->cart->date_upd            = $date_now;
 
            // Adding the new customer's cart        
            $opt = array( 'resource' => 'carts' );
            $opt['postXml'] = $xml->asXML();
            $xml = $webService->add( $opt );
            $id_cart = $xml->cart->id;   
        }
       
        
        /*
        * 4. Create the order 
        * 
        */
        // Getting the structure of an order
$xml = $webService->get(array('url' => PS_SHOP_PATH .'api/orders/?schema=blank'));
 
        // Adding dinamic and required fields
        // Required
$xml->order->id_address_delivery    = $id_address; // Customer 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_customer            = $id_customer; 
$xml->order->id_carrier             = $id_carrier;
        $xml->order->module                 = $order_module;
$xml->order->payment                = $order_payment;        
        $xml->order->total_paid             = $total_paid;
        $xml->order->total_paid_real        = $total_paid_real;
        $xml->order->total_products         = $total_products;
        $xml->order->total_products_wt      = $total_products_wt;
        $xml->order->conversion_rate        = 1;
        // Others
$xml->order->valid                      = 1; 
        $xml->order->current_state              = $id_status;        
        $xml->order->total_discounts            = $total_discounts;
        $xml->order->total_discounts_tax_incl   = $total_discounts_tax_incl;
        $xml->order->total_discounts_tax_excl   = $total_discounts_tax_excl;
        $xml->order->total_paid_tax_incl        = $total_paid_tax_incl;
        $xml->order->total_paid_tax_excl        = $total_paid_tax_excl;
        $xml->order->total_shipping             = $total_shipping;
        $xml->order->total_shipping_tax_incl    = $total_shipping_tax_incl;
        $xml->order->total_shipping_tax_excl    = $total_shipping_tax_excl;
        // Order Row. Required
        $xml->order->associations->order_rows->order_row[0]->product_id             = $products[0]['id_product'];
        $xml->order->associations->order_rows->order_row[0]->product_attribute_id   = $products[0]['id_product_attribute'];
        $xml->order->associations->order_rows->order_row[0]->product_quantity       = $products[0]['quantity'];
        // Order Row. Others
        $xml->order->associations->order_rows->order_row[0]->product_name           = $products[0]['name'];
        $xml->order->associations->order_rows->order_row[0]->product_reference      = $products[0]['reference'];
        $xml->order->associations->order_rows->order_row[0]->product_price          = $products[0]['product_price'];
        $xml->order->associations->order_rows->order_row[0]->unit_price_tax_incl    = $products[0]['product_price'];
        $xml->order->associations->order_rows->order_row[0]->unit_price_tax_excl    = $products[0]['product_price'];
        
        // Creating the order
        $opt = array( 'resource' => 'orders' );
        $opt['postXml'] = $xml->asXML();
        $xml = $webService->add( $opt );
        $id_order = $xml->order->id;   
        
        echo "Customer: ".$id_customer." address: ".$id_address." cart: ".$id_cart." Order: .".$id_order;
        
        
}  catch (PrestaShopWebserviceException $e) {
      
  // Here we are dealing with errors
  $trace = $e->getTrace();
  if ($trace[0]['args'][0] == 404) echo 'Bad ID';
  else if ($trace[0]['args'][0] == 401) echo 'Bad auth key';
  else echo 'Other error<br />'.$e->getMessage();
}
  • Like 3
  • Thanks 1
Link to comment
Share on other sites

  • 3 months later...

With that code all orders are created with state "Payment error", Someone knows the solution? and in table ps_orders and in prestashop i have 49 order and in table ps_order_State only have 14 rows, it is normal? Should not there be the same number of records in the two tables?

Link to comment
Share on other sites

  • 4 months later...

Why new orders are in cart section and not submitted in orders ??

I have cart id and order id but the orders are somehow not completed.

This is the output :

 

RETURN HTTP BODY
<?xml version="1.0" encoding="UTF-8"?><prestashop xmlns:xlink="http://www.w3.org/1999/xlink"><order>	<id><![CDATA[236]]></id>	<id_address_delivery xlink:href="http://elpakhsh.com/api/addresses/319"><![CDATA[319]]></id_address_delivery>	<id_address_invoice xlink:href="http://elpakhsh.com/api/addresses/319"><![CDATA[319]]></id_address_invoice>	<id_cart xlink:href="http://elpakhsh.com/api/carts/522"><![CDATA[522]]></id_cart>	<id_currency xlink:href="http://elpakhsh.com/api/currencies/1"><![CDATA[1]]></id_currency>	<id_lang xlink:href="http://elpakhsh.com/api/languages/2"><![CDATA[2]]></id_lang>	<id_customer xlink:href="http://elpakhsh.com/api/customers/272"><![CDATA[272]]></id_customer>	<id_carrier xlink:href="http://elpakhsh.com/api/carriers/82"><![CDATA[82]]></id_carrier>	<current_state xlink:href="http://elpakhsh.com/api/order_states/" notFilterable="true"></current_state>	<module><![CDATA[cashondelivery]]></module>	<invoice_number></invoice_number>	<invoice_date></invoice_date>	<delivery_number></delivery_number>	<delivery_date></delivery_date>	<valid><![CDATA[1]]></valid>	<date_add></date_add>	<date_upd></date_upd>	<shipping_number notFilterable="true"></shipping_number>	<id_shop_group></id_shop_group>	<id_shop></id_shop>	<secure_key></secure_key>	<payment><![CDATA[Mellat Payment]]></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><![CDATA[240000]]></total_paid>	<total_paid_tax_incl></total_paid_tax_incl>	<total_paid_tax_excl></total_paid_tax_excl>	<total_paid_real><![CDATA[0]]></total_paid_real>	<total_products><![CDATA[240000]]></total_products>	<total_products_wt><![CDATA[240000]]></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><![CDATA[1]]></conversion_rate>	<reference></reference>	<visitorCheck></visitorCheck><associations><order_rows nodeType="order_row" virtualEntity="true">	<order_row>	<id><![CDATA[317]]></id>	<product_id><![CDATA[10104]]></product_id>	<product_attribute_id><![CDATA[0]]></product_attribute_id>	<product_quantity><![CDATA[1]]></product_quantity>	<product_name><![CDATA[ک�سر� خ�ارک باد�جا� تبرک     15000ر�ا�*20عدد]]></product_name>	<product_reference><![CDATA[10104]]></product_reference>	<product_ean13><![CDATA[10104]]></product_ean13>	<product_upc><![CDATA[10104]]></product_upc>	<product_price><![CDATA[300000.000000]]></product_price>	<unit_price_tax_incl><![CDATA[240000.000000]]></unit_price_tax_incl>	<unit_price_tax_excl><![CDATA[240000.000000]]></unit_price_tax_excl>	</order_row></order_rows></associations></order></prestashop>

 

 

I have these ids like the following :

Customer: 272 address: 319 cart: 522 Order: .236

 

But the orders are in cart and not on orders of prestashop admin . What's wrong here ??

Thanks

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

  • 1 year later...

<?xml version="1.0" encoding="UTF-8"?>
<prestashop xmlns:xlink="http://www.w3.org/1999/xlink">
    <order>
        <id_cart>7</id_cart>
        <id_customer>12</id_customer>
        <id_address_delivery>7</id_address_delivery>
        <id_address_invoice>7</id_address_invoice>
        <id_currency>1</id_currency>
        <id_lang>1</id_lang>
        <id_carrier>2</id_carrier>
        <!--<current_state>2</current_state>-->
        <valid>1</valid>
        <payment>Payment by check</payment>
        <module>ps_checkpayment</module>
        <total_paid>1000</total_paid>
        <!--<total_paid_tax_incl>1000</total_paid_tax_incl>-->
        <!--<total_paid_tax_excl>1000</total_paid_tax_excl>-->
        <total_products>1</total_products>
        <total_paid_real>1000</total_paid_real>
        <total_products_wt>1</total_products_wt>
        <conversion_rate>1.000000</conversion_rate>
        <associations>
           <order_rows nodeType="order_row" virtualEntity="true" >
           <order_row>
           <id>10</id>
           <product_name>"Hummingbird printed t-shirt - Color : White, Size : S</product_name>
           <product_id>10</product_id>
           <product_attribute_id>39</product_attribute_id>
           <product_quantity>1</product_quantity>
           </order_row>
           </order_rows>
        </associations>
        </order>
</prestashop>

 

i am inserting this xml but status code is 500 can anyone help me plz

url : http://key/presta/api/orders?schema=blank

 

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

  • 1 year later...
  • 7 months later...

Hi,

 

for all those who are confused and having headaches with prestashop webservice and get multiple code errors, here are some tips you can use:

1. In order to create an order successfully, first you will need customer, customer address and cart, in that order, otherwise you won't succeed.

2.By obtaining /api/resource?schema=blank and  /api/resource?schema=synopsis where resource will be "customers,addresses,carts and orders", you MUST fill in all required fields marked with "required" label in schema=synopsis

3. If you do all the steps mentioned above, you will get error 500 because you can't generate an order with an empty cart with no customer or no delivery (these fields are NOT REQUIRED for cart creation, but are MANDATORY for order creation)

4. Still, if you have issues with that, take a look at my code

<?php
define('PS_SHOP_PATH', 'https://url.com');
define('PS_WS_AUTH_KEY', 'your_api_key');
require_once ('./PSWebServiceLibrary.php');

function getCart($customer, $id_delivery, $id_invoice)
{
    try
    {
        $webService = new PrestaShopWebservice(PS_SHOP_PATH, PS_WS_AUTH_KEY, DEBUG);
        $opt = array(
            'resource' => 'carts'
        );
        //We prepare the XML in blank so we can pass parameters to the variable
        $cart = $webService->get(array(
            'url' => PS_SHOP_PATH . '/api/carts?schema=blank'
        ));
        foreach ($resources as $nodeKey => $node)
        {
            $resources->$nodeKey = $_POST[$nodeKey];
        }
        // Here we have XML before update, lets update XML
        try
        {
            $opt = array(
                'resource' => 'carts'
            );
            $cart
                ->cart->id_currency = 1;
            $cart
                ->cart->id_lang = 1;
            $cart
                ->cart->id_address_delivery = $id_delivery;
            $cart
                ->cart->id_address_invoice = $id_invoice;
            $cart
                ->cart->id_customer = $customer;
            //Multidimensional array or products for test purposes. Warning: using same array line inside the main array breaks.
            $product_list = array(
                array(
                    5513,
                    43816,
                    1
                ) ,
                array(
                    5514,
                    43823,
                    1
                ) ,
                array(
                    5488,
                    43687,
                    3
                ) ,
            );
            //Insertion of the products inside the associations
            for ($i = 0;$i <= count($product_list);$i++)
            {
                $cart
                    ->cart
                    ->associations
                    ->cart_rows
                    ->cart_row[$i]->id_product = $product_list[$i][0];
                $cart
                    ->cart
                    ->associations
                    ->cart_rows
                    ->cart_row[$i]->id_product_attribute = $product_list[$i][1];
                $cart
                    ->cart
                    ->associations
                    ->cart_rows
                    ->cart_row[$i]->quantity = $product_list[$i][2];
            }
            $opt['postXml'] = $cart->asXML(); //Load XML with values
            $cart = $webService->add($opt); // Send XML to prestashop
            
        }
        catch(PrestaShopWebserviceException $ex)
        {
            // Here we are dealing with errors
            $trace = $ex->getTrace();
            if ($trace[0]['args'][0] == 404) echo 'Bad ID';
            else if ($trace[0]['args'][0] == 401) echo 'Bad auth key';
            else echo 'Other error<br />' . $ex->getMessage();
        }
    }
    catch(PrestaShopWebserviceException $e)
    {
        // Here we are dealing with errors
        $trace = $e->getTrace();
        if ($trace[0]['args'][0] == 404) echo 'Bad ID';
        else if ($trace[0]['args'][0] == 401) echo 'Bad auth key';
        else echo 'Other error<br />' . $e->getMessage();
    }
    return $cart
        ->cart->id;
}
?>

This is for cart creation used later in the main php file:

<html><head><title>Create Order Tutorial</title></head><body>
<?php
/*
 * 2007-2020 PrestaShop SA and Contributors
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to [email protected] so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
 * versions in the future. If you wish to customize PrestaShop for your
 * needs please refer to http://www.prestashop.com for more information.
 *
 *  @author PrestaShop SA <[email protected]>
 *  @copyright  2007-2020 PrestaShop SA
 *  @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 *  International Registered Trademark & Property of PrestaShop SA
 * PrestaShop Webservice Library
 * @package PrestaShopWebservice
*/

// Here we define constants /!\ You need to replace this parameters
define('DEBUG', false);
define('PS_SHOP_PATH', 'https://url.com');
define('PS_WS_AUTH_KEY', 'your_api_key');
require_once ('./PSWebServiceLibrary.php');
require_once ('./GetCart.php');

// Here we use the WebService to get the schema of "customers" resource
try
{
    $webService = new PrestaShopWebservice(PS_SHOP_PATH, PS_WS_AUTH_KEY, DEBUG);
    $opt = array(
        'resource' => 'orders'
    );
    //If I'm in creating page
    if (isset($_GET['Create']))
    {
        //We prepare the XML in blank so we can pass parameters to the variable
        $order = $webService->get(array(
            'url' => PS_SHOP_PATH . '/api/orders?schema=blank'
        ));
    }
    else
    //If not in the creating page, I retrieve the orders list
    $order = $webService->get($opt);
    //XML-> prestashop-> valor de resource que es carts
    $resources = $order->children()
        ->children();
}
catch(PrestaShopWebserviceException $e)
{
    // Here we are dealing with errors
    $trace = $e->getTrace();
    if ($trace[0]['args'][0] == 404) echo 'Bad ID';
    else if ($trace[0]['args'][0] == 401) echo 'Bad auth key';
    else echo 'Other error<br />' . $e->getMessage();
}

if (count($_POST) > 0) //If we successfully retrieved the blank schema

{
    //We get all the variables of blank schema
    foreach ($resources as $nodeKey => $node)
    {
        $resources->$nodeKey = $_POST[$nodeKey];
    }
    // Here we have XML before update, lets update XML
    try
    {
        $opt = array(
            'resource' => 'orders'
        );
        if ($_GET['Create'] == 'Creating') // If we are creating
        
        {
            //We add required fields. This fields are ALL mandatory. These values are for testing, use your own test variables/values !!!
            $order->order->id_address_delivery = 2110;//Better approach is to find delivery address of customer as variable
            $order->order->id_address_invoice = 2110;
            //We pass the details to the cart, these fields are MANDATORY!!! Otherwise you will get error 500!
            $order->order->id_cart = getCart($order->order->id_customer, $order->order->id_address_delivery, $order->order->id_address_invoice);
            $order->order->id_currency = 1;
            $order->order->id_lang = 2110;
            $order->order->id_carrier = 89;
            $order->order->module = "ps_cashondelivery";
            $order->order->payment = "Cash on delivery (COD)";
            $order->order->total_paid = 41.02;
            $order->order->total_paid_real = 41.02;
            $order->order->total_products = 5;
            $order->order->total_products_wt = 0;
            $order->order->conversion_rate = 1;

            $opt['postXml'] = $order->asXML(); //Load XML
            $order = $webService->add($opt); // Send XML
            echo "Successfully added.";
        }
    }
    catch(PrestaShopWebserviceException $ex)
    {
        // Here we are dealing with errors
        $trace = $ex->getTrace();
        if ($trace[0]['args'][0] == 404) echo 'Bad ID';
        else if ($trace[0]['args'][0] == 401) echo 'Bad auth key';
        else echo 'Other error<br />' . $ex->getMessage();
    }
}

  ///////////////////////////////////////////////////////////////
 //      This part of the code is for display purposes        // 
///////////////////////////////////////////////////////////////

echo '<table border="5">';
if (isset($resources))
{

    echo '<tr>';
    if (isset($_GET['Create'])) //Display creating page
    
    {
        echo '<h1>Creating...give me values</h1>';
        echo '<a href="?">Go back if you change your mind</a>';
        echo '<form method="POST" action="?Create=Creating">';
        echo '</tr>';
        //Getting parameters
        foreach ($resources as $key => $resource)
        {
            //This array lets you display the parameters you want to display, and enter manually like customer
            $requiredFields = array("id_customer");
            if (in_array($key, $requiredFields))
            {
                echo '<tr><th>' . $key . '</th><td>';
                echo '<input type="text" name="' . $key . '" value=""/>';
            }
            echo '</td></tr>';
        }

        echo '</table><br/>';
        echo '<input type="submit" value="Create"></form>';
    }
    else
    // Display index
    
    {
        echo '<h1>Here is a list</h1>';
        echo '<input type="button" onClick="document.location.href=\'?Create\'" value="Create whateva">';
        echo '<th>Id</th></tr>';
        foreach ($resources as $resource)
        {
            echo '<tr><td>' . $resource->attributes() . '</td></tr>';
        }
        echo '</table><br/>';
    }

}
?>
</body></html>

Everything is commented for noobs, so if you don't understand something you can always reach me and I'll try to explain.

I think this kind of stuff should be included or posted in the documentation (which is REALLY poor), if not then a better debugger of the errors would be nice.

 

Peace

Link to comment
Share on other sites

Hello,

@ChineseNorris I have created as above mentioned web service call code. Now I could create the order, but I need to create order and then post the payment process and then need to update the payment status in order status.

Can you please update the code to do payment using web services.

And also please update which will be better method, whether order need to create after payment success or Order creation after that payment and then update the payment status for order.

 

1.Create Cart -> Submit cart to Order -> Payment gateway -> Update payment status to order

Else 

1.Create Cart -> Payment gateway -> After that create order 

 

Which one will be good for Ecom application? And which is better to do via web services in Prestashop API?

 

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

3 hours ago, rvkvino said:

Hello,

@ChineseNorris I have created as above mentioned web service call code. Now I could create the order, but I need to create order and then post the payment process and then need to update the payment status in order status.

Can you please update the code to do payment using web services.

And also please update which will be better method, whether order need to create after payment success or Order creation after that payment and then update the payment status for order.

 

1.Create Cart -> Submit cart to Order -> Payment gateway -> Update payment status to order

Else 

1.Create Cart -> Payment gateway -> After that create order 

 

Which one will be good for Ecom application? And which is better to do via web services in Prestashop API?

 

Hi,

 

I would suggest you to create the order if it's not paid so you can track your customer for payment, but not everyone will be happy with that approach, it depends on what kind of business you are in. For the status update I'm not in that part yet, if I succeed I'll post a solution.

 

Peace

Link to comment
Share on other sites

  • 5 months later...
On 8/9/2020 at 6:36 PM, ChineseNorris said:

Hi,

 

for all those who are confused and having headaches with prestashop webservice and get multiple code errors, here are some tips you can use:

1. In order to create an order successfully, first you will need customer, customer address and cart, in that order, otherwise you won't succeed.

2.By obtaining /api/resource?schema=blank and  /api/resource?schema=synopsis where resource will be "customers,addresses,carts and orders", you MUST fill in all required fields marked with "required" label in schema=synopsis

3. If you do all the steps mentioned above, you will get error 500 because you can't generate an order with an empty cart with no customer or no delivery (these fields are NOT REQUIRED for cart creation, but are MANDATORY for order creation)

4. Still, if you have issues with that, take a look at my code


<?php
define('PS_SHOP_PATH', 'https://url.com');
define('PS_WS_AUTH_KEY', 'your_api_key');
require_once ('./PSWebServiceLibrary.php');

function getCart($customer, $id_delivery, $id_invoice)
{
    try
    {
        $webService = new PrestaShopWebservice(PS_SHOP_PATH, PS_WS_AUTH_KEY, DEBUG);
        $opt = array(
            'resource' => 'carts'
        );
        //We prepare the XML in blank so we can pass parameters to the variable
        $cart = $webService->get(array(
            'url' => PS_SHOP_PATH . '/api/carts?schema=blank'
        ));
        foreach ($resources as $nodeKey => $node)
        {
            $resources->$nodeKey = $_POST[$nodeKey];
        }
        // Here we have XML before update, lets update XML
        try
        {
            $opt = array(
                'resource' => 'carts'
            );
            $cart
                ->cart->id_currency = 1;
            $cart
                ->cart->id_lang = 1;
            $cart
                ->cart->id_address_delivery = $id_delivery;
            $cart
                ->cart->id_address_invoice = $id_invoice;
            $cart
                ->cart->id_customer = $customer;
            //Multidimensional array or products for test purposes. Warning: using same array line inside the main array breaks.
            $product_list = array(
                array(
                    5513,
                    43816,
                    1
                ) ,
                array(
                    5514,
                    43823,
                    1
                ) ,
                array(
                    5488,
                    43687,
                    3
                ) ,
            );
            //Insertion of the products inside the associations
            for ($i = 0;$i <= count($product_list);$i++)
            {
                $cart
                    ->cart
                    ->associations
                    ->cart_rows
                    ->cart_row[$i]->id_product = $product_list[$i][0];
                $cart
                    ->cart
                    ->associations
                    ->cart_rows
                    ->cart_row[$i]->id_product_attribute = $product_list[$i][1];
                $cart
                    ->cart
                    ->associations
                    ->cart_rows
                    ->cart_row[$i]->quantity = $product_list[$i][2];
            }
            $opt['postXml'] = $cart->asXML(); //Load XML with values
            $cart = $webService->add($opt); // Send XML to prestashop
            
        }
        catch(PrestaShopWebserviceException $ex)
        {
            // Here we are dealing with errors
            $trace = $ex->getTrace();
            if ($trace[0]['args'][0] == 404) echo 'Bad ID';
            else if ($trace[0]['args'][0] == 401) echo 'Bad auth key';
            else echo 'Other error<br />' . $ex->getMessage();
        }
    }
    catch(PrestaShopWebserviceException $e)
    {
        // Here we are dealing with errors
        $trace = $e->getTrace();
        if ($trace[0]['args'][0] == 404) echo 'Bad ID';
        else if ($trace[0]['args'][0] == 401) echo 'Bad auth key';
        else echo 'Other error<br />' . $e->getMessage();
    }
    return $cart
        ->cart->id;
}
?>

This is for cart creation used later in the main php file:


<html><head><title>Create Order Tutorial</title></head><body>
<?php
/*
 * 2007-2020 PrestaShop SA and Contributors
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to [email protected] so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
 * versions in the future. If you wish to customize PrestaShop for your
 * needs please refer to http://www.prestashop.com for more information.
 *
 *  @author PrestaShop SA <[email protected]>
 *  @copyright  2007-2020 PrestaShop SA
 *  @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 *  International Registered Trademark & Property of PrestaShop SA
 * PrestaShop Webservice Library
 * @package PrestaShopWebservice
*/

// Here we define constants /!\ You need to replace this parameters
define('DEBUG', false);
define('PS_SHOP_PATH', 'https://url.com');
define('PS_WS_AUTH_KEY', 'your_api_key');
require_once ('./PSWebServiceLibrary.php');
require_once ('./GetCart.php');

// Here we use the WebService to get the schema of "customers" resource
try
{
    $webService = new PrestaShopWebservice(PS_SHOP_PATH, PS_WS_AUTH_KEY, DEBUG);
    $opt = array(
        'resource' => 'orders'
    );
    //If I'm in creating page
    if (isset($_GET['Create']))
    {
        //We prepare the XML in blank so we can pass parameters to the variable
        $order = $webService->get(array(
            'url' => PS_SHOP_PATH . '/api/orders?schema=blank'
        ));
    }
    else
    //If not in the creating page, I retrieve the orders list
    $order = $webService->get($opt);
    //XML-> prestashop-> valor de resource que es carts
    $resources = $order->children()
        ->children();
}
catch(PrestaShopWebserviceException $e)
{
    // Here we are dealing with errors
    $trace = $e->getTrace();
    if ($trace[0]['args'][0] == 404) echo 'Bad ID';
    else if ($trace[0]['args'][0] == 401) echo 'Bad auth key';
    else echo 'Other error<br />' . $e->getMessage();
}

if (count($_POST) > 0) //If we successfully retrieved the blank schema

{
    //We get all the variables of blank schema
    foreach ($resources as $nodeKey => $node)
    {
        $resources->$nodeKey = $_POST[$nodeKey];
    }
    // Here we have XML before update, lets update XML
    try
    {
        $opt = array(
            'resource' => 'orders'
        );
        if ($_GET['Create'] == 'Creating') // If we are creating
        
        {
            //We add required fields. This fields are ALL mandatory. These values are for testing, use your own test variables/values !!!
            $order->order->id_address_delivery = 2110;//Better approach is to find delivery address of customer as variable
            $order->order->id_address_invoice = 2110;
            //We pass the details to the cart, these fields are MANDATORY!!! Otherwise you will get error 500!
            $order->order->id_cart = getCart($order->order->id_customer, $order->order->id_address_delivery, $order->order->id_address_invoice);
            $order->order->id_currency = 1;
            $order->order->id_lang = 2110;
            $order->order->id_carrier = 89;
            $order->order->module = "ps_cashondelivery";
            $order->order->payment = "Cash on delivery (COD)";
            $order->order->total_paid = 41.02;
            $order->order->total_paid_real = 41.02;
            $order->order->total_products = 5;
            $order->order->total_products_wt = 0;
            $order->order->conversion_rate = 1;

            $opt['postXml'] = $order->asXML(); //Load XML
            $order = $webService->add($opt); // Send XML
            echo "Successfully added.";
        }
    }
    catch(PrestaShopWebserviceException $ex)
    {
        // Here we are dealing with errors
        $trace = $ex->getTrace();
        if ($trace[0]['args'][0] == 404) echo 'Bad ID';
        else if ($trace[0]['args'][0] == 401) echo 'Bad auth key';
        else echo 'Other error<br />' . $ex->getMessage();
    }
}

  ///////////////////////////////////////////////////////////////
 //      This part of the code is for display purposes        // 
///////////////////////////////////////////////////////////////

echo '<table border="5">';
if (isset($resources))
{

    echo '<tr>';
    if (isset($_GET['Create'])) //Display creating page
    
    {
        echo '<h1>Creating...give me values</h1>';
        echo '<a href="?">Go back if you change your mind</a>';
        echo '<form method="POST" action="?Create=Creating">';
        echo '</tr>';
        //Getting parameters
        foreach ($resources as $key => $resource)
        {
            //This array lets you display the parameters you want to display, and enter manually like customer
            $requiredFields = array("id_customer");
            if (in_array($key, $requiredFields))
            {
                echo '<tr><th>' . $key . '</th><td>';
                echo '<input type="text" name="' . $key . '" value=""/>';
            }
            echo '</td></tr>';
        }

        echo '</table><br/>';
        echo '<input type="submit" value="Create"></form>';
    }
    else
    // Display index
    
    {
        echo '<h1>Here is a list</h1>';
        echo '<input type="button" onClick="document.location.href=\'?Create\'" value="Create whateva">';
        echo '<th>Id</th></tr>';
        foreach ($resources as $resource)
        {
            echo '<tr><td>' . $resource->attributes() . '</td></tr>';
        }
        echo '</table><br/>';
    }

}
?>
</body></html>

Everything is commented for noobs, so if you don't understand something you can always reach me and I'll try to explain.

I think this kind of stuff should be included or posted in the documentation (which is REALLY poor), if not then a better debugger of the errors would be nice.

 

Peace

Hello everybody :).

I followed your steps to create a order, the cart and the order are created, but i'm still getting the 500 error.

Can you please help me with a solution for this issue?

Here is the code, I didn't used separate functions for cart and order.

// Create cart
$blankCartXml = $webService->get(array('url' => 'https://test.local/api/carts?schema=blank'));

$cartFields = $blankCartXml->cart->children();

$cartFields->id_currency = 1;
$cartFields->id_lang = 1;
$cartFields->id_address_delivery = 69393;
$cartFields->id_address_invoice = 69393;
$cartFields->id_customer = 41740;

$cartFields->id_shop = 1;
$cartFields->id_carrier = 222;
$cartFields->date_add = date("Y-j-m");
$cartFields->associations->cart_rows->cart_row->id_product = 12;
$cartFields->associations->cart_rows->cart_row->quantity = 1;

$createdCartXml = $webService->add([
    'resource' => 'carts',
    'postXml' => $blankCartXml->asXML(),
]);


// Create order
$blankOrdersXml = $webService->get(array('url' => 'https://test.local/api/orders?schema=blank'));

$orderFields = $blankOrdersXml->order->children();

$orderFields->id_address_delivery = 69393;
$orderFields->id_address_invoice = 69393;

$orderFields->id_cart = $createdCartXml->cart->id;
$orderFields->id_currency = 1;
$orderFields->id_lang = 1;
$orderFields->id_shop = 1;
$orderFields->id_carrier = 222;

$orderFields->id_customer = 41740;
$orderFields->payment = 'Cash on delivery (COD)';
$orderFields->module = 'cashondelivery';
$orderFields->total_paid = 535;
$orderFields->total_paid_real = 0;
$orderFields->total_products = 1;
$orderFields->conversion_rate = 1;
$orderFields->total_products_wt = 0;

$orderFields->associations->order_rows->order_row->id_product = 12;
$orderFields->associations->order_rows->order_row->quantity = 1;


$createdOrderXml = $webService->add([
    'resource' => 'orders',
    'postXml' => $blankOrdersXml->asXML(),
]);

Thank you all!

Link to comment
Share on other sites

  • 8 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...