Some way to get the price of the dollar

Asked

Viewed 7,965 times

5

  • Just updating, API facinha: https://docs.awesomeapi.com.br/api-de-moedas

5 answers

5

You can use the Central Bank website:

http://blog.tiagocrizanto.com/configuracoes-do-webservice-do-banco-central-cotacoes-diversas/

I believe I’m more reliable and because it’s a state service, you won’t have the risk of a developer taking it off the air when you want.

Here is an example of how to implement:

<?php

// Mostra erros
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 1);
ini_set('default_socket_timeout', 300);

$debug = true;
$result = null;
$error = null;
$exception = null;
$xml = null;


// Definição da localização do arquivo WSDL
$wsdl = 'https://www3.bcb.gov.br/sgspub/JSP/sgsgeral/FachadaWSSGS.wsdl';

// Soapclient PHP 5.0 ou Superior ( SOAP 1.1 e SOAP 1.2 )
$client = new Soapclient($wsdl, array('trace' => 1, 'exceptions' => true));



$xml =' <?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://publico.ws.casosdeuso.sgs.pec.bcb.gov.br" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<ns1:getUltimoValorVO>
<in xsi:type="xsd:long">'. '206'.'</in>
</ns1:getUltimoValorVO>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>';
// Chamada do método SOAP
try {
    //$serie = 206;
    $result = $client->getUltimoValorVO($xml, $serie);

    if (is_object($result)) {
        if (!$result->getUltimoValorVOResult) {
            $error = $result->getUltimoValorVOError;
        }
    }

    if (is_soap_fault($result)) {
        trigger_error("SOAP Fault: (faultcode: {$result->faultcode}, faultstring: {$result->faultstring})", E_USER_ERROR);
    }

} catch (Exception $e) {
    $exception = $e->getMessage();
}

if ($debug) {
    echo '<h2>Request Headers</h2>';
    echo '<pre>' . htmlspecialchars($client->__getLastRequestHeaders()) . '</pre>';

    echo '<h2>Response Headers</h2>';
    echo '<pre>' . htmlspecialchars($client->__getLastResponseHeaders()) . '</pre>';

    echo '<h2>Request</h2>';
    echo '<pre>' . htmlspecialchars($client->__getLastRequest()) . '</pre>';

    echo '<h2>Response</h2>';
    echo '<pre>' . htmlspecialchars($client->__getLastResponse()) . '</pre>';

    echo '<h2>Debug</h2>';
    echo '<pre>' . var_dump($result) . '</pre>';

    echo '<h2>Exception</h2>';
    echo '<pre>' . var_dump($exception) . '</pre>';

    echo '<h2>Error</h2>';
    echo '<pre>' . $error . '</pre>';
}

?>
  • also recommend taking direct from the central bank

5


You can use the Yahoo YQL, through the Query: select Rate from yahoo.finance.xchange where pair in ("USDBRL"), for example, the USDBRL must be set by what you want, this case will be returned 3.1141, it seems to be updated in real time.


You need to get the answer as follows:

http://query.yahooapis.com/v1/public/yql?
q=select%20Rate%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22USDBRL%22)
&format=json
&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys

Basically use:

function converterMoeda(string $de, string $para){

    $parametros = [
        'q' => 'select Rate from yahoo.finance.xchange where pair = "'.$de.$para.'"',
        'env' => 'store://datatables.org/alltableswithkeys',
        'format' => 'json'
    ];

    $parametros = http_build_query($parametros, '', '&', PHP_QUERY_RFC3986);

    $ch = curl_init('http://query.yahooapis.com/v1/public/yql?'.$parametros);

    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_FAILONERROR => 1
    ]);

    if($resultado = curl_exec($ch)){

        $resultado = json_decode($resultado, true);

        return $resultado['query']['results']['rate']['Rate'];

    }

    return false;

}

if($resultado = converterMoeda('USD', 'BRL')){
   echo $resultado;
}

At this point the result is 3,1141, but logically it will change. It supports multiple currencies, including Bitcoin, you can use BTCBRL and will return, now, 3982.2249.

5

Fixer.io

To Fixer.io which is a free and simple to use API.

Giving a GET at the address http://api.fixer.io/latest?base=USD&symbols=BRL you have a JSON as a result:

{"base":"USD","date":"2017-03-03","rates":{"BRL":3.1311}}

The database is from European Central Bank and is updated once a day.

currencylayer

Another option is the Currency Layer. You have paid and free plans, regardless of which registration you need to use. Free is limited to 1000 accesses per month and values are updated every hour.

Other plans here: https://currencylayer.com/product

  • This would be great if it wasn’t updated only once a day. Do you know others for free? Some paid would not be unfeasible depending on the charged, you know also?

  • updated the response

  • The Fixer.io no longer allows consultation by base currency USD, the free version is now only with base currency EUR.

2

Here is another example for using the BACEN web service.

Simply instantiate the BACEN class and use the getUltimoValorXML function for the last quotation or getValue for quotation on a specific date.

Remembering that the code for the dollar is 1.

class SOAP extends SOAPClient {

    private static $bacen_instance;

    private function SOAP($bacen_url) {
        return parent::__construct($bacen_url, array('soap_version' => SOAP_1_1));
    }

    public static function getInstance($bacen_dados) {
        if (empty(self::$bacen_instance))
            self::$bacen_instance = new SOAP($bacen_dados);

        return self::$bacen_instance;
    }

    public function call($teste, $bacen_configuracoes) {
        return parent::__soapCall($teste, $bacen_configuracoes);
    }

}


class BACEN {
    private $bacen_url = "https://www3.bcb.gov.br/sgspub/JSP/sgsgeral/FachadaWSSGS.wsdl";

    /**
     *Função para acessar soap
     * @access public
     * @param array contendo os itens necessários para o retorno do webservice
     * @return objeto XML 
     */
    public function soap($teste, $bacen_conf){
        $bacen_cliente = SOAP::getInstance($this->bacen_url);

        $bacen_resultado = $bacen_cliente->call($teste, $bacen_conf);
        return ($bacen_resultado);        
    }   

    /**
     *

     */
    public function getUltimoValorXML($bacen_cod_moeda) {
        $bacen_conf[0] = 'getUltimoValorXML';
        $bacen_conf[1] = array('in0' => $bacen_cod_moeda);
        return $this->soap($bacen_conf);
    }

       /**
     *

     */
    public function getValor($bacen_cod_moeda, $databr) {
        $bacen_conf['in0'] = $bacen_cod_moeda;
        $bacen_conf['in1'] = $databr;
        $retorno = $this->soap('getValor', $bacen_conf);
        return $retorno;
    }
}

2

Using the Bacen API:

$hoje = (new DateTime())->format('m-d-Y');
$uri = 'https://olinda.bcb.gov.br/olinda/servico/PTAX/versao/v1/odata/CotacaoDolarDia(dataCotacao=@dataCotacao)?@dataCotacao=\''.$hoje.'\'&$top=100&$format=json&$select=cotacaoCompra,cotacaoVenda,dataHoraCotacao';
$jsonData = json_decode(file_get_contents($uri));
var_dump($jsonData);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.