Página 1 de 2

webservice json deliveryapp

Enviado: 28 Mai 2020 10:37
por JoséQuintas
Estou tentando ajudar um colega nosso.
Nunca fiz nada com webservice json.

o manual do webservice é este:

https://deliveryapp.neemo.com.br/api/do ... sion_order

Meu teste, incompleto e nem sei se está certo, é este, baseado em posts do fórum:

Código: Selecionar todos

PROCEDURE Main

   LOCAL cURL, nId, cJSON, cSort := "[id][asc]", cCertCN, cSoapAction

   cURL        := ""
   cSoapAction := "/v1/order"
   cJSON       := {{] + ;
      ["token_account": 0,] + ;
      ["limit": 10,] + ;
      ["page": 1,] + ;
      ["modified": "2020-05-28 08:00:00",] + ;
      ["status": 0,] + ;
      ["sort": "] + cSort + [",] + ;
      ["created_at": "2020-05-28 08:00:00"] + ;
      [}]

   ? MicrosoftXMLSoapPost( cURL, cJSON, cSoapAction, cCertCN )
   Inkey(0)

   RETURN

FUNCTION MicrosoftXmlSoapPost( cURL, cJSON, cSoapAction, cCertCN )

   LOCAL oServer, nCont, cRetorno
   LOCAL cSoapAction

   oServer := win_OleCreateObject( "MSXML2.ServerXMLHTTP.6.0" )
   IF cCertCN != NIL
      oServer:setOption( 3, "CURRENT_USER\MY\" + cCertCN )
   ENDIF
   oServer:Open( "POST", cURL, .F. )
   IF cSoapAction != NIL .AND. ! Empty( cSoapAction )
      oServer:SetRequestHeader( "SOAPAction", cSoapAction )
   ENDIF
   oServer:SetRequestHeader( "Content-Type", "application/json" )
   oServer:Send( cJSON )
   oServer:WaitForResponse( 5000 )
   cRetorno := oServer:ResponseBody()

   RETURN cRetorno
Alguém pode ajudar?

webservice json deliveryapp

Enviado: 28 Mai 2020 11:16
por ANDRIL
José na construção de cJSON tem um { a mais o resto aparentemente esta correto. Conseguiu se comunicar com o server ?

webservice json deliveryapp

Enviado: 28 Mai 2020 12:36
por lwinter
Tente desta forma. Acho mais pratico e evita erros de formatacao do json.
so nao consegui testar pois apresentou erro de compilacao por nao saber qual lib incluir.

webservice json deliveryapp

Enviado: 28 Mai 2020 12:54
por lwinter
Esqueci de dizer, caso a api retornar um outro json, voce pode utilizar a funcao hb_jsondecode ().

Exemplo:
dictJson = {}
hb_jsondecode (json, @dictJson)
// pronto ja pode usar conforme o retorno do webservice
? dictJson ['pedido']['numero'] // exemplo qualquer

Bem mais facil do que trabalhar com XML nao é verdade?

webservice json deliveryapp

Enviado: 28 Mai 2020 14:04
por Itamar M. Lins Jr.
Ola!

Código: Selecionar todos

C:\fontes\teste>hbmk2 testapp.prg hbwin.hbc                                                            
hbmk2: Processando script local: hbmk.hbm                                                                              
Harbour 3.2.0dev (r2004201301)                                                                                         
Copyright (c) 1999-2020, https://harbour.github.io/                                                                    
Compiling 'testapp.prg'...                                                                                              
Lines 47, Functions/Procedures 2                                                                                       
Generating C source output to 'C:\Users\RICARD~1\AppData\Local\Temp\hbmk_wehtc5.dir\testapp.c'... Done.                                                                                                                                         C:\fontes\teste>testapp                                                                                            
     
Error WINOLE/1007  ParΓmetro incorreto.                                                                                  (0x80070057): msxml6.dll (DOS Error -2147352567)                                                                       Called from WIN_OLEAUTO:OPEN(0)                                                                                         Called from MICROSOFTXMLSOAPPOST(36)                                                                                    Called from MAIN(21)
C:\fontes\teste>                                                                                                        
Outro assunto. Não sei pq tanta dificuldade que estão encontrando para compilar usando o hbmk2
Ele mesmo informa o que falta.
Por exemplo:
>hbmk2 testapp.prg

Código: Selecionar todos

hbmk2: Dica: Adicionar opção 'hbwin.hbc' faltando nas funções:
       win_oleCreateObject()
>hbmk2 testapp.prg hbwin.hbc //resolvido!

Saudações,
Itamar M. Lins Jr.

webservice json deliveryapp

Enviado: 28 Mai 2020 14:22
por JoséQuintas
Como eu disse no início, está incompleto.
Com certeza nem precisei testar, porque já sei que está incompleto e não funciona.

O mínimo necessário seria o endereço de internet.

Mas... e aí?
É igual XML, onde o webservice faz o manual automático com tudo que precisa?
O manual tá incompleto e tem que procurar em outro lugar?
Existe alguma opção pra json, igual tem em xml, que é só adicionar ?wsdl ?

webservice json deliveryapp

Enviado: 28 Mai 2020 14:42
por lwinter
Nossa Itamar nem tinha visto esta dica do hbmk2. Obrigado agora vai ficar mais facil.
Preciso me acostumar a usar o -find tambem.

Agora compilou e esta dando o mesmo erro. Dai ja nao posso ajudar. Mas espero que a questao semantica do json tenha ajudado.

webservice json deliveryapp

Enviado: 28 Mai 2020 15:57
por JoséQuintas
lwinter escreveu:Mas espero que a questao semantica do json tenha ajudado.
Não gosto de variável hash.
Preferi adaptar minha rotina do XML pra json.

Código: Selecionar todos


PROCEDURE Main

   LOCAL cURL, aList, cCertCN := NIL, cSoapAction := NIL, cRetorno

   cURL  := "https://deliveryapp.neemo.com.br/api/integration/v1/order"
   aList := { ;
      { "token_account", "xxx" }, ;
      { "limit",  10 }, ;
      { "page", 1 }, ;
      { "modified", "2020-05-28 08:00:00" }, ;
      { "status", 0 }, ;
      { "sort", "[id][asc]" }, ;
      { "created_at", "2020-05-28 08:00:00" } }

   cRetorno := MicrosoftXMLSoapPost( cURL, ListToJason( aList ), cSoapAction, cCertCN )
   ? cRetorno
   Inkey(0)

   RETURN

FUNCTION MicrosoftXmlSoapPost( cURL, cJSON, cSoapAction, cCertCN )

   LOCAL oServer, cRetorno

   oServer := win_OleCreateObject( "MSXML2.ServerXMLHTTP.6.0" )
   IF cCertCN != NIL
      oServer:setOption( 3, "CURRENT_USER\MY\" + cCertCN )
   ENDIF
   oServer:Open( "POST", cURL, .F. )
   IF cSoapAction != NIL .AND. ! Empty( cSoapAction )
      oServer:SetRequestHeader( "SOAPAction", cSoapAction )
   ENDIF
   oServer:SetRequestHeader( "Content-Type", "application/json" )
   oServer:Send( cJSON )
   oServer:WaitForResponse( 2000 )
   cRetorno := oServer:ResponseBody()

   RETURN cRetorno

FUNCTION ListToJason( aList )

   LOCAL oElement, cJason := ""

   cJason += "{"
   FOR EACH oElement IN aList
      cJason += ["] + oElement[ 1 ] + [": ] + JasonValue( oElement[ 2 ] ) + ;
         iif( oElement:__EnumIsLast(), "}", "," )
   NEXT

   RETURN cJason

FUNCTION JasonValue( xValue )

   IF ValType( xValue ) == "N"
      RETURN Ltrim( Str( xValue ) )
   ENDIF

   RETURN ["] + Transform( xValue, "" ) + ["]
Aqui é um exemplo que já comentei: sabendo o básico se vira com o avançado.... rs
Pelo menos conecta, mas ainda não funcionou.
Com certeza usei um token válido, o xxx foi só pra postar.
json.png
json.png (11.01 KiB) Exibido 6324 vezes

webservice json deliveryapp

Enviado: 28 Mai 2020 16:18
por JoséQuintas
Tem mais uma coisa:

https://deliveryapp.neemo.com.br/api/v1/order
{"error":"access_token is missing"}
mas..... no json é token_account
e aí mostra access_token

Talvez aquelas variáveis de ambiente do navegador, ou algum login em outra tela?

webservice json deliveryapp

Enviado: 29 Mai 2020 14:36
por JoséQuintas
Resolvido.

Os caras tinham passado token ERRADO.
Tá aí pra quem precisar, só colocar o token certo.
Para os demais, só olhar a página de documentação do webservice.

Código: Selecionar todos

PROCEDURE Main

   LOCAL cURL, aList, cCertCN := NIL, cSoapAction := NIL, cRetorno, cToken

   cURL   := "https://deliveryapp.neemo.com.br/api/integration/v1/order"
   cToken := "xxx"
   aList := { ;
      { "token_account", cToken }, ;
      { "limit",  10 } }
      // outras opcoes
      //{ "page", 1 }, ;
      //{ "modified", "2020-05-28 08:00:00" }, ;
      //{ "status", 0 }, ;
      //{ "sort", "[id][asc]" }, ;
      //{ "created_at", "2020-05-28 08:00:00" } }

   cRetorno := MicrosoftXMLSoapPost( cURL, ListToJason( aList ), cToken, cSoapAction, cCertCN )
   ? cRetorno
   Inkey(0)

   RETURN

FUNCTION MicrosoftXmlSoapPost( cURL, cJSON, cToken, cSoapAction, cCertCN )

   LOCAL oServer, cRetorno

   ( cToken )
   oServer := win_OleCreateObject( "MSXML2.ServerXMLHTTP" )
   IF cCertCN != NIL
      oServer:setOption( 3, "CURRENT_USER\MY\" + cCertCN )
   ENDIF
   oServer:Open( "POST", cURL, .F. )
   IF cSoapAction != NIL .AND. ! Empty( cSoapAction )
      oServer:SetRequestHeader( "SOAPAction", cSoapAction )
   ENDIF
   oServer:SetRequestHeader( "Content-Type", "application/json" )
   oServer:Send( cJSON )
   oServer:WaitForResponse( 2000 )
   cRetorno := oServer:ResponseBody()

   RETURN cRetorno

FUNCTION ListToJason( aList )

   LOCAL oElement, cJason := ""

   cJason += "{"
   FOR EACH oElement IN aList
      cJason += ["] + oElement[ 1 ] + [": ] + JasonValue( oElement[ 2 ] ) + ;
         iif( oElement:__EnumIsLast(), "}", "," )
   NEXT

   RETURN cJason

FUNCTION JasonValue( xValue )

   IF ValType( xValue ) == "N"
      RETURN Ltrim( Str( xValue ) )
   ENDIF

   RETURN ["] + Transform( xValue, "" ) + ["]

webservice json deliveryapp

Enviado: 29 Mai 2020 20:21
por JoséQuintas
Agora em classe, pra adicionar os outros métodos depois.
Acabei chamando cTxt, porque acaba sendo txt mesmo....
A rotina que criei só serve pro json simples, provavelmente vai virar hash array depois, e simplificar mais o fonte.

Código: Selecionar todos

#include "hbclass.ch"

PROCEDURE Main

   LOCAL oWeb := DeliveryAppClass():New()

   oWeb:cToken := "xxx"
   oWeb:OrderPost( 10 )
   ? oWeb:cTxtRetorno
   Inkey(0)

   RETURN

CREATE CLASS DeliveryAppClass

   VAR cURL        INIT ""
   VAR cToken      INIT ""
   VAR cTxtEnvio   INIT ""
   VAR cTxtRetorno INIT ""
   VAR cURLBase    INIT "https://deliveryapp.neemo.com.br/api/integration/"

   METHOD OrderPost( nLimit, nPage, cModified, nStatus, cSort, cCreated )
   METHOD MicrosoftPost()
   METHOD ListToJason( aList )
   METHOD JasonValue( xValue )
   ENDCLASS

METHOD OrderPost( nLimit, nPage, cModified, nStatus, cSort, cCreated ) CLASS DeliveryAppClass

   LOCAL aList

   aList := {}
   AAdd( aList, { "token_account", ::cToken } )
   IF ! Empty( nLimit )
      AAdd( aList, { "limit", 10 } )
   ENDIF
   IF ! Empty( nPage )
      AAdd( aList, { "page", nPage } )
   ENDIF
   IF ! Empty( cModified )
      AAdd( aList, { "modified", cModified } )
   ENDIF
   IF ! Empty( nStatus )
      AAdd( aList, { "status", nStatus } )
   ENDIF
   IF ! Empty( cSort )
      AAdd( aList, { "sort", "[id][asc]" } )
   ENDIF
   IF ! Empty( cCreated )
      AAdd( aList, { "created", cCreated } )
   ENDIF
   ::cTxtEnvio := ::ListToJason( aList )
   ::cURL      := ::cURLBase + "v1/order"
   ::MicrosoftPost()

   RETURN ::cTxtRetorno

METHOD MicrosoftPost() CLASS DeliveryAppClass

   LOCAL oServer

   oServer := win_OleCreateObject( "MSXML2.ServerXMLHTTP" )
   oServer:Open( "POST", ::cURL, .F. )
   oServer:SetRequestHeader( "Content-Type", "application/json" )
   oServer:Send( ::cTxtEnvio )
   oServer:WaitForResponse( 2000 )
   ::cTxtRetorno := oServer:ResponseBody()

   RETURN NIL

METHOD ListToJason( aList ) CLASS DeliveryAppClass

   LOCAL oElement, cJason := ""

   cJason += "{"
   FOR EACH oElement IN aList
      cJason += ["] + oElement[ 1 ] + [": ] + ::JasonValue( oElement[ 2 ] ) + ;
         iif( oElement:__EnumIsLast(), "}", "," )
   NEXT

   RETURN cJason

METHOD JasonValue( xValue ) CLASS DeliveryAppClass

   IF ValType( xValue ) == "N"
      RETURN Ltrim( Str( xValue ) )
   ENDIF

   RETURN ["] + Transform( xValue, "" ) + ["]

webservice json deliveryapp

Enviado: 29 Mai 2020 20:32
por JoséQuintas
E usando hash

Código: Selecionar todos

#include "hbclass.ch"

PROCEDURE Main

   LOCAL oWeb := DeliveryAppClass():New()

   oWeb:cToken := ""
   oWeb:OrderPost( 10 )
   ? oWeb:cTxtRetorno
   Inkey(0)

   RETURN

CREATE CLASS DeliveryAppClass

   VAR cURL        INIT ""
   VAR cToken      INIT ""
   VAR cTxtEnvio   INIT ""
   VAR cTxtRetorno INIT ""
   VAR cURLBase    INIT "https://deliveryapp.neemo.com.br/api/integration/"

   METHOD OrderPost( nLimit, nPage, cModified, nStatus, cSort, cCreated )
   METHOD MicrosoftPost()
   ENDCLASS

METHOD OrderPost( nLimit, nPage, cModified, nStatus, cSort, cCreated ) CLASS DeliveryAppClass

   LOCAL aList

   aList := hb_hash()
   aList[ "token_account" ] := ::cToken
   IF ! Empty( nLimit )
      aList[ "limit" ] := nLimit
   ENDIF
   IF ! Empty( nPage )
      aList[ "page" ] := nPage
   ENDIF
   IF ! Empty( cModified )
      aList[ "modified" ] := cModified
   ENDIF
   IF ! Empty( nStatus )
      aList[ "status" ] := nStatus
   ENDIF
   IF ! Empty( cSort )
      aList[ "sort" ] := "[id][asc]"
   ENDIF
   IF ! Empty( cCreated )
      aList[ "created" ] := cCreated
   ENDIF
   ::cTxtEnvio := hb_JsonEncode( aList )
   ::cURL      := ::cURLBase + "v1/order"
   ::MicrosoftPost()

   RETURN ::cTxtRetorno

METHOD MicrosoftPost() CLASS DeliveryAppClass

   LOCAL oServer

   oServer := win_OleCreateObject( "MSXML2.ServerXMLHTTP" )
   oServer:Open( "POST", ::cURL, .F. )
   oServer:SetRequestHeader( "Content-Type", "application/json" )
   oServer:Send( ::cTxtEnvio )
   oServer:WaitForResponse( 2000 )
   ::cTxtRetorno := oServer:ResponseBody()

   RETURN NIL

webservice json deliveryapp

Enviado: 01 Jun 2020 22:34
por JoséQuintas
IMPORTANTE

Falhou usando Harbour 3.2 de 2014, mas o problema foi com hb_jsonDecode()
Ao invés de retornar o HASH estava retornando um NÚMERO na conversão do json.
Testado com Harbour 3.2 baixado hoje, versão nightly de 2020, converteu o json direito.

No 3.4 sem problemas.

webservice json deliveryapp

Enviado: 17 Jun 2020 09:25
por JoséQuintas
Só adicionais:

Se no manual do webservice indicar PUT, significa que na comunicação também é PUT
Se no manual indicar PATH, significa que faz parte da URL, e não do conteúdo

webservice json deliveryapp

Enviado: 04 Jul 2020 07:48
por anupam
Hello Experts,

how can I convert the below curl syntax using MSXML2.ServerXMLHTTP

curl -X POST https://content.dropboxapi.com/2/files/upload
--header "Authorization: Bearer ii2YJ0ys4gAAAAAAAAAADxxxxxxxxxxxxxxxxx"
--header "Dropbox-API-Arg: {\"path\": \"/Homework/test.pdf\",\"mode\": \"add\",\"autorename\": true,\"mute\": false,\"strict_conflict\": false}"
--header "Content-Type: application/octet-stream"
--data-binary @test.pdf


Thanks & Regards.