Jump to content

Création d'un produit avec image en webservice


Recommended Posts

Bonjour à tous :)

 

J'essaye de créer un produit par webservice (enfin réussi après un certain temps à batailler...), mais je ne comprends pas comment ajouter une image au produit tout en le créant. Voici le code que j'utilise pour créer le produit (il fonctionne).

      $xml = $webService->get(array('resource' => 'products?schema=synopsis'));
     $resources = $xml->children()->children();

     // Champs requis
     $resources->quantity = $product->getQuantity();
     $resources->price = '15.5';
     $resources->out_of_stock = '0';
     $resources->name->language[1] = $product->getName();
     $resources->link_rewrite->language[1] = $product->getEan();

     // Meta
     $resources->meta_keywords->language[1] = $product->getMetaKeywords();
     $resources->meta_title->language[1] = $product->getMetaTitle();
     $resources->meta_description->language[1] = $product->getMetaDescription(); /// vide
     // References
     $resources->ean13 = $product->getEan();
     $resources->supplier_reference = $product->getEan();

     // Inventaire
     $resources->active = '1';
     $resources->available_for_order = '1';
     $resources->condition = 'new';
     $resources->show_price = '1';

    unset($resources->associations->categories->category);

     // associer a une categorie
     $resources->associations->categories->addChild('category')->addChild('id', 2);
     $xml = $webService->add(
                     array(
                         'resource' => 'products',
                         'postXml' => $xml->asXML()
                     )
     );

 

Aussi, j'aimerais ajouter une description à mon produit, mais quand je fais :

$resources->description->language[1] = 'toto';

ça marche, alors que quand je fais :

$resources->description->language[1] = '<strong>toto</strong>';

J'ai une erreur avec un code 500.

J'ai essayé avec cdata et/ou htmlentities, mais rien n'y fait.

 

Auriez-vous une idée svp ? Merci d'avance :)

 

P.S. : Je suis sur la 1.4.3

Link to comment
Share on other sites

  • 2 years later...

Comme ça parle de webservice, je vais en profiter pour poser une question : Avez-vous réussi à gérer les problèmes d'accents ainsi que les caractères étrangers ? Comme le caractère chinois, il ne le prends pas en compte, et met une erreur :

 

Fatal error: Uncaught exception 'PrestaShopWebserviceException' with message 'This call to PrestaShop Web Services failed and returned an HTTP status of 500. That means: Internal Server Error.' in C:\wamp\www\testPrestashop\prestashop\PSWebServiceLibrary.php:91 Stack trace: #0 C:\wamp\www\testPrestashop\prestashop\PSWebServiceLibrary.php(224): PrestaShopWebservice->checkStatusCode(500) #1 C:\wamp\www\testPrestashop\prestashop\C-CRUD.class.php(488): PrestaShopWebservice->add(Array) #2 {main} thrown in C:\wamp\www\testPrestashop\prestashop\PSWebServiceLibrary.php on line 91

 

 

 

Sinon je vais créer un autre topic, en espérant avoir de l'aide :)

 

 

Edit : Solution trouvée, voir ce topic :

 

http://www.prestashop.com/forums/topic/337312-probl%C3%A8me-encodage-acsii/

 

:-)

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

  • 4 months later...

Bonjour à tous smile.gif

 

J'essaye de créer un produit par webservice (enfin réussi après un certain temps à batailler...), mais je ne comprends pas comment ajouter une image au produit tout en le créant. Voici le code que j'utilise pour créer le produit (il fonctionne).

$xml = $webService->get(array('resource' => 'products?schema=synopsis'));
      $resources = $xml->children()->children();

      // Champs requis
      $resources->quantity = $product->getQuantity();
      $resources->price = '15.5';
      $resources->out_of_stock = '0';
      $resources->name->language[1] = $product->getName();
      $resources->link_rewrite->language[1] = $product->getEan();

      // Meta
      $resources->meta_keywords->language[1] = $product->getMetaKeywords();
      $resources->meta_title->language[1] = $product->getMetaTitle();
      $resources->meta_description->language[1] = $product->getMetaDescription(); /// vide
      // References
      $resources->ean13 = $product->getEan();
      $resources->supplier_reference = $product->getEan();

      // Inventaire
      $resources->active = '1';
      $resources->available_for_order = '1';
      $resources->condition = 'new';
      $resources->show_price = '1';

     unset($resources->associations->categories->category);

      // associer a une categorie
      $resources->associations->categories->addChild('category')->addChild('id', 2);
      $xml = $webService->add(
                      array(
                          'resource' => 'products',
                          'postXml' => $xml->asXML()
                      )
      );
Aussi, j'aimerais ajouter une description à mon produit, mais quand je fais :

$resources->description->language[1] = 'toto';
ça marche, alors que quand je fais :

$resources->description->language[1] = '<strong>toto</strong>';
J'ai une erreur avec un code 500.

J'ai essayé avec cdata et/ou htmlentities, mais rien n'y fait.

 

Auriez-vous une idée svp ? Merci d'avance smile.gif

 

P.S. : Je suis sur la 1.4.3

 

 

Salut

 

J'avais le même prpblème que toi et je vien de trouver la solution:

 

1 - Créer le produit

2 - Récupéré l'id du produit

3 - ajouter l'image via curl  (c'est pareil pour les stock ça ce fait après la création du produit)

 

1 - Création du produit: on passe....

 

2 - Récup de l'id (je met que le code de l'envois au serveur...)

          // Envois de la requete au webservices
          
          $opt = array('resource' => 'products',
                       'display' => 'full',
                       'postXml' => $xml->asXML());
          
          $xml = $this->webService->add($opt);

          // Récupration de l'id du produit créé
          $product_id = $xml->children()->children()->id;

2 - création de l'image en curl: voici une fonction isssue de ma classe, il faut adapter l'url du webservice, et le token

        public function updateProductImage($product_id,$imgFullPath)
          { 

          $webservice_url = $this->webservices_url. '/api/images/products/' . $product_id;
          $webservices_token = $this->webservices_token; 

          $ch = curl_init();
          
          curl_setopt($ch, CURLOPT_URL, $webservice_url);
          curl_setopt($ch, CURLOPT_POST, true);
          
          curl_setopt($ch, CURLOPT_USERPWD, $webservices_token.':');
          curl_setopt($ch, CURLOPT_POSTFIELDS, array('image'=>"@".$imgFullPath.";type=image/jpeg"));
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
          
          if(curl_exec($ch) === false)
            { 
            $str_return = "-1"; 
            }
          else 
            { 
            $str_return = "-1"; 
            }
            
          curl_close($ch);
          return $str_return;
          }   

Voila.

 

Par contre je ne trouve pas comment modifier/supprimer une image produit par webservice, si quelqun sais faire je suis preneur

 

a+

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

  • 4 weeks later...

Bonjour, 

J'ai suivi votre solution mais je n'arrive pas à insérer une image à un produit. 

 

Voici mon code :

 

$product_id = '2';

$imgFullPath = $_SERVER["DOCUMENT_ROOT"].'/img/p/produit/123.jpg';
var_dump(file_exists($imgFullPath)); // retour true

updateProductImage($product_id,$imgFullPath);


function updateProductImage($product_id,$imgFullPath)
{ 

          $webservice_url = PS_SHOP_PATH. '/api/images/products/' . $product_id;
          $webservices_token = PS_WS_AUTH_KEY; //défini en haut de mon document 

          $ch = curl_init();
          
          curl_setopt($ch, CURLOPT_URL, $webservice_url);
          curl_setopt($ch, CURLOPT_POST, true);
          
          curl_setopt($ch, CURLOPT_USERPWD, $webservices_token.':');
          curl_setopt($ch, CURLOPT_POSTFIELDS, array('image'=>"@".$imgFullPath.";type=image/jpeg"));
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

         $reponse = curl_exec($ch);  // retourne "Unable to save this image"
             
          curl_close($ch);
          return $reponse;
   }  

Avez-vous rencontré la même erreur ?

Link to comment
Share on other sites

Bonjour non je n'ai pas eu ça.

 

est-ce que l'image est bien une jpeg (voir ci-dessous pour pallier à ce problème) ?

 

Entre temps j'ai réussit à supprimer une image et faire la mise à jour (en supprimant puis en ajoutant la nouvelle image). J'ai également modifié mon code pour trouver le type mime de l'image automatiquement.

 

Voici le code brut de classe

        public function updateProductImage($product_id,$imgFullPath)
          {     
          // Préparation des variables utiles à l'envois de l'image
          $image_path = str_replace('\\','\\\\',$imgFullPath); //adaptation du path qui est du genre C:\temp\big_images\mon_image.png 

          $image_mime = image_type_to_mime_type(exif_imagetype($imgFullPath));          
          
          // Recherche d'une image existante pour le produit
          try
            {
            $url = $this->webservices_url. "/api/images/products/$product_id";
            $xml = $this->webService->get(array('url' => $url));
            
            $resources_img = $xml->image->children();

            $oldImageId = $resources_img->attributes();
            
            }
          catch(Exception $e)
            {
            $oldImageId = '';
            }
          
          if ($oldImageId != '')   // Mode mise à jour
            {
            // suppression de l'image existante
            $url = $this->webservices_url. "/api/images/products/$product_id/$oldImageId";
            $ch = curl_init();
            
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
            curl_setopt($ch, CURLOPT_USERPWD, $this->webservices_token.':');
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
            $result = curl_exec($ch);
            curl_close($ch);
            
            // envois de la nouvelle image   
            $url = $this->webservices_url. "/api/images/products/$product_id";
            
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_USERPWD, $this->webservices_token.':');
            curl_setopt($ch, CURLOPT_POSTFIELDS, array('image' => '@'.$image_path . ";type=" . $image_mime));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $result = curl_exec($ch);
            curl_close($ch);     
            }                   
          else  // Mode insetion
            {
            // envois de la nouvelle image   
            $url = $this->webservices_url. "/api/images/products/$product_id";
            
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_USERPWD, $this->webservices_token.':');
            curl_setopt($ch, CURLOPT_POSTFIELDS, array('image' => '@'.$image_path . ";type=" . $image_mime));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $result = curl_exec($ch);
            curl_close($ch);              
            }

          return array('Code' => '1',
                       'Type' => 'OK',
                       'Message' => 'Transphert réussit');  
          }   

Attention la fonction exif_imagetype() nécessite que php_exif.dll soit déclarée ds le php.ini

 

 

Link to comment
Share on other sites

  • 2 weeks 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...