Debug School

rakesh kumar
rakesh kumar

Posted on

Currency conversion using laravel Api

To convert one dynamic currency to another currency using Laravel, you can utilize an API service like Fixer.io, Open Exchange Rates, or CurrencyLayer, which provide currency conversion rates. Here's a basic example using the Fixer.io API:

First, make sure you have Guzzle HTTP client installed in your Laravel project:

composer require guzzlehttp/guzzle
Enter fullscreen mode Exit fullscreen mode

Then, create a service to handle the currency conversion:

// app/Services/CurrencyConverter.php

namespace App\Services;

use GuzzleHttp\Client;

class CurrencyConverter
{
    protected $apiKey;
    protected $client;

    public function __construct()
    {
        $this->apiKey = config('services.fixer.key'); // Or use other configuration method
        $this->client = new Client([
            'base_uri' => 'http://data.fixer.io/api/',
        ]);
    }

    public function convert($from, $to, $amount)
    {
        $response = $this->client->get("convert?access_key={$this->apiKey}&from={$from}&to={$to}&amount={$amount}");

        $data = json_decode($response->getBody(), true);

        return $data['result'];
    }
}
Enter fullscreen mode Exit fullscreen mode

Next, create a configuration file for the Fixer.io API key:

// config/services.php

return [
    'fixer' => [
        'key' => env('FIXER_API_KEY'),
    ],
];
Enter fullscreen mode Exit fullscreen mode

Then, set the API key in your environment file:

FIXER_API_KEY=your-api-key
Enter fullscreen mode Exit fullscreen mode

Now, you can use the CurrencyConverter service in your controller or wherever you need to perform currency conversion:

use App\Services\CurrencyConverter;

class CurrencyConversionController extends Controller
{
    protected $converter;

    public function __construct(CurrencyConverter $converter)
    {
        $this->converter = $converter;
    }

    public function convertCurrency(Request $request)
    {
        $from = $request->input('from');
        $to = $request->input('to');
        $amount = $request->input('amount');

        $convertedAmount = $this->converter->convert($from, $to, $amount);

        return response()->json(['converted_amount' => $convertedAmount]);
    }
}
Enter fullscreen mode Exit fullscreen mode

Finally, you can create a route to handle the currency conversion request:

Route::post('convert-currency', [CurrencyConversionController::class, 'convertCurrency']);
Enter fullscreen mode Exit fullscreen mode

Make sure to replace 'your-api-key' with your actual Fixer.io API key.

This is a basic example of how to perform currency conversion using Laravel. Depending on your requirements, you might need to adjust the implementation accordingly, especially considering API rate limits, error handling, caching, and more.

How to get FIXER_API_KEY

To get the FIXER_API_KEY, you need to sign up for an account on the Fixer website and subscribe to one of their plans. Here's how you can obtain the API key:

Sign up for an account: Go to the Fixer website and sign up for an account. You'll need to provide your email address and create a password.

Subscribe to a plan: Once you've signed up, navigate to the pricing page or subscription section on the Fixer website. Choose a plan that suits your needs and budget. Fixer offers various plans with different features and usage limits.

Obtain the API key: After subscribing to a plan, you'll receive an API key. This key is unique to your account and is used to authenticate your requests to the Fixer API.

Configure your Laravel application: Once you have your API key, you can configure it in your Laravel application. You can set it in your .env file like this:

FIXER_API_KEY=your-api-key
Enter fullscreen mode Exit fullscreen mode

Replace your-api-key with the actual API key you obtained from Fixer.

Use the API key in your code: You can now use the FIXER_API_KEY environment variable in your Laravel application to authenticate requests to the Fixer API. For example, you can access it in your code like this:

$apiKey = env('FIXER_API_KEY');
Enter fullscreen mode Exit fullscreen mode

You can then pass this API key to your CurrencyConverter service or any other part of your application that requires it.

By following these steps, you can obtain the FIXER_API_KEY and use it in your Laravel application for currency conversion. Make sure to adhere to the usage limits of your Fixer plan to avoid exceeding API quotas or facing any restrictions.

Another Way

If you want to convert currencies without using an API key, you can use a free API like ExchangeRate-API. However, keep in mind that using a free API might come with limitations or restrictions, and the accuracy of the exchange rates might vary.

Here's an example of how you can perform currency conversion using ExchangeRate-API without an API key:

First, you need to install the Guzzle HTTP client package:

composer require guzzlehttp/guzzle
Enter fullscreen mode Exit fullscreen mode

Then, create a service to handle the currency conversion:

// app/Services/CurrencyConverter.php

namespace App\Services;

use GuzzleHttp\Client;

class CurrencyConverter
{
    protected $client;

    public function __construct()
    {
        $this->client = new Client([
            'base_uri' => 'https://api.exchangerate-api.com/v4/',
        ]);
    }

    public function convert($from, $to, $amount)
    {
        $response = $this->client->get("latest/{$from}");

        $data = json_decode($response->getBody(), true);

        if (isset($data['rates'][$to])) {
            return $data['rates'][$to] * $amount;
        } else {
            throw new \Exception("Invalid currency code: {$to}");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Next, you can use the CurrencyConverter service in your controller:

use App\Services\CurrencyConverter;

class CurrencyConversionController extends Controller
{
    protected $converter;

    public function __construct(CurrencyConverter $converter)
    {
        $this->converter = $converter;
    }

    public function convertCurrency(Request $request)
    {
        $from = $request->input('from');
        $to = $request->input('to');
        $amount = $request->input('amount');

        $convertedAmount = $this->converter->convert($from, $to, $amount);

        return response()->json(['converted_amount' => $convertedAmount]);
    }
}
Enter fullscreen mode Exit fullscreen mode

Finally, create a route to handle the currency conversion request:

Route::post('convert-currency', [CurrencyConversionController::class, 'convertCurrency']);
Enter fullscreen mode Exit fullscreen mode

With this setup, you can convert currencies without using an API key. However, keep in mind that the availability and accuracy of the exchange rates depend on the free API service you are using, and there may be rate limits or other restrictions.

Top comments (0)