# PHP
URL: /docs/examples/php.mdx

Integre a API brapi.dev em suas aplicações PHP usando cURL. Exemplos práticos para buscar cotações de ações brasileiras.

***

title: 'PHP'
description: >-
Integre a API brapi.dev em suas aplicações PHP usando cURL. Exemplos práticos
para buscar cotações de ações brasileiras.
full: false
keywords: brapi, api, php, curl, cotações, ações brasileiras
openGraph:
title: Integração PHP - brapi.dev
description: Exemplos de integração usando PHP e cURL
type: website
locale: pt\_BR
lastUpdated: '2025-10-12T17:30:00.000Z'
lang: pt-BR
howToSteps:

* name: 'Inicialize uma requisição cURL'
  text: 'Use curl\_init() com a URL [https://brapi.dev/api/quote/PETR4](https://brapi.dev/api/quote/PETR4), configure CURLOPT\_RETURNTRANSFER como true e adicione o header Authorization: Bearer SEU\_TOKEN via CURLOPT\_HTTPHEADER.'
* name: 'Execute a requisição e obtenha a resposta'
  text: 'Execute curl\_exec(), verifique o código HTTP com curl\_getinfo() e feche a conexão com curl\_close().'
* name: 'Parse o JSON e acesse os dados'
  text: 'Use json\_decode($response, true) para converter a resposta em array PHP e acesse $data\["results"]\[0]\["regularMarketPrice"].'
* name: 'Implemente tratamento de erros'
  text: 'Verifique curl\_error() e o código HTTP para tratar erros de conexão e respostas inválidas adequadamente.'
* name: 'Opcionalmente, integre com WordPress ou Laravel'
  text: 'Use wp\_remote\_get() no WordPress com transients para cache, ou Http::get() no Laravel com Cache::remember().'
  howToTools:
* 'PHP 7.4+'
* 'cURL'
* 'Editor de código'
  howToSupplies:
* 'Servidor com PHP instalado'
* 'Conta brapi.dev'
* 'Token de API brapi.dev'

***

Integre a API brapi.dev em suas aplicações PHP usando cURL ou file\_get\_contents.

## Usando cURL

```php
<?php
$token = 'SEU_TOKEN';
$ticker = 'PETR4';
$url = "https://brapi.dev/api/quote/{$ticker}";

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
    "Authorization: Bearer {$token}"
]);
$response = curl_exec($curl);
curl_close($curl);

$data = json_decode($response, true);
print_r($data);
?>
```

## Com Tratamento de Erros

```php
<?php
function getQuote($ticker, $token) {
    $url = "https://brapi.dev/api/quote/{$ticker}";
    
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 10);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, [
        "Authorization: Bearer {$token}"
    ]);
    
    $response = curl_exec($curl);
    $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    $error = curl_error($curl);
    curl_close($curl);
    
    if ($error) {
        throw new Exception("Erro cURL: {$error}");
    }
    
    if ($httpCode !== 200) {
        throw new Exception("HTTP {$httpCode}: {$response}");
    }
    
    return json_decode($response, true);
}

try {
    $data = getQuote('PETR4', 'SEU_TOKEN');
    $quote = $data['results'][0];
    echo "{$quote['symbol']}: R$ {$quote['regularMarketPrice']}\n";
} catch (Exception $e) {
    echo "Erro: {$e->getMessage()}\n";
}
?>
```

## Classe Cliente

```php
<?php
class BrapiClient {
    private $baseUrl = 'https://brapi.dev/api';
    private $token;
    
    public function __construct($token) {
        $this->token = $token;
    }
    
    public function getQuote($ticker) {
        $url = "{$this->baseUrl}/quote/{$ticker}";
        return $this->request($url);
    }
    
    public function getMultipleQuotes($tickers) {
        $tickersParam = implode(',', $tickers);
        $url = "{$this->baseUrl}/quote/{$tickersParam}";
        return $this->request($url);
    }
    
    private function request($url) {
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        curl_setopt($curl, CURLOPT_HTTPHEADER, [
            'User-Agent: PHP BrapiClient/1.0',
            "Authorization: Bearer {$this->token}"
        ]);
        
        $response = curl_exec($curl);
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        $error = curl_error($curl);
        curl_close($curl);
        
        if ($error) {
            throw new Exception("Erro cURL: {$error}");
        }
        
        if ($httpCode !== 200) {
            throw new Exception("HTTP {$httpCode}");
        }
        
        return json_decode($response, true);
    }
}

// Uso
$client = new BrapiClient('SEU_TOKEN');

try {
    $data = $client->getQuote('PETR4');
    $quote = $data['results'][0];
    echo "{$quote['symbol']}: R$ {$quote['regularMarketPrice']}\n";
} catch (Exception $e) {
    echo "Erro: {$e->getMessage()}\n";
}
?>
```

## WordPress Integration

```php
<?php
// Adicione ao functions.php do seu tema

function brapi_get_stock_price($ticker) {
    $token = get_option('brapi_token');
    if (!$token) {
        return 'Token não configurado';
    }
    
    $transient_key = 'brapi_quote_' . $ticker;
    $cached = get_transient($transient_key);
    
    if ($cached !== false) {
        return $cached;
    }
    
    $url = "https://brapi.dev/api/quote/{$ticker}";
    $response = wp_remote_get($url, [
        'timeout' => 10,
        'headers' => [
            'Authorization' => "Bearer {$token}",
        ],
    ]);
    
    if (is_wp_error($response)) {
        return 'Erro ao buscar dados';
    }
    
    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);
    
    if (isset($data['results'][0]['regularMarketPrice'])) {
        $price = $data['results'][0]['regularMarketPrice'];
        set_transient($transient_key, $price, 60); // Cache por 60 segundos
        return $price;
    }
    
    return 'Cotação indisponível';
}

// Shortcode
function brapi_stock_price_shortcode($atts) {
    $atts = shortcode_atts([
        'ticker' => 'PETR4',
    ], $atts);
    
    $price = brapi_get_stock_price($atts['ticker']);
    
    if (is_numeric($price)) {
        return 'R$ ' . number_format($price, 2, ',', '.');
    }
    
    return $price;
}
add_shortcode('brapi_cotacao', 'brapi_stock_price_shortcode');

// Uso no WordPress: [brapi_cotacao ticker="PETR4"]
?>
```

## Laravel

```php
<?php
// app/Services/BrapiService.php
namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Cache;

class BrapiService
{
    private $baseUrl = 'https://brapi.dev/api';
    private $token;
    
    public function __construct()
    {
        $this->token = config('services.brapi.token');
    }
    
    public function getQuote(string $ticker)
    {
        $cacheKey = "quote_{$ticker}";
        
        return Cache::remember($cacheKey, 60, function () use ($ticker) {
            $response = Http::timeout(10)
                ->withToken($this->token)
                ->get("{$this->baseUrl}/quote/{$ticker}");
            
            if ($response->failed()) {
                throw new \Exception('Failed to fetch quote');
            }
            
            return $response->json();
        });
    }
    
    public function getMultipleQuotes(array $tickers)
    {
        $tickersParam = implode(',', $tickers);
        
        $response = Http::timeout(10)
            ->withToken($this->token)
            ->get("{$this->baseUrl}/quote/{$tickersParam}");
        
        if ($response->failed()) {
            throw new \Exception('Failed to fetch quotes');
        }
        
        return $response->json();
    }
}

// config/services.php
return [
    'brapi' => [
        'token' => env('BRAPI_TOKEN'),
    ],
];

// Controller
namespace App\Http\Controllers;

use App\Services\BrapiService;

class StockController extends Controller
{
    public function show($ticker, BrapiService $brapi)
    {
        $data = $brapi->getQuote($ticker);
        $quote = $data['results'][0] ?? null;
        
        return view('stock.show', compact('quote'));
    }
}
?>
```

## Próximos Passos

* Explore [outros exemplos](/docs/examples)
* Veja a [documentação completa](/docs)
* Confira os [endpoints disponíveis](/docs/acoes)


