Subir imágenes API REST Prestashop

Subir imágenes API REST Prestashop

Postby AngelSalom » Mon Apr 09, 2018 3:03 pm

Hola amiguetes, gracias a la ayuda de Quim empiezo a entender la maravilla de los webservices, estoy comunicando con el API REST de Prestashop de manera fenomenal pero me he encallado a la hora de subir imágenes. Siguiendo este ejemplo escrito en PHP

Code: Select all  Expand view
define("PS_SHOP_PATH", 'http://midominio.com/');
define("PS_WS_AUTH_KEY", 'XXXXXXXXXXX' );
$img= _PS_TMP_IMG_DIR_  .$mifoto ;

$curl = curl_init();
curl_setopt($curl,CURLOPT_HEADER, true);
curl_setopt($curl,CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl,CURLINFO_HEADER_OUT, true);
curl_setopt($curl, CURLOPT_URL, PS_SHOP_PATH . '/api/images/products/' .  $id_produc );
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, PS_WS_AUTH_KEY  );
curl_setopt($curl, CURLOPT_POSTFIELDS, array('image' => '@'.$img) );
if( ! $result = curl_exec($curl))
     { echo $crlf .'Error : '.$idproduc.' '.$img.' -> '.curl_error($curl). $crlf; }
else { echo $result. '<br>. Image added: ' . $nomfoto . $crlf  ; }

curl_close($curl);


adaptado a Harbour ...

Code: Select all  Expand view

#include "hbcurl.ch"

Function main()
Local cApiUrl   := "http://24h.vinaros.net/prestashop_16/api/"
Local cApiKey   := 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
Local hWebService
Local cUrl
Local cImagen

  curl_global_init()
  hWebService := curl_easy_init()

  If !empty(hWebService)
    cUrl   :=cApiUrl+'images/products/1'
    cImagen:='C:\pruebas\imagen.jpg'

    curl_easy_setopt(hWebService,HB_CURLOPT_HEADER, .T.)
    curl_easy_setopt(hWebService,HB_CURLOPT_RETURNTRANSFER, .T.)
    curl_easy_setopt(hWebService,HB_CURLINFO_HEADER_OUT, .T.)
    curl_easy_setopt(hWebService,HB_CURLOPT_URL, cUrl )
    curl_easy_setopt(hWebService,HB_CURLOPT_POST, .T.)
    curl_easy_setopt(hWebService,HB_CURLOPT_HTTPAUTH, HB_CURLAUTH_BASIC)
    curl_easy_setopt(hWebService,HB_CURLOPT_USERPWD, cApiKey)
    curl_easy_setopt(hWebService,HB_CURLOPT_POSTFIELDS, {'image',cImagen})

    curl_easy_setopt(hWebService, HB_CURLOPT_DL_BUFF_SETUP )
   
    If curl_easy_perform (hWebService)<>0
      msginfo ('error')
    Else
      memowrit ('resultado.xml',curl_easy_dl_buff_get( hWebService ))
    Endif
 
  Endif

  curl_global_cleanup()
Return (nil)
 


... presupongo que no estaré haciendo bien la traducción de la línea que pasa la imagen :

Code: Select all  Expand view
curl_setopt($curl, CURLOPT_POSTFIELDS, array('image' => '@'.$img) );


... veo en otra web que se habla de indicar la imagen del siguiente modo :

Code: Select all  Expand view
curl_setopt($ch, CURLOPT_POSTFIELDS, array('image' =>  new CurlFile($imagePath)));


No consigo un resultado .... ¿alguien se ha peleado con esto?
Angel Salom
Visionwin Software - https://www.visionwin.com
------------------------------------------------------------
fwh 19.05 - harbour 3.2 - bcc 7.4
User avatar
AngelSalom
 
Posts: 708
Joined: Fri Oct 07, 2005 7:38 am
Location: Benicarló (Castellón ) - España

Re: Subir imágenes API REST Prestashop

Postby cnavarro » Mon Apr 09, 2018 3:22 pm

Hablo, sin haber utilizado esta api nunca, pero tiene toda la pinta de esperar recibir un hash
Cristobal Navarro
Hay dos tipos de personas: las que te hacen perder el tiempo y las que te hacen perder la noción del tiempo
El secreto de la felicidad no está en hacer lo que te gusta, sino en que te guste lo que haces
User avatar
cnavarro
 
Posts: 6500
Joined: Wed Feb 15, 2012 8:25 pm
Location: España

Re: Subir imágenes API REST Prestashop

Postby AngelSalom » Mon Apr 09, 2018 3:25 pm

cnavarro wrote:Hablo, sin haber utilizado esta api nunca, pero tiene toda la pinta de esperar recibir un hash


¿Y cómo crear ese hash del fichero de imagen? :oops: :oops:
Angel Salom
Visionwin Software - https://www.visionwin.com
------------------------------------------------------------
fwh 19.05 - harbour 3.2 - bcc 7.4
User avatar
AngelSalom
 
Posts: 708
Joined: Fri Oct 07, 2005 7:38 am
Location: Benicarló (Castellón ) - España

Re: Subir imágenes API REST Prestashop

Postby manuelcalerosolis » Mon Apr 09, 2018 4:06 pm

Ángel,

Yo subo las imágenes a mano, creando ademas las rutas, pq prestashop tiene una manera "rara" de designar donde se colocan las imágenes, pero si tienes el 'id' del producto no tiene ninguna dificultad.

Contacta conmigo si quieres q te envíe mi código.

Saludos

mcalero@gestool.es
User avatar
manuelcalerosolis
 
Posts: 149
Joined: Mon Oct 10, 2005 9:30 am
Location: Huelva - Spain

Re: Subir imágenes API REST Prestashop

Postby AngelSalom » Mon Apr 09, 2018 4:12 pm

Hola Manuel, gracias. Hasta ahora subo las imágenes por FTP, con los diferentes tamaños y tal. El resto de información la actualizo atacando directamente la base de datos por SQL.

Mi intención es abandonar este procedimiento que me da bastante guerra con los cambios de versiones de PrestaShop y pasarme al webservice.
Angel Salom
Visionwin Software - https://www.visionwin.com
------------------------------------------------------------
fwh 19.05 - harbour 3.2 - bcc 7.4
User avatar
AngelSalom
 
Posts: 708
Joined: Fri Oct 07, 2005 7:38 am
Location: Benicarló (Castellón ) - España

Re: Subir imágenes API REST Prestashop

Postby cnavarro » Mon Apr 09, 2018 4:46 pm

En la documentacion del API tiene que haber información, si me la facilitas, quizás pueda ayudarte
A ver si alguien se anima y hace una clase para esta API
Cristobal Navarro
Hay dos tipos de personas: las que te hacen perder el tiempo y las que te hacen perder la noción del tiempo
El secreto de la felicidad no está en hacer lo que te gusta, sino en que te guste lo que haces
User avatar
cnavarro
 
Posts: 6500
Joined: Wed Feb 15, 2012 8:25 pm
Location: España

Re: Subir imágenes API REST Prestashop

Postby AngelSalom » Mon Apr 09, 2018 7:53 pm

Cristóbal, la documentación :
http://doc.prestashop.com/display/PS15/Using+the+PrestaShop+Web+Service

Estoy empezando con el CRUD de Customers y Products, y parece estar dando buenos resultados. El punto en el que estoy encallado, como comentaba :

http://doc.prestashop.com/display/PS15/Chapter+9+-+Image+management

Gracias.

PD : No sería mala idea trabajar en una clase para el API de Prestashop. Yo tengo un buen trabajo por delante, y Quim me adelantó un muy buen ejemplo que puede servir de base. A medida que vaya adelantando iré informando.
Angel Salom
Visionwin Software - https://www.visionwin.com
------------------------------------------------------------
fwh 19.05 - harbour 3.2 - bcc 7.4
User avatar
AngelSalom
 
Posts: 708
Joined: Fri Oct 07, 2005 7:38 am
Location: Benicarló (Castellón ) - España

Re: Subir imágenes API REST Prestashop

Postby cnavarro » Mon Apr 09, 2018 9:16 pm

Angel, no sé si esto te funcionará

Code: Select all  Expand view


local cImage

   TEXT INTO cImage
   {
    "image": ["c:\myimage.jpg"],
    }
   ENDTEXT

.../...

   curl_easy_setopt(hWebService,HB_CURLOPT_POSTFIELDS, hb_JsonDecode( cImage, .F. ) )

 
Cristobal Navarro
Hay dos tipos de personas: las que te hacen perder el tiempo y las que te hacen perder la noción del tiempo
El secreto de la felicidad no está en hacer lo que te gusta, sino en que te guste lo que haces
User avatar
cnavarro
 
Posts: 6500
Joined: Wed Feb 15, 2012 8:25 pm
Location: España

Re: Subir imágenes API REST Prestashop

Postby AngelSalom » Tue Apr 10, 2018 7:14 am

No funciona Cristóbal. He capturado el resultado que arroja el servidor .

El código

Code: Select all  Expand view

#include "fivewin.ch"
#include "hbcurl.ch"

#define GET_METHOD    1
#define POST_METHOD   2
#define PUT_METHOD    3

#xcommand TEXT INTO <v> => #pragma __cstream|<v>:=%s
#xcommand TEXT INTO <v> ADDITIVE => #pragma __cstream|<v>+=%s

Function main()
Local cApiUrl   := "http://24h.vinaros.net/prestashop_16/api/"
Local cApiKey   := 'xxx'
Local hWebService
Local cUrl
Local cImagen

  // Creo un nuevo objeto CURL
  curl_global_init()
  hWebService := curl_easy_init()

  // Si se crea correctamente
  If !empty(hWebService)
    cUrl   :=cApiUrl+'images/products/1'
   
    // -------------------------- Activa que se reciba buffer
    curl_easy_setopt(hWebService, HB_CURLOPT_DL_BUFF_SETUP )
   
    // -------------------------- Proceso de envío
    curl_easy_setopt(hWebService,HB_CURLOPT_HEADER, .T.)
    curl_easy_setopt(hWebService,HB_CURLOPT_RETURNTRANSFER, .T.)
    curl_easy_setopt(hWebService,HB_CURLINFO_HEADER_OUT, .T.)
    curl_easy_setopt(hWebService,HB_CURLOPT_URL, cUrl )
    curl_easy_setopt(hWebService,HB_CURLOPT_POST, .T.)
    curl_easy_setopt(hWebService,HB_CURLOPT_HTTPAUTH, HB_CURLAUTH_BASIC)
    curl_easy_setopt(hWebService,HB_CURLOPT_USERPWD, cApiKey)

    TEXT INTO cImagen
     {
       "image": ["C:\SI\TRABAJO\FWH\propios\presta3\visionwincargando.jpg"],
     }
    ENDTEXT
   
    curl_easy_setopt(hWebService,HB_CURLOPT_POSTFIELDS, hb_JsonDecode( cImagen, .F. ) )
   
    If curl_easy_perform (hWebService)<>0
      msginfo ('error')
    Else
      memowrit ('resultado.xml',curl_easy_dl_buff_get( hWebService ))
    Endif
 
  Endif

  // Elimino objeto CURL
  curl_global_cleanup()
Return (nil)

 


Y la respuesta :

Code: Select all  Expand view
HTTP/1.1 400 Bad Request
Date: Tue, 10 Apr 2018 07:11:54 GMT
Server: Apache
Connection: close
Content-Type: text/html; charset=iso-8859-1

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>400 Bad Request</title>
</head><body>
<h1>Bad Request</h1>
<p>Your browser sent a request that this server could not understand.<br />
</p>
<hr>
<address>Apache Server at 24h.vinaros.net Port 80</address>
</body></html>
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>503 Service Unavailable</title>
</head><body>
<h1>Service Unavailable</h1>
<p>The server is temporarily unable to service your
request due to maintenance downtime or capacity
problems. Please try again later.</p>
<p>Additionally, a 503 Service Unavailable
error was encountered while trying to use an ErrorDocument to handle the request.</p>
<hr>
<address>Apache Server at 24h.vinaros.net Port 80</address>
</body></html>
 


Si necesitas la API KEY para hacer alguna prueba te la paso.
Gracias.
Angel Salom
Visionwin Software - https://www.visionwin.com
------------------------------------------------------------
fwh 19.05 - harbour 3.2 - bcc 7.4
User avatar
AngelSalom
 
Posts: 708
Joined: Fri Oct 07, 2005 7:38 am
Location: Benicarló (Castellón ) - España

Re: Subir imágenes API REST Prestashop

Postby AngelSalom » Tue Apr 10, 2018 8:02 am

Según la documentación, para añadir una imagen nueva :
Code: Select all  Expand view

    HTTP method: POST
    URL: /images/products/1
    Parameters: images=[binary content for the new image]
 


En PHP he visto dos métodos :

Code: Select all  Expand view
curl_setopt($ch, CURLOPT_POSTFIELDS, array('image' => '@'.$image_path));

Code: Select all  Expand view
curl_setopt($ch, CURLOPT_POSTFIELDS, array('image' => new CurlFile($image_path)));


El segundo método sería el apropiado para PHP a partir de 5.5, es el que deberíamos considerar. El tema es encontrar la equivalencia a la función CurlFile ... supongo.
Angel Salom
Visionwin Software - https://www.visionwin.com
------------------------------------------------------------
fwh 19.05 - harbour 3.2 - bcc 7.4
User avatar
AngelSalom
 
Posts: 708
Joined: Fri Oct 07, 2005 7:38 am
Location: Benicarló (Castellón ) - España

Re: Subir imágenes API REST Prestashop

Postby hmpaquito » Tue Apr 10, 2018 11:30 am

No soy experto, pero por lo que dice aquí http://php.net/manual/es/curlfile.construct.php se necesita un hash por fichero, que contenga un hash a 5 elementos.

También ver el equivalente a la clase que es la funcion
Code: Select all  Expand view
$cfile = curl_file_create('cats.jpg','image/jpeg','test_name');
hmpaquito
 
Posts: 1482
Joined: Thu Oct 30, 2008 2:37 pm

Re: Subir imágenes API REST Prestashop

Postby cnavarro » Tue Apr 10, 2018 12:31 pm

Angel, mandame un mail
Cristobal Navarro
Hay dos tipos de personas: las que te hacen perder el tiempo y las que te hacen perder la noción del tiempo
El secreto de la felicidad no está en hacer lo que te gusta, sino en que te guste lo que haces
User avatar
cnavarro
 
Posts: 6500
Joined: Wed Feb 15, 2012 8:25 pm
Location: España

Re: Subir imágenes API REST Prestashop

Postby AngelSalom » Tue Apr 10, 2018 1:08 pm

cnavarro wrote:Angel, mandame un mail


Enviado :D
Angel Salom
Visionwin Software - https://www.visionwin.com
------------------------------------------------------------
fwh 19.05 - harbour 3.2 - bcc 7.4
User avatar
AngelSalom
 
Posts: 708
Joined: Fri Oct 07, 2005 7:38 am
Location: Benicarló (Castellón ) - España

Re: Subir imágenes API REST Prestashop

Postby AngelSalom » Wed Apr 11, 2018 11:09 am

Este código en C generado por CURL sube bien las imágenes. Lo tengo portado a Harbour pero me faltan algunas funciones que ya comento aquí : http://forums.fivetechsupport.com/viewtopic.php?f=17&t=34057, concretamente curl_mime_init(), curl_mime_addpart(), curl_mime_filedata(), curl_mime_name().

Aparecen en libcurl a partir de la 7.56 ... ¿alguna ayudita?

Code: Select all  Expand view
/********* Sample code generated by the curl command line tool **********
 * All curl_easy_setopt() options are documented at:
 * https://curl.haxx.se/libcurl/c/curl_easy_setopt.html
 ************************************************************************/

#include <curl/curl.h>

int main(int argc, char *argv[])
{
  CURLcode ret;
  CURL *hnd;
  curl_mime *mime1;
  curl_mimepart *part1;

  mime1 = NULL;

  hnd = curl_easy_init();
  curl_easy_setopt(hnd, CURLOPT_BUFFERSIZE, 102400L);
  curl_easy_setopt(hnd, CURLOPT_URL, "http://miprestashop/api/images/products/1");
  curl_easy_setopt(hnd, CURLOPT_NOPROGRESS, 1L);
  curl_easy_setopt(hnd, CURLOPT_HEADER, 1L);
  curl_easy_setopt(hnd, CURLOPT_USERPWD, "xxx:xxx");
  mime1 = curl_mime_init(hnd);
  part1 = curl_mime_addpart(mime1);
  curl_mime_filedata(part1, "imagen.jpg");
  curl_mime_name(part1, "image");
  curl_easy_setopt(hnd, CURLOPT_MIMEPOST, mime1);
  curl_easy_setopt(hnd, CURLOPT_USERAGENT, "curl/7.59.0");
  curl_easy_setopt(hnd, CURLOPT_MAXREDIRS, 50L);
  curl_easy_setopt(hnd, CURLOPT_VERBOSE, 1L);
  curl_easy_setopt(hnd, CURLOPT_TCP_KEEPALIVE, 1L);
  ret = curl_easy_perform(hnd);

  curl_easy_cleanup(hnd);
  hnd = NULL;
  curl_mime_free(mime1);
  mime1 = NULL;

  return (int)ret;
}
/**** End of sample code ****/
 
Angel Salom
Visionwin Software - https://www.visionwin.com
------------------------------------------------------------
fwh 19.05 - harbour 3.2 - bcc 7.4
User avatar
AngelSalom
 
Posts: 708
Joined: Fri Oct 07, 2005 7:38 am
Location: Benicarló (Castellón ) - España


Return to FiveWin para Harbour/xHarbour

Who is online

Users browsing this forum: No registered users and 70 guests