Page 1 of 1

Login by api

Posted: Wed May 29, 2019 5:14 pm
by roh.drigo
I need to login according to the Tray layout,

Request authorization
The authorization code is provided through the Tray Commerce authentication server.

To allow access to the information and resources of the account, the client must be redirected to the browser-based url. (****** WILL HOW TO HOW TO DO NOT OPEN THE BROWSER *****)
Tray Commerce is responsible for receiving confirmation of the customer's authorization and providing the authorization code to the application.

Url for authentication: https: // {host_domain} /auth.php

Supported HTTP "GET" Parameters for Authentication:
response_type: Request type (Default value code)
consumer_key: Identification of the application with Tray Commerce.
callback: Callback URL that will be redirected after authorization

Then get the return of the url to return, according to the Tray tutorial:

After authorization, the client is redirected to the URL specified in the callback parameter passed at the time of authorization (in the example above it is the URL http: // localhost / tray / callback / auth /), where it would be, following the previous examples, the following form this URL:

https: // {domain_database} /auth.php?response_type=code&consumer_key=2r9dg7sgdb&callback=https:// {url_de_callback}

So you can capture the information from this URL and use it to configure it in your application, with the code and api_address parameters most important in the integration process.

With the code and api_address, you must use the Generate Access Key API to generate the value of the access_token used in the other APIs. It is extremely important to store all the return information of this API as it will be used constantly during communication with the API. Tray

Code: Select all

    cUrl := 'https://trayparceiros.commercesuite.com.br/auth.php?'+'response_type=code&consumer_key='+consumerkey+'&callback='+wcallback
    aResult:= ""
    cXml:= [{"usuario":"conta_teste","senha":"senha"}]
    oHttp:= CreateObject( 'MSXML2.ServerXMLHTTP.6.0' )
    oHttp:Open( "GET" , cUrl, .F. )
    oHttp:setRequestHeader("Content-Type","application/json")
    oHttp:Send(cXml)
    IF oHttp:status <> 200 // COM ERRO
       MsgStop( Alltrim(Str(oHttp:status)) +" - "+ Alltrim(oHttp:ResponseText) , "Erro na requisição")
       HB_MemoWrit('erro.html', oHttp:ResponseText) // coloquei apenas para visualizar o retorno em caso de erro
       RETURN NIL
    ENDIF
    x:= oHttp:ResponseText
    MSGINFO(x,"OK")
 

Re: Login by api

Posted: Wed May 29, 2019 7:19 pm
by leandro
Rodrigo good afternoon

I do not understand what the question is :shock: , these days I have had the need to consume web services, for this I have been using the curl class of xharbour, and I do it in the same way that you are doing it.

On the other hand, the theme of creating the webservice, is not built from harbor, but I have one in php and communicates perfectly with FW.

Code: Select all

<?php
//DATOS DE AUTORIZACION BASICA DE CABECERA
$auto_usuario = $_SERVER["PHP_AUTH_USER"];
$auto_clave = $_SERVER["PHP_AUTH_PW"];

//recogemos los datos que vienen en el json
$datos = json_decode(file_get_contents("php://input"),true);
$nit_autorizado = $datos["nit"];

//incluimos la conexion con la base de datos
include("conecta.php");
$query = "SELECT AUT.*,CLI.identificacion,CLI.estado FROM autorizados AUT LEFT JOIN clientes 
            CLI ON AUT.id_cliente=CLI.id_cliente WHERE CLI.identificacion='".$auto_usuario."'";

$sqls = $conexion->prepare($query);
$sqls->execute();
$nro_reg = count($sqls->fetchall());
if($nro_reg==0){
    $retorno["error"] = "Error de Autenticacion";
    $retorno["autorizado"]=false;
}else{
    $sql = $conexion->prepare($query);
    $sql->execute();
    while($row = $sql->fetch()){
        $clave_db = $row['clave']; 
        if($clave_db==$auto_clave){
            $retorno["estado"]=$row['estado'];
            $retorno["error"]="";
            $retorno["nit_json"]=$nit_autorizado;
            $retorno["autorizado"]=true;
        }else{
            $retorno["error"] = "Error de Autenticacion";
            $retorno["autorizado"]=false;
        }
    }       
}
$conexion = null;
echo json_encode($retorno);
?>
 

Re: Login by api

Posted: Thu May 30, 2019 3:04 am
by roh.drigo
I could not authenticate with this code, does it have to pass as consuming with the curl class the code?

Re: Login by api

Posted: Thu May 30, 2019 2:13 pm
by leandro
Hello good day

With this code I managed to identify myself, send json files to the web service and receive a response.

Code: Select all

function consultar_documento()

    local user := "myuser"
    local pass := "mypass"
    local cBas64 := hb_base64encode(user+":"+pass,len(user+":"+pass))
    
    local encabezado := {=>}
    local documento := {=>}
    local final := {=>}
    local enviar
    local respuesta
    local aHasRes
    local elemento

    //Encabezado factura
    encabezado["identifica"] = "12456789"
    encabezado["numero"] =  125

    //agregamos la información al json documento
    documento["encabezado"] = encabezado
    
    //creamos el json con el documento final
    final["documento"] = documento
    enviar := hb_jsonEncode( final )

    ohttp := CreateObject( "MSXML2.XMLHTTP" )
    ohttp:Open( "POST" ,"https://myurl/service",.F.)
    oHttp:SetRequestHeader("cache-control", "no-cache")
    ohttp:SetRequestHeader("content-type", "application/json" )
    ohttp:SetRequestHeader("authorization", "Basic "+cBas64 )
    TRY
      ohttp:Send( enviar )
    CATCH
        msginfo("No Se Pudo Enviar Documento JSON","Intente Nuevamente")
        return .t.
    END
    response:=ohttp:responseText
    
    aHasRes := hash()
    hb_jsondecode(response ,@aHasRes) //Parse JSON to hash
    
    elemento := aHasRes["error"] //control del error en este web service
    xBrowse(aHasRes)

return nil

 

Re: Login by api

Posted: Wed Jun 05, 2019 6:56 pm
by roh.drigo
Thanks, leandro.