Skip to content

Instantly share code, notes, and snippets.

@n3omaster
Created August 28, 2022 17:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save n3omaster/fb0246ca657c00be6aeba5fd77718496 to your computer and use it in GitHub Desktop.
Save n3omaster/fb0246ca657c00be6aeba5fd77718496 to your computer and use it in GitHub Desktop.
Get Bitcoin Price from CoinMarketCap
<?php
namespace App\Http\Controllers\Api;
use App\Models\Bitcoin;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Cache;
class BitcoinController extends Controller
{
private static $url = 'https://pro-api.coinmarketcap.com/v1/';
private static $token = 'YOUR-TOKEN';
/**
* Update BITCOIN price
*/
public static function price()
{
// CoinmarketCap prices
$endpoint = 'cryptocurrency/quotes/latest?symbol=BTC&CMC_PRO_API_KEY=' . self::$token;
$response = Http::get(self::$url . $endpoint);
$data = json_decode($response->body(), true);
// Save data to de Bitcoin DB
if (isset($data['data']['BTC']['quote']['USD']['price'])) {
$btc = $data['data']['BTC']['quote']['USD']['price'];
$btc = round($btc, 2);
// Update bitcoin table price
$bitcoin = Bitcoin::first();
// If no bitcoin price in the table, create new one
if (!$bitcoin) {
$bitcoin = Bitcoin::create([
'price' => $btc,
]);
} else {
$bitcoin->price = $btc;
$bitcoin->save();
}
} else {
$btc = $bitcoin = Bitcoin::first()->price;
}
// Now save to cache
Cache::forever('btc', $btc);
return $btc;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment