Created
August 28, 2022 17:17
-
-
Save n3omaster/fb0246ca657c00be6aeba5fd77718496 to your computer and use it in GitHub Desktop.
Get Bitcoin Price from CoinMarketCap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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