【问题标题】:How can I get the local currency per user如何获得每个用户的当地货币
【发布时间】:2019-05-23 13:41:48
【问题描述】:

我在前端使用 Laravel 5.6 和 Vue.js。我需要用他的货币代码自动注册一个用户。有什么建议吗?

我尝试了很多包(geoip、geolocal),但没有一个适合我。

$location = geoip()->getLocation();

【问题讨论】:

    标签: vue.js laravel-5 currency


    【解决方案1】:

    我使用几个服务来获取国家代码。如果由于某种原因(例如超出限制)无法工作,它会尝试下一个服务:

    /**
    * Make cUrl request.
    */
    private static function _getCurl(string $url, int $timeout = 400):?string {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, $timeout);     // If it takes too long just try the next api
        curl_setopt($ch, CURLOPT_TIMEOUT_MS, $timeout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
    
    /**
    * Try to get the country code of the current user based on it's ip.
    */
    public static function getCountryCode():?string {
        // https://hostip.info/  - unlimited? requests per day
        // https://ipinfo.io/    - 1000 requests per day
        // https://ipdata.co/    - 1500 requests per day
        // https://ipstack.com/  - 10000 requests per month (not used at the moment)
    
            // Get country code:
            $ip = $_SERVER['HTTP_CLIENT_IP']);
    
            $countryCode = null;
            if (!$countryCode) {    // Try hostip.info
                try {
                    $output = self::_getCurl('https://api.hostip.info/get_json.php?ip=' . $ip);
                    $output = json_decode($output);
                    $countryCode = ($output->country_code == 'XX') ? null : $output->country_code;
                }
                catch (Throwable $t) {}
            }
            if (!$countryCode) {    // Try ipinfo.io
                try {
                    $output = self::_getCurl('http://ipinfo.io/' . $ip . '/json?token=[ipinfo.io TOKEN HERE]');
                    $output = json_decode($output);
                    $countryCode = ($output->country == 'XX') ? null : $output->country;
                }
                catch (Throwable $t) {}
            }
            if (!$countryCode) {    // Try ipdata.co
                try {
                    $output = self::_getCurl('https://api.ipdata.co/' . $ip . '?api-key=[ipdata.co TOKEN HERE]');
                    $output = json_decode($output);
                    $countryCode = ($output->country_code == 'XX') ? null : $output->country_code;
                }
                catch (Throwable $t) {}
            }
    
        return $countryCode;
    }
    

    这是一个更大的课程的过去,所以你可能需要在这里和那里做一些调整。 ipinfo.io 和 ipdata.co 需要 api 令牌,因此您需要先从他们的网站获取这些令牌(两者都是免费的)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-17
      • 1970-01-01
      • 2012-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多