PrestaShop: Can't create order with web service - php

I'm trying to create an order using the web service on another web page i have. I'm running the latest version of PrestaShop 1.7. It's really basic, just entering ID of product and quantity. This is my first serious task and i'm struggling to make this work, which it still doesn't. The code i will soon show can create a cart, but it can not create the order for some reason.
Code:
try {
/*
Creating new cart
*/
$xml = $webService->get( array( 'url' => PS_SHOP_PATH .'/api/carts?schema=blank' ) );
// Required
$xml->cart->id_currency = 1;
$xml->cart->id_lang = 1;
foreach($_SESSION['vezimas'] as $i => $vezimas) {
$xml->cart->associations->cart_rows->cart_row[$i]->id_product = $vezimas['product_id'];
$xml->cart->associations->cart_rows->cart_row[$i]->quantity = $vezimas['qty'];
}
// Adding the new cart
$opt = array( 'resource' => 'carts' );
$opt['postXml'] = $xml->asXML();
$xml = $webService->add( $opt );
$id_cart = $xml->cart->id;
/*
Creating Order
*/
// Getting the structure of an order
$xml = $webService->get(array('url' => PS_SHOP_PATH .'/api/orders/?schema=blank'));
// Required
$xml->order->id_address_delivery = 6; // Customer address
$xml->order->id_address_invoice = 6;
$xml->order->id_cart = $id_cart;
$xml->order->id_currency = 1;
$xml->order->id_lang = 1;
$xml->order->id_customer = 2;
$xml->order->id_carrier = 1;
$xml->order->module = 'ps_checkpayment';
$xml->order->payment = 'Payments by check';
$xml->order->total_paid = 0;
$xml->order->total_paid_real = 0;
$xml->order->total_products = $_SESSION['prekesNum'];
$xml->order->total_products_wt = 0;
$xml->order->conversion_rate = 1;
// Others
$xml->order->valid = 1;
// Order Row. Required
foreach($_SESSION['vezimas'] as $i => $vezimas) {
$xml->order->associations->order_rows->order_row[0]->product_id = $vezimas['product_id'];
$xml->order->associations->order_rows->order_row[0]->product_quantity = $vezimas['qty'];
}
// Creating the order
$opt = array( 'resource' => 'orders' );
$opt['postXml'] = $xml->asXML();
$xml = $webService->add( $opt );
$id_order = $xml->order->id;
} 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();
}
I get a fatal error in Debug, and this on the page:
Other error
HTTP XML response is not parsable: array ( 0 => LibXMLError::__set_state(array( 'level' => 3, 'code' => 4, 'column' => 1, 'message' => 'Start tag expected, \'<\' not found ', 'file' => '', 'line' => 1, )), )

Added some more field and a secure key to my cart code then it worked fine.

Related

Loop return one result in conditioner query

I am trying to fetch data from database in code-igniter .Bur this loop return only one loop .
$userchatData = $this->db->get($this->db->dbprefix('usres_chat'))->result_array();
foreach($userchatData as $key => $userdata)
{
$userdatas[]= array(
'chat_id' => $userdata['chat_id'],
'chat_from' => $userdata['chat_from'],
'created_date' => $userdata['created_date']
);
}
$data['ChatdatabyId'] = $userdatas;
$data['responseCode'] = '200';
$data['responseMessage'] = 'User listing successfully';
echo json_encode($data);
You need to define $userdatas=array(); outside the loop. It is inside the loop that's why it overrides the data and returns the last record.
$userchatData = $this->db->get($this->db->dbprefix('usres_chat'))->result_array();
$userdatas = array();
foreach($userchatData as $key => $userdata){
$userdatas[]= array(
'chat_id' => $userdata['chat_id'],
'chat_from' => $userdata['chat_from'],
'created_date' => $userdata['created_date']
);
}
$data['ChatdatabyId'] =$userdatas;
$data['responseCode'] = '200';
$data['responseMessage'] = 'User listing successfully';
echo json_encode($data);
Hope this will help you :
$userchatData = $this->db->get($this->db->dbprefix('usres_chat'))->result_array();
foreach($userchatData as $key => $userdata)
{
$userdatas[$key]['chat_id'] = $userdata['chat_id'];
$userdatas[$key]['chat_from'] = $userdata['chat_from'];
$userdatas[$key]['created_date'] = $userdata['created_date'];
}
/*print_r($userdatas); output here*/
$data['ChatdatabyId'] = $userdatas;
$data['responseCode'] = '200';
$data['responseMessage'] = 'User listing successfully';
}
echo json_encode($data);

504 Gateway time out php

i'm running script(svc/rest services) that request a server which response me a XML string.. this request is going through an intermediate server.
My aim is to fetch the details of guests o.e. rooms which will be response..
but after certain number of request i am getting 504 gateway out and only about 40 rooms are able to retreived
1: file...source hots
$ROOMS = ["301","302","304","305","306","307","308","309","310",
"311","312","314","315","316","317","318","319","320",
"401","402","403","404","405","406","407","408","409",
"410","411","412","414","415","416","802","802","802",
"802","802","802","802","802","802","802","802","802",
"802","802","802","802","802","802","802","802","802",
"802","802","802","802","802","802","802","802"
];
// all rooms more than 75
for ($x = 0; $x < count($ROOMS); $x++){
$end_point = "https://www.innkeyapp.com/SerRest.svc/GetOccupiedRoomData";
$sharedkey = "2diSq8bjZ4N3ZR4XB5KXXXXXXXXXXXXXXXXXXXXXXX";
$url = 'https://eastern-services.com/innkeyPMS_room_ststus.php';
$room_no = $ROOMS[$x];
$postdata = http_build_query([
'end_point' => $end_point,
'room_no' => $room_no,
'sharedkey' => $sharedkey
]);
$opts = [
'http' => [
'method' => 'POST',
'content' => $postdata
]
];
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
$arrayData = json_decode($result,true);
if (empty($arrayData)) {
// Redirect('failure.php?msg=Error in service');
echo "Error in Service";
exit();
}
print_r($arrayData);
echo $room_no."Added";
}
2: file.... innkeyPMS_room_ststus.php i.e. intermediate host.
$room_no = $post_var['room_no'];
$end_point = $post_var['end_point'];
$sharedkey = $post_var['sharedkey'];
$registerno = '';
$prprtxt = '';
$validunit = '';
// echo $post_var;
function curl_get_file_contents($URL)
{
return file_get_contents($URL);
}
$xmlString = curl_get_file_contents(
$end_point.'sharedkey='.$sharedkey.'=&roomno='.$room_no
);
$xml = simplexml_load_string($xmlString);
header("Content-Type: application/json");
echo json_encode($xml);
why this connection is getting lost or why its showing 504 gateway time out?

How to update order status in OpenCart

I'm currently building an OpenCart payment extension for a new payment gateway. Right now, I can successfully make payments and redirect back to the merchant site but I don't know how to write the code so that it updates the order status as well.
All my order are now showing under missing orders and I feel it's because of that. I don't have a callback function and I don't know how to go about it. I want to update the code so that it can update my order status as completed if payment is successful or redirect back to checkout if payment fails but still updates the order status.
This is my code below:
<?php
class ControllerExtensionPaymentSCPAY extends Controller {
public function index() {
$this->load->language('extension/payment/sc_pay');
$data['button_confirm'] = $this->language->get('button_confirm');
$data['testmode'] = $this->config->get('sc_pay_test');
$order_info = $this->model_checkout_order->getOrder($this->session->data['order_id']);
$total = $order_info['total'];
$newbutton = str_replace("50", $total, $this->config->get('sc_pay_button_link'));
$newbutton = $newbutton . "&redirect_url=" .$this->url->link('checkout/success');
if (!$this->config->get('sc_pay_test')) {
$data['action'] = $newbutton;
}
else {
$data['action'] = '';
}
$this->load->model('checkout/order');
$order_info = $this->model_checkout_order->getOrder($this->session->data['order_id']);
if ($order_info) {
$data['business'] = $this->config->get('sc_pay_email');
$data['item_name'] = html_entity_decode($this->config->get('config_name'), ENT_QUOTES, 'UTF-8');
$data['products'] = array();
foreach ($this->cart->getProducts() as $product) {
$option_data = array();
foreach ($product['option'] as $option) {
if ($option['type'] != 'file') {
$value = $option['value'];
}
else {
$upload_info = $this->model_tool_upload->getUploadByCode($option['value']);
if ($upload_info) {
$value = $upload_info['name'];
}
else {
$value = '';
}
}
$option_data[] = array(
'name' => $option['name'],
'value' => (utf8_strlen($value) > 20 ? utf8_substr($value, 0, 20) . '..' : $value)
);
}
$data['products'][] = array(
'name' => htmlspecialchars($product['name']),
'model' => htmlspecialchars($product['model']),
'price' => $this->currency->format($product['price'], $order_info['currency_code'], false, false),
'quantity' => $product['quantity'],
'option' => $option_data,
'weight' => $product['weight']
);
}
$data['discount_amount_cart'] = 0;
$total = $this->currency->format($order_info['total'] - $this->cart->getSubTotal(), $order_info['currency_code'], false, false);
if ($total > 0) {
$data['products'][] = array(
'name' => $this->language->get('text_total'),
'model' => '',
'price' => $total,
'quantity' => 1,
'option' => array(),
'weight' => 0
);
}
else {
$data['discount_amount_cart'] -= $total;
}
$data['currency_code'] = $order_info['currency_code'];
$data['first_name'] = html_entity_decode($order_info['payment_firstname'], ENT_QUOTES, 'UTF-8');
$data['last_name'] = html_entity_decode($order_info['payment_lastname'], ENT_QUOTES, 'UTF-8');
$data['address1'] = html_entity_decode($order_info['payment_address_1'], ENT_QUOTES, 'UTF-8');
$data['address2'] = html_entity_decode($order_info['payment_address_2'], ENT_QUOTES, 'UTF-8');
$data['city'] = html_entity_decode($order_info['payment_city'], ENT_QUOTES, 'UTF-8');
$data['zip'] = html_entity_decode($order_info['payment_postcode'], ENT_QUOTES, 'UTF-8');
$data['country'] = $order_info['payment_iso_code_2'];
$data['email'] = $order_info['email'];
$data['invoice'] = $this->session->data['order_id'] . ' - ' . html_entity_decode($order_info['payment_firstname'], ENT_QUOTES, 'UTF-8') . ' ' . html_entity_decode($order_info['payment_lastname'], ENT_QUOTES, 'UTF-8');
$data['lc'] = $this->session->data['language'];
$data['return'] = $this->url->link('checkout/success');
$data['notify_url'] = $this->url->link('extension/payment/sc_pay/callback', '', true);
$data['cancel_return'] = $this->url->link('checkout/checkout', '', true);
$data['custom'] = $this->session->data['order_id'];
return $this->load->view('extension/payment/sc_pay', $data);
}
}
enter code here
I am assuming from your controller file that you are using 2.3.0.2 version of opencart.
//some validation here
$this->model_checkout_order->addOrderHistory($order_id, $order_status_id,print_r($callback,true),true,false);
// if order id is not 0, it will update order status to whatever you defined in admin / payment settings (integer). if 0, it will add new order

Insert Custom Options of product with script

I have a script for inserting a product custom options in Magento. Its working fine for single custom option, if there are multiple custom options for a single product then it insert only single custom option and discard others.
<?php
// Report all PHP errors (see changelog)
error_reporting(E_ALL);
ini_set("display_errors", 1);
// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);
// Include Magento application
require_once ( "../app/Mage.php" );
umask(0);
// Initialize Magento
Mage::app("default");
$start = 0;
$totalno =1000;
$row = 0;
$sku = 0;
$baseRowoption = array();
$myarrayoption = array();
if (($handle = fopen("custom_option-final.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle,",")) !== FALSE) {
$num = count($data);
for ($c=0; $c < $num; $c++) {
if($row == 0){
$baseRowoption[$c]=$data[$c];
}else{
if($c==0){
$sku=$data[$c];
}
$myarrayoption[$sku][$row][$baseRowoption[$c]]=$data[$c];
}
}
$row++;
if($row > $totalno){
break;
}
}
fclose($handle);
}
$myarrayoptionfinal = array();
foreach($myarrayoption as $key=>$myarrayoption1){
//if($key != "smartek-rx3044"){ break; }
foreach($myarrayoption1 as $myarrayoption11){
$myarrayoptionfinal[$key][$myarrayoption11['option_title']]['input_type'] = $myarrayoption11['input_type'];
$myarrayoptionfinal[$key][$myarrayoption11['option_title']]['required'] = $myarrayoption11['required'];
$myarrayoptionfinal[$key][$myarrayoption11['option_title']]['sort_order'] = $myarrayoption11['sort_order'];
$myarrayoptionfinal[$key][$myarrayoption11['option_title']]['row_title'][] = $myarrayoption11['row_title'];
$myarrayoptionfinal[$key][$myarrayoption11['option_title']]['row_price'][] = $myarrayoption11['row_price'];
$myarrayoptionfinal[$key][$myarrayoption11['option_title']]['row_price_type'][] = $myarrayoption11['row_price_type'];
$myarrayoptionfinal[$key][$myarrayoption11['option_title']]['row_sku'][] = $myarrayoption11['row_sku'];
$myarrayoptionfinal[$key][$myarrayoption11['option_title']]['row_sort_order'][] = $myarrayoption11['row_sort_order'];
}
}
echo "<pre>";
echo "total No : ".count($myarrayoptionfinal);
echo "<br />";
//print_r($myarrayoptionfinal);
$i=0;
foreach($myarrayoptionfinal as $keys=>$myarrayoptionfinal1){
if($i<$start){
$i++; continue;
}
echo "<br />".$i."--->";
$i++;
echo $keys."--->";
$product = Mage::getModel('catalog/product')->loadByAttribute('sku',$keys);
if($product){
foreach ($product->getProductOptionsCollection() as $option)
{
$optionsData = $option->getData();
$optionsData['is_delete'] = 1;
$product->setProductOptions(array($option->getId() => $optionsData));
$product->setCanSaveCustomOptions(true);
$product->save();
}}else{
continue;
}
$product = Mage::getModel('catalog/product')->loadByAttribute('sku',$keys);
print_r($product->getData("entity_id"));
foreach($myarrayoptionfinal1 as $keysub=>$myarrayoptionfinal11){
$subarray = array();
foreach($myarrayoptionfinal11['row_title'] as $keysub1=>$myarrayoptionfinal111){
$subarray[]=array(
'is_delete' => 0,
'title' => $myarrayoptionfinal111,
'price_type' => $myarrayoptionfinal11['row_price_type'][$keysub1],
'price' => $myarrayoptionfinal11['row_price'][$keysub1],
'sku' => $keys.'_'.$myarrayoptionfinal11['row_sku'][$keysub1],
'sort_order' => $myarrayoptionfinal11['row_sort_order'][$keysub1],
'option_type_id'=> -1,
);
}
$required = false;
if($myarrayoptionfinal11["required"] == 1) $required = true;
$opt = array(
'is_delete' => 0,
'is_require' => $required,
'previous_group' => '',
'title' => $keysub,
'type' => $myarrayoptionfinal11["input_type"],
'price_type' => '',
'price' => '',
'sort_order' => $myarrayoptionfinal11["sort_order"],
/** array of values for this option **/
'values' => $subarray,
);
}
try {
//print_r($opt);
$option = Mage::getModel('catalog/product_option')
->setProduct($product)
->addOption($opt)
->saveOptions();
$product->setHasOptions(1);
$product->save();
}
catch (Exception $e) {
echo 'Caught exception 2: '.$e->getMessage()."\n";
continue;
}
}
Add custom option to multiple products is quite difficult because there are multiple type custom option in magento like (dropdown, text etc.) also you will found in each custom option multiple values which you need to handle.
http://www.magentocommerce.com/magento-connect/custom-option-manger.html
This extension provides exact functionality multiple custom options for multiple products.

Prestashop webservice create order

I'm trying to create API connection to prestashop via webservices
I can create Custommers, Addresses, Carts succesfully
(there is available well known pure documentation about customers CRUD,
it works as expected)
I'm not able to complete new Order:
There is source code fragment
require_once('config.php'); // PS_SHOP_PATH etc.
require_once('PSWebServiceLibrary.php');
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'));
$xml->children()->children()->id_address_delivery = 1;
$xml->children()->children()->id_address_invoice = 1;
$xml->children()->children()->id_cart = 25;
$xml->children()->children()->id_currency = 1;
$xml->children()->children()->current_state = 1;
$xml->children()->children()->id_lang = 1;
$xml->children()->children()->id_customer = 1;
$xml->children()->children()->id_carrier = 0;
$xml->children()->children()->total_paid = '56973';
$xml->children()->children()->total_paid_real = '56973';
$xml->children()->children()->total_paid_tax_excl = '56973';
$xml->children()->children()->total_paid_tax_incl = '56977';
$xml->children()->children()->total_products = 1338;
$xml->children()->children()->total_products_wt = 1337;
$xml->children()->children()->conversion_rate = '1';
$xml->children()->children()->secure_key = md5('-1');;
$xml->children()->children()->valid = 1;
$xml->children()->children()->module = 'Bankwire';
$xml->children()->children()->payment = 'bankwire';
$xml->children()->children()->current_state = 1;
unset($xml->children()->children()->id);
unset($xml->children()->children()->date_add);
unset($xml->children()->children()->date_upd);
unset($xml->children()->children()->associations);
unset($xml->children()->children()->delivery_date);
unset($xml->children()->children()->invoice_date);
unset($xml->children()->children()->total_discounts_tax_incl);
unset($xml->children()->children()->total_discounts_tax_excl);
$xml = $webService->add(array('resource' => 'orders',
'postXml' => $xml->asXML()
));
$resources = $xml->children()->children();
echo "Successfully added order.".$resources->id;
}
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();
}
And there is part. webview log from Fiddler
XML SENT
xml=<?xml version="1.0" encoding="UTF-8"?>
<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>25</id_cart>
<id_currency>1</id_currency>
<id_lang>1</id_lang>
<id_customer>1</id_customer>
<id_carrier>0</id_carrier>
<current_state>1</current_state>
<module>Bankwire</module>
<invoice_number/>
<delivery_number/>
<valid>1</valid>
<id_shop_group/>
<id_shop/>
<secure_key>6bb61e3b7bce0931da574d19d1d82c88</secure_key>
<payment>bankwire</payment>
<recyclable/>
<gift/>
<gift_message/>
<mobile_theme/>
<total_discounts/>
<total_paid>56973</total_paid>
<total_paid_tax_incl>56977</total_paid_tax_incl>
<total_paid_tax_excl>56973</total_paid_tax_excl>
<total_paid_real>56973</total_paid_real>
<total_products>1338</total_products>
<total_products_wt>1337</total_products_wt>
<total_shipping/>
<total_shipping_tax_incl/>
<total_shipping_tax_excl/>
<carrier_tax_rate/>
<total_wrapping/>
<total_wrapping_tax_incl/>
<total_wrapping_tax_excl/>
<shipping_number/>
<conversion_rate>1</conversion_rate>
<reference/>
</order>
</prestashop>
RETURN HTTP BODY
Fatal error
Other error
HTTP XML response is not parsable : array ( 0 => LibXMLError::__set_state(array( 'level' => 3, 'code' => 4, 'column' => 1, 'message' => 'Start tag expected, \'<\' not found ', 'file' => '', 'line' => 1, )), )
"Other error" comes from this:
else echo 'Other error<br />'.$ex->getMessage();
PSWebServiceLibrary contains
/** #var array compatible versions of PrestaShop Webservice */
const psCompatibleVersionsMin = '1.4.0.17';
const psCompatibleVersionsMax = '1.5.4.1';
PrestaShop is 1.5.4.0
Any advice?
Problem solved.
1) create Customer (opt.)
2) create Address (opt.)
3) check Products availibility (this is really better...)
4) create Cart with order_rows and with product id's and quantities
5) create Order with this
in all cases required tags should by filled- see /api/object?schema=synopsis
Simply cart should not be empty before create order, its sounds logic
in step by step intearctive process and the same sequence should
be done in "batch" processing via webservices.
For placing order through webservice you need to make some entries directly to db with respect to cart like delivery option in cart table and for discount add entries in ps_cart_cart_rule table then place and order as you were placing.
1. add cart;
2. add discount options with respect to cart.
3. add delivery option with respect to cart.
4. Place order With same cart id.
Code as followed:
foreach ($raw_data['discounts'] as $discount) {
foreach ($raw_data['discounts'] as $discount) {
$sql = "insert into ps_cart_cart_rule values('" . $id['cart'] . "','" . $discount['id_cart_rule'] . "')";
$r = mysql_query($sql, $conn)or die(mysql_error($conn));
}
$sql = "update ps_cart set `delivery_option`='a:1:{i:" . $id['address'] . ";s:3:\"" . $id['carrier'] . ",\";}', `id_carrier`='" . $id['carrier'] . "' where id_cart='" . $id['cart'] . "'";
$r = mysql_query($sql, $conn)or die(mysql_error($conn));
$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->current_state = "3";
$xml->order->valid = 0;
$xml->order->total_shipping = $raw_data['total_shipping'];
$xml->order->total_shipping_tax_incl = $raw_data['total_shipping'];
$xml->order->total_shipping_tax_excl = $raw_data['total_shipping'];
$xml->order->total_discounts = $raw_data['total_discounts'];
$xml->order->total_discounts_tax_incl = $raw_data['total_discounts'];
$xml->order->total_discounts_tax_excl = $raw_data['total_discounts'];
$xml->order->payment = 'Cash on delivery';
$xml->order->module = 'cashondelivery';
$xml->order->total_products = $raw_data['total_products'];
$xml->order->total_products_wt = $raw_data['total_products'];
$xml->order->total_paid = $raw_data['total_paid'];
$xml->order->total_paid_tax_incl = $raw_data['total_paid'];
$xml->order->total_paid_tax_excl = $raw_data['total_paid'];
$xml->order->total_paid_real = "0";
$xml->order->conversion_rate = '1';
$opt = array('resource' => 'orders');
$opt['postXml'] = $xml->asXML();
$xml = $webService->add($opt);
$id['order'] = $xml->order->id;
$id['secure_key'] = $xml->order->secure_key;
Following error is because of missing required value in Cart or Order
HTTP XML response is not parsable : array ( 0 => LibXMLError::__set_state(array( 'level' => 3, 'code' => 4, 'column' => 1, 'message' => 'Start tag expected, \'<\' not found ', 'file' => '', 'line' => 1, )), )
In my case id_address_delivery & id_address_invoice where missing in Cart, that's why i was facing this error.
Read more at PrestaShop web service create order errors
If you are getting this Start tag expected, \'<\' not found ', error try to check response which your sending to parse.
This is showing due to improper data that you sending in order or due to xml validation problem.
I also gone through same problem and I solved it by checking what response I am sending to parse method in Prestashop library.
define('DEBUG', true);
define('PS_SHOP_PATH', 'http://.....');
define('PS_WS_AUTH_KEY', '...');
define('FILE_NAME', 'file.xlsx');
require_once('./PSWebServiceLibrary.php');
ini_set('error_reporting', E_ALL);
ini_set('display_errors', true);
require_once __DIR__.'/src/SimpleXLSX.php';
$newArray = array(); // here we will accumulate grouped data
$dataArray=[];
$product_count=0;
if ( $xlsx = SimpleXLSX::parse(FILE_NAME) ) {
for($i=1; $i < count($xlsx->rows()); $i++){
$id=$xlsx->rows()[$i][0];
$product_id=$xlsx->rows()[$i][96];
if($product_id)
{
if(!isset($dataArray[$id]))
{
$dataArray[$id]["products"][$product_id]= $xlsx->rows()[$i][103];
$dataArray[$id]["price"]=$xlsx->rows()[$i][38];
$dataArray[$id]["product_weight"]=$xlsx->rows()[$i][24];
$dataArray[$id]["id_address_delivery"]=$xlsx->rows()[$i][170];
$dataArray[$id]["id_carrier"]=$xlsx->rows()[$i][172];
$dataArray[$id]["payment_mode"]=$xlsx->rows()[$i][173];
$dataArray[$id]["product_count"]=$product_count;
$dataArray[$id]["currency_code"] = $xlsx->rows()[$i][17];
}
else
{
if(!isset($dataArray[$id]["products"][$product_id]))
{
$dataArray[$id]["products"][$product_id]+= $xlsx->rows()[$i][103];
}
else
{
$dataArray[$id]["products"][$product_id]+= $xlsx->rows()[$i][103];
}
}
}
}
} else {
echo SimpleXLSX::parseError();
}
try{
foreach($dataArray as $key => $value){
$webService = new PrestaShopWebservice(PS_SHOP_PATH, PS_WS_AUTH_KEY, DEBUG);
$xml = $webService->get(array('url' => PS_SHOP_PATH.'/api/carts?schema=blank'));
$xml_currency = $webService->get(array('url' => PS_SHOP_PATH.'/api/currencies/?display=full'));
$xml_language = $webService->get(array('url' => PS_SHOP_PATH.'/api/languages?display=full'));
$value['id_language'] = (int)$xml_language->languages->language->id;
$xml->cart->id_customer = $key;
$count = 0;
$value['total_products'] = 0;
foreach($value['products'] as $product_key => $product_value){
$xml->cart->associations->cart_rows->cart_row[$count]->id_product = $product_key;
$xml->cart->associations->cart_rows->cart_row[$count]->quantity = $product_value;
$value['total_products']+= $product_value;
$count++;
}
for($i=0; $i<count($xml_currency->currencies->currency);$i++){
if($xml_currency->currencies->currency[$i]->iso_code == $value['currency_code'])
$value['id_currency'] =(int) $xml_currency->currencies->currency[$i]->id;
}
$xml->cart->id_address_delivery = $value['id_address_delivery'];
$xml->cart->id_address_invoice = $value['id_address_delivery'];
$xml->cart->id_currency = $value['id_currency'];
$xml->cart->id_lang = $value['id_language'];
$xml->cart->id_carrier = $value['id_carrier'];
$opt = array('resource' => 'carts');
$opt['postXml'] = $xml->asXML();
$xml = $webService->add($opt);
$cart_id = $xml->cart->id;
$xml = $webService->get(array('url' => PS_SHOP_PATH .'/api/orders/?schema=blank'));
$xml->order->id_address_delivery = $value['id_address_delivery'];
$xml->order->id_address_invoice = $value['id_address_delivery'];
$xml->order->id_cart = $cart_id;
$xml->order->id_currency = $value['id_currency'];
$xml->order->id_lang = $value['id_language'];
$xml->order->id_customer = $key;
$xml->order->id_carrier = $value['id_carrier'];
if($value['payment_mode'] == 'Cash on delivery (COD)')
$xml->order->module = 'ps_cashondelivery';
if($value['payment_mode'] == 'Payment by check')
$xml->order->module = 'ps_checkpayment';
$xml->order->payment = $value['payment_mode'];
$xml->order->total_paid = $value['price'];
$xml->order->total_paid_real = $value['price'];
$xml->order->total_products = $value['total_products'];
$xml->order->total_products_wt = $value['product_weight'];
$xml->order->conversion_rate = '1'; // conversion rate is fixed here
$opt = array('resource' => 'orders');
$opt['postXml'] = $xml->asXML();
$xml = $webService->add($opt);
}
}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();
} 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();
}

Categories