-
app/Support/FreeGeoIp/FreeGeoIp.php
Open in GitHubuse Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Http; class FreeGeoIp { public static function getCountryCodeForIp(string $ip): string { return Cache::remember("countryCodeIp{$ip}", 60 * 5, function () use ($ip) { $response = Http::get("https://freegeoip.app/json/{$ip}"); if ($response->status() !== 200) { return 'US'; } $countryCode = $response->json('country_code', 'US'); if (empty($countryCode)) { return 'US'; } return $countryCode; }); } }
-
app/Models/Purchasable.php
Open in GitHubuse Illuminate\Database\Eloquent\Model; use App\Support\FreeGeoIp\FreeGeoIp; class Purchasable extends Model { public function getPriceForIp(string $ip): DisplayablePrice { $countryCode = FreeGeoIp::getCountryCodeForIp($ip); return $this->getPriceForCountryCode($countryCode); } }
-
app/Support/PPPApi/PPPApi.php
Open in GitHubuse Illuminate\Support\Facades\Http; class PPPApi { public static function fetchForCountryCode(string $countryCode): ?PPPResponse { $response = Http::get("https://api.purchasing-power-parity.com/?target={$countryCode}"); if ($response->status() !== 200) { return null; } $rawResponse = $response->json(); if (isset($rawResponse['message'])) { return null; } if (! isset($rawResponse['ppp']['currencyMain']['code'])) { return null; } return PPPResponse::create($rawResponse); } }
-
app/Console/Commands/UpdateConversionRatesCommand.php
Open in GitHubuse App\Support\PPPApi\PPPApi; use App\Support\PPPApi\PPPResponse; use Illuminate\Console\Command; class UpdateConversionRatesCommand extends Command { public function handle() { $this->info('Start updating conversion rates...'); PaddleCountries::get()->each(function (array $country) { $this->comment("Getting conversion rate for `{$country['code']}`..."); $pppResponse = PPPApi::fetchForCountryCode($country['code']); if (! $pppResponse) { return; } ConversionRate::query()->updateOrCreate([ 'country_code' => $country['code'], ], [ 'currency_symbol' => $pppResponse->currencySymbol, 'currency_code' => $pppResponse->currencyCode, 'ppp_conversion_factor' => $this->getConversionFactor($pppResponse), 'exchange_rate' => $pppResponse->exchangeRate, ]); }); $this->info('All done!'); } // }