Added gold currency api

This commit is contained in:
m.razaghi
2026-08-15 23:43:51 +03:30
parent 500ef019a3
commit 4e5ef028dc

View File

@@ -19,31 +19,37 @@ class CurrencyController extends Controller
$latestUpdate = GoldCurrency::max('updated_at'); $latestUpdate = GoldCurrency::max('updated_at');
$isUpdatedToday = $latestUpdate && Carbon::parse($latestUpdate)->isToday(); $isUpdatedToday = $latestUpdate && Carbon::parse($latestUpdate)->isToday();
// 2. If not updated today, call the API (Cache once per day) // 2. If not updated today, call the API
if (!$isUpdatedToday) { if (!$isUpdatedToday) {
$this->fetchAndCacheGoldPrices(); $this->fetchAndCacheGoldPrices();
} }
// 3. Fetch data from our own database // 3. Fetch data from our own database
$goldCurrencies = GoldCurrency::all()->map(function ($currency) { $goldCurrencies = GoldCurrency::all();
// 4. Debug check: If it is STILL empty, the API failed and we have no backup data yet.
if ($goldCurrencies->isEmpty()) {
return $this->failed(null, 'ارتباط با سرور قیمت‌ها برقرار نشد. لطفا بعدا تلاش کنید.');
}
// 5. Map the data
$mappedCurrencies = $goldCurrencies->map(function ($currency) {
return [ return [
'change_percent' => $currency->change_percent, 'change_percent' => $currency->change_percent,
'change_value' => $currency->change_value, 'change_value' => $currency->change_value,
'date' => $currency->updated_at->format('Y-m-d'), // Format for the DTO 'date' => $currency->updated_at->format('Y-m-d'),
'name' => $currency->name, 'name' => $currency->name,
'name_en' => $currency->name_en, 'name_en' => $currency->name_en,
'price' => $currency->price, 'price' => $currency->price,
'symbol' => $currency->symbol, 'symbol' => $currency->symbol,
'time' => $currency->updated_at->format('H:i:s'), // Format for the DTO 'time' => $currency->updated_at->format('H:i:s'),
'time_unix' => $currency->time_unix, 'time_unix' => $currency->time_unix,
'unit' => $currency->unit, 'unit' => $currency->unit,
]; ];
}); });
// 4. Return in the exact format your frontend expects!
// We nest it inside ['gold' => ...] to match your CurrencyListBrsDto
return $this->success([ return $this->success([
'gold' => $goldCurrencies 'gold' => $mappedCurrencies
], 'موفق', 'لیست قیمت طلا و سکه دریافت شد.'); ], 'موفق', 'لیست قیمت طلا و سکه دریافت شد.');
} }
@@ -53,17 +59,22 @@ class CurrencyController extends Controller
private function fetchAndCacheGoldPrices() private function fetchAndCacheGoldPrices()
{ {
try { try {
$url = 'https://Api.BrsApi.ir/Api/Market/Gold_Currency.php?key=B727Ue3kBrbtCwHR3BmSVZKRRNF1sllp'; $url = 'https://BrsApi.ir/Api/Market/Gold_Currency.php?key=B727Ue3kBrbtCwHR3BmSVZKRRNF1sllp';
// Timeout after 10 seconds so the user isn't stuck waiting if the API is down // FIX: Added withoutVerifying() for Iranian SSL issues and a User-Agent to bypass firewalls
$response = Http::timeout(10)->get($url); $response = Http::withoutVerifying()
->withHeaders([
'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Accept' => 'application/json',
])
->timeout(15)
->get($url);
if ($response->successful()) { if ($response->successful()) {
$data = $response->json(); $data = $response->json();
if (isset($data['gold']) && is_array($data['gold'])) { if (isset($data['gold']) && is_array($data['gold'])) {
foreach ($data['gold'] as $item) { foreach ($data['gold'] as $item) {
// updateOrCreate uses the 'name_en' as the unique key to update existing rows
GoldCurrency::updateOrCreate( GoldCurrency::updateOrCreate(
['name_en' => $item['name_en']], ['name_en' => $item['name_en']],
[ [
@@ -79,11 +90,9 @@ class CurrencyController extends Controller
} }
} }
} else { } else {
Log::warning('BrsApi returned an error status: ' . $response->status()); Log::warning('BrsApi returned an error status: ' . $response->status() . ' - ' . $response->body());
} }
} catch (\Exception $e) { } catch (\Exception $e) {
// If the API completely dies (DNS issue, offline), we log it but don't crash.
// The controller will just safely return yesterday's prices from the DB!
Log::error('Failed to fetch from BrsApi: ' . $e->getMessage()); Log::error('Failed to fetch from BrsApi: ' . $e->getMessage());
} }
} }