Prestashop Webservice to add simple product - php

I am writing a script that will add products through the webservice.
I`m having some dificulties for a couple of hours so I seek for help.
This is what I have now.
require_once("config.php");
require_once("PSWebServiceLibrary.php");
try {
$webService = new PrestaShopWebservice(SITE_URL, WEBSERVICE_AUTH_KEY, DEBUG_MODE);
$xml = $webService->get(array('url' => SITE_URL.'/api/products?schema=synopsis'));
$product = $xml->children()->children();
$product->price = 99;
$product->wholesale_price = 89;
$product->active = '1';
$product->on_sale = 0;
$product->show_price = 1;
$product->available_for_order = 1;
$product->name->language[0][0] = "Produit webservice";
$product->name->language[0][0]['id'] = 1;
$product->name->language[0][0]['xlink:href'] = SITE_URL . '/api/languages/' . 1;
$product->description->language[0][0] = "Description produit webservice";
$product->description->language[0][0]['id'] = 1;
$product->description->language[0][0]['xlink:href'] = SITE_URL . '/api/languages/' . 1;
$product->description_short->language[0][0] = "Descr. courte";
$product->description_short->language[0][0]['id'] = 1;
$product->description_short->language[0][0]['xlink:href'] = SITE_URL . '/api/languages/' . 1;
$product->reference = "ref_product_webservice";
$product->depends_on_stock = 0;
$category_id = 3;
$product->associations->categories->addChild('category')->addChild('id', $category_id);
$product->id_category_default = $category_id;
//
$opt = array('resource' => 'products');
$opt['postXml'] = $xml->asXML();
$xml = $webService->add($opt);
}
catch (PrestaShopWebserviceException $ex) {
echo "Error:<br>";
echo $ex->getMessage();
exit(1);
}
I have my webservice all set up , but I keep getting this error :
This call to PrestaShop Web Services failed and returned an HTTP status of 500. That means: Internal Server Error.
Please tell me what I am doing wrong.

Enable debug mode in your Prestashop. You will receive exactly which field are you setting wrong and why.
Enable Pretashop debug mode
Good luck.

Changed the schema to blank , and now it`s working.
The initial error was:
Attribute "href" bound to namespace

Related

Drupal 7, validate node as per interface

I created a webservice, it works correctly, I was doing the node creation operation and it works correctly.
I need to validate the node I'm about to save in the same way it is validated during the interface insertion form.
I have tried with
drupal_form_submit($nodeType . '_node_form', $form_state, (object) $node);
it keeps giving me errors its node reference fields
Could you suggest other ways to do the same validation that is done by the interface on a programmatically created node?
The error on the node reference field is:
" field_ente : this entry cannot be
referenced. "
The node (6310) exists correctly and if I try to do the node_save, it is saved correctly
the complete function is as follows
function my_ws_resource_create($field_nome = '', $field_cognome = '', $field_codice_fiscale = '', $field_data_di_nascita = '', $field_ente= '')
{
module_load_include('inc', 'node', 'node.pages');
global $user;
$nodeType = 'contatti';
$node = new stdClass();
$node->type = $nodeType;
$node->uid = $user->uid;
$node->status = 1;
$node->revision = 1;
$node->promote = 0;
$node->comment = 0;
node_object_prepare($node);
$node->field_cognome['und'][0]['value'] = $field_cognome;
$node->field_nome['und'][0]['value'] = $field_nome;
$node->field_codice_fiscale['und'][0]['cck_codicefiscale'] = $field_codice_fiscale;
$node->field_data_di_nascita['und'][0]['value'] = $field_data_di_nascita;
$node->field_categoria_contatto['und'][0]['tid'] = '66';
// $node->field_ente = array('und' => array(array('nid'=> $field_ente )));
// this field causes the error
$node->field_ente = array('und' => array(array('nid'=> '6310')));
$node->field_simplenews_term['it'][0]['tid'] = '13660';
$form_state = array();
$form_state['values']['type'] = $nodeType;
$form_state['values']['name'] = $user->name;
$form_state['values']['status'] = 1;
$form_state['values']['promote'] = 1;
$form_state['values']['sticky'] = 0;
$form_state['values']['op'] = t('Save');
drupal_form_submit($nodeType . '_node_form', $form_state, (object) $node);
if ($errors = form_get_errors()) {
return services_error(implode(" ", $errors), 406, array('form_errors' => $errors));
}
return 'Creation successful';
}
I've had success with the following (remove $form_state and replace drupal_form_submit):
if ($node = node_submit($node)) {
node_save($node);
// Success!
}
else {
// Fail :(
}

generating raw trx and sending it to the network shows “transaction underpriced” error

I'm trying to make an ethereum raw transaction by php and these libraries:
https://github.com/simplito/elliptic-php
https://github.com/kornrunner/php-keccak
https://github.com/web3p/rlp
this is my code:
use Elliptic\EC;
use kornrunner\Keccak;
use Web3p\RLP\RLP;
$privateKeyHex = '.....'; // wallet private key
$toWallet = '118086be6247fBDa3BC64B4A11F07F3894aA1fAF';
$ec = new EC('secp256k1');
$key = $ec->keyFromPrivate($privateKeyHex );
$publicKeyHex = $key->getPublic('hex');
// $publicKeyHex => 0445e2caf0f227247dfa10440765812492e4d4c9df7b4e74d0d5cd3279fa80f5ef987a70e061ca20c06f09690957c9ba365cf06541181d1291e14c847d0d826583
$nonce= 0;
$gasPrice = 1e9;
$gasLimit = 21000;
$to = hex2bin($toWallet);
$value = 1e14-($gasLimit*$gasPrice)-1;
$inputData = 0;
//*********** EIP_155 *********
$chain_id = 1;
$r = 0;
$s = 0;
//*****************************
$SignData = [$nonce,$gasPrice,$gasLimit,$to,$value,$inputData,$chain_id,$r,$s];
$SignRlpData = rlpEncode($SignData);
$signHash = Keccak::hash(hex2bin($SignRlpData), 256);
$signature = $ec->sign($signHash ,$key);
$r = $signature->r->toString('hex');
$s = $signature->s->toString('hex');
$v = $chain_id*2 + ($signature->recoveryParam +35);
$trxData = [$nonce,$gasPrice,$gasLimit,$to,$value,$inputData,$v,hex2bin($r),hex2bin($s)];
$trxRlpData = rlpEncode($trxData );
// trxRlpData => f86980843b9aca0082520894118086be6247fbda3bc64b4a11f07f3894aa1faf8647d99eefefff8026a08a53214c92ff615c82eede2e51ab9d4d22d6a393f3ab8acee63c23d04e8e2fa7a07661f758f8b968d7597449ce05027edf3f2891fef0d1278f7330e99545109a2b
function rlpEncode($a){
$rlp = new RLP;
$encodedBuffer = $rlp->encode($a);
return $encodedBuffer->toString('hex');
}
now after I send value of $trxRlpData to the ethereum network by https://etherscan.io/pushTx, show me this error message:
Error! Unable to broadcast Tx : {"jsonrpc":"2.0","id":1,"error":{"code":-32000,"message":"transaction underpriced"}}
but where is problem ?
finally I solved this problem with increasing a little $gasLimit.
$gasLimit = 21001;
When there is a pending transaction and you try to send a new one with same nonce you see this error.
If you needs to make a new transaction while the old one has not confirmed yet, you must get pending transactions count getTransactionCount of address and use as nonce

Prestashop 1.6 Webservice Order

I'm trying to finish my custom module to import clients, addresses, carts and orders from a webservice.
Clients, Adresses and Carts imports works fine but when trying to insert new Order, it returns this error:
This call to PrestaShop Web Services failed and returned an HTTP status of 500. That means: Internal Server Error.
If i take a look to my apache2 error.log I can see this error:
PHP Fatal error: Call to a member function validateOrder() on boolean in /var/www/html/prestashop_pool/myshop/classes/order/Order.php on line 1463
This piece of code is the ones related to the order adittion via WebService:
// 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
Anyone knows how to fix it?
It may be due to the wrong values you are passing in
$xml->order->module = $order_module;
$xml->order->payment = $order_payment;
check this value, I think prestashop need ps_ prefix before adding module value.

php - prestashop Class 'Product' not found

I'm writing a webservice using php and I'm using prestashop webservice library (https://github.com/PrestaShop/PrestaShop-webservice-lib) . this is my code :
define('DEBUG', true);
define('PS_SHOP_PATH', 'http://xxxxx.com/');
define('PS_WS_AUTH_KEY', 'xxxxx');
require_once ('PSWebServiceLibrary.php');
$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 (strlen($_POST('c_email'))>0)
$customer['email'] = Tools::getValue('c_email');
else
$customer['email'] = 'admin#yoursite.com';
*/
$customer['email'] ="navid.abutorab#gmail.com";
$customer['firstname'] = "navid";
$customer['lastname'] ="abutorab";
$customer['address1'] = "adres";
$customer['city'] = "citye";
$customer['phone'] = "09360544841";
$id['country'] = '165';
$id['lang'] = '1';
$id['currency'] = '1';
$id['carrier'] = '3';
$product['quantity'] ="1";
$id_product="10104";
$product['id'] = $id_product;
echo Product::getPriceStatic($product['id']) . "-----";
$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;
When I run the page , I get this error :
Class 'Product' not found in /home/xxxxx/public_html/test/test.php on line 37
line 37 is this line :
$product['price'] = Product::getPriceStatic($product['id']);
what should I include to make it works fine ?
Try adding the following line in the starting of your web service code.
require_once(dirname(__FILE__).'/../../config/config.inc.php');
Note: Please adjust the path as per your file path. You just need to include the 'config.inc.php' file.

PHP-EWS 2010, how to set the IsRead flag

I have been able to successfully retrieve the unread emails from an Exchange 2010 inbox using php-ews API. However after I have fetched the emails, I want to set the IsRead property of the email to true, so that these messages do not appear the next time I fetch emails.
Anyone done this before ?
EDIT :
This is how I am trying to set the IsRead flag :
$message_id = ''; //id of message
$change_key = ''; //change key
$response = $ews->GetItem($request);
//print_r($response);exit;
if( $response->ResponseMessages->GetItemResponseMessage->ResponseCode == 'NoError' &&
$response->ResponseMessages->GetItemResponseMessage->ResponseClass == 'Success' ) {
$a = array();
$message = $response->ResponseMessages->GetItemResponseMessage->Items->Message;
$a['message_body'] = $message->Body->_;
$a['sender'] = $message->From->Mailbox->EmailAddress;
$a['subject'] = $message->ConversationTopic;
$data[] = $a;
//process the message data.
$messageType = new EWSType_MessageType();
$messageType->IsRead = true;
$path = new EWSType_PathToUnindexedFieldType();
$path->FieldURI = 'message:IsRead';
$setField = new EWSType_SetItemFieldType();
$setField->Message = $messageType;
$setField->FieldURI = $path;
$u = new EWSType_ItemChangeType();
$u->Updates = new EWSType_NonEmptyArrayOfItemChangeDescriptionsType();
$u->Updates->SetItemField = $setField;
$u->ItemId = new EWSType_ItemIdType();
$u->ItemId->Id = $message_id;
$u->ItemId->ChangeKey = $change_key;
$updatedItems = new EWSType_NonEmptyArrayOfItemChangesType();
$updatedItems->ItemChange = $u;
$updateMessenger = new EWSType_UpdateItemType();
$updateMessenger->ItemChanges = $updatedItems;
$updateMessenger->MessageDisposition = 'SaveOnly';
$updateMessenger->ConflictResolution = 'AutoResolve';
try {
$update_response = $ews->UpdateItem($updateMessenger);
}catch (Exception $e){
echo $e->getMessage();
}
}
When I run the file I get the following error :
An internal server error occurred. The operation failed.
After debugging for some time, I have concluded that the error happens at the curl_exec function in NTLMSoapClient.php file.
I dont know where to go on from here. Please help.
I've faced a similar issue when updating a calendar event and setting the IsAllDayEvent flag. This is the code that worked for me:
$ews = new ExchangeWebServices(...);
$request = new EWSType_UpdateItemType();
$request->ConflictResolution = 'AlwaysOverwrite';
$request->ItemChanges = array();
$change = new EWSType_ItemChangeType();
$change->ItemId = new EWSType_ItemIdType();
$change->ItemId->Id = $id;
$change->ItemId->ChangeKey = $changeKey;
$field = new EWSType_SetItemFieldType();
$field->FieldURI = new EWSType_PathToUnindexedFieldType();
$field->FieldURI->FieldURI = "calendar:IsAllDayEvent";
$field->CalendarItem = new EWSType_CalendarItemType();
$field->CalendarItem->IsAllDayEvent = true;
$change->Updates->SetItemField[] = $field;
$request->ItemChanges[] = $change;
$response = $ews->UpdateItem($request);
The biggest difference I see here is that you do $u->Updates->SetItemField = $setField;, whereas my code uses $u->Updates->SetItemField[] = $setField;.
I hope this helps.
Edit: You might have already seen this, but I based my code on the one from the php-ews wiki.
I tried everything including PathToExtendedFieldType and it doesn't work at the end code below worked for me
$ews = new ExchangeWebServices('red', 'red', 'red',ExchangeWebServices::VERSION_2007_SP1);
$request = new EWSType_UpdateItemType();
$request->SendMeetingInvitationsOrCancellations = 'SendToNone';
$request->MessageDisposition = 'SaveOnly';
$request->ConflictResolution = 'AlwaysOverwrite';
$request->ItemChanges = array();
// Build out item change request.
$change = new EWSType_ItemChangeType();
$change->ItemId = new EWSType_ItemIdType();
$change->ItemId->Id = $contact_id;
$change->ItemId->ChangeKey = $contact_change_key;
#$change->Updates = new EWSType_NonEmptyArrayOfItemChangeDescriptionsType();
#$change->Updates->SetItemField = array();
// Build the set item field object and set the item on it.
$field = new EWSType_SetItemFieldType();
$field->FieldURI = new EWSType_PathToUnindexedFieldType();
$field->FieldURI->FieldURI = "message:IsRead";
$field->Message = new EWSType_MessageType();
$field->Message->IsRead = true;
$change->Updates->SetItemField[] = $field;
$request->ItemChanges[] = $change;
$response = $ews->UpdateItem($request);
var_dump($response);
Well, i dont know how it is in php, but in C# there is another field, that must be set: IsReadSpecified = true.
email.IsRead = true;
email.IsReadSpecified = true;

Categories