# 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 da B3.

***

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 da B3.
full: false
keywords: brapi, api, php, curl, cotações, B3
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
-----------

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}?token={$token}";

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$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}?token={$token}";
    
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 10);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    
    $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}?token={$this->token}";
        return $this->request($url);
    }
    
    public function getMultipleQuotes($tickers) {
        $tickersParam = implode(',', $tickers);
        $url = "{$this->baseUrl}/quote/{$tickersParam}?token={$this->token}";
        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'
        ]);
        
        $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}?token={$token}";
    $response = wp_remote_get($url, ['timeout' => 10]);
    
    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)
                ->get("{$this->baseUrl}/quote/{$ticker}", [
                    'token' => $this->token
                ]);
            
            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)
            ->get("{$this->baseUrl}/quote/{$tickersParam}", [
                'token' => $this->token
            ]);
        
        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)


