Git Product home page Git Product logo

laravel-currency's Introduction

Laravel Currency

Tests Packagist License Packagist Version Packagist Downloads

This package supports exchangerate.host API keys.

Laravel currency is a simple package for current and historical currency exchange rates & crypto exchange rates. based on the free API exchangerate.host!

Note: This package is an integration for the Currency library

Requirements

  • PHP >= 7.2
  • Laravel >= 6.0
  • guzzlehttp >= 6.0

Installation

composer require xdemonme/laravel-currency

Usage

1. Currency Conversion

To convert from one currency to another you may chain the methods:

use AmrShawky\LaravelCurrency\Facade\Currency;

$accessKey = 'YOUR_API_ACCESS_KEY';

Currency::convert()
        ->setAccessKey($accessKey)
        ->from('USD')
        ->to('EUR')
        ->get();

This will return the converted amount or null on failure.

The amount to be converted is default to 1, you may specify the amount:

use AmrShawky\LaravelCurrency\Facade\Currency;

$accessKey = 'YOUR_API_ACCESS_KEY';

Currency::convert()
        ->setAccessKey($accessKey)
        ->from('USD')
        ->to('EUR')
        ->amount(50)
        ->get();

Available Methods

  • Convert currency using historical exchange rates YYYY-MM-DD:
use AmrShawky\LaravelCurrency\Facade\Currency;

$accessKey = 'YOUR_API_ACCESS_KEY';

Currency::convert()
        ->setAccessKey($accessKey)
        ->from('USD')
        ->to('EUR')
        ->date('2019-08-01')
        ->get();
  • Round the converted amount to decimal places:
use AmrShawky\LaravelCurrency\Facade\Currency;

$accessKey = 'YOUR_API_ACCESS_KEY';

Currency::convert()
        ->setAccessKey($accessKey)
        ->from('USD')
        ->to('EUR')
        ->round(2)
        ->get();
  • You may also switch data source between forex default, bank view or crypto currencies:
use AmrShawky\LaravelCurrency\Facade\Currency;

$accessKey = 'YOUR_API_ACCESS_KEY';

Currency::convert()
        ->setAccessKey($accessKey)
        ->from('BTC')
        ->to('ETH')
        ->source('crypto')
        ->get();

2. Live (latest) Rates

Note: This method is DEPRECATED

To get latest rates you may chain the methods:

use AmrShawky\LaravelCurrency\Facade\Currency;

$accessKey = 'YOUR_API_ACCESS_KEY';

Currency::rates()
        ->setAccessKey($accessKey)
        ->live()
        ->get();

// ['USD' =>  1.215707, ...]

Currency::rates()
        ->setAccessKey($accessKey)
        ->live()
        ->source('crypto')
        ->get();

// ['ETH' => 3398.61, ...]

This will return an array of all available currencies or null on failure.

Available Methods

  • Just like currency conversion you may chain any of the available methods:
use AmrShawky\LaravelCurrency\Facade\Currency;

$accessKey = 'YOUR_API_ACCESS_KEY';

Currency::rates()
        ->setAccessKey($accessKey)
        ->live()
        ->symbols(['USD', 'EUR', 'EGP']) //An array of currency codes to limit output currencies
        ->base('GBP') //Changing base currency (default: EUR). Enter the three-letter currency code of your preferred base currency.
        ->amount(5.66) //Specify the amount to be converted
        ->round(2) //Round numbers to decimal places
        ->source('ecb') //Switch data source between forex `default`, bank view or crypto currencies.
        ->get();

3. Historical Rates

Historical rates are available for most currencies all the way back to the year of 1999.

use AmrShawky\LaravelCurrency\Facade\Currency;

$accessKey = 'YOUR_API_ACCESS_KEY';

Currency::rates()
        ->setAccessKey($accessKey)
        ->historical('2020-01-01') //`YYYY-MM-DD` Required date parameter to get the rates for
        ->get();

// ['USD' =>  1.1185, ...]

Currency::rates()
        ->setAccessKey($accessKey)
        ->historical('2021-03-30')
        ->source('crypto')
        ->get();
        
// ['BTC' =>  2.0E-5, ...]

Same as latest rates you may chain any of the available methods:

use AmrShawky\LaravelCurrency\Facade\Currency;

$accessKey = 'YOUR_API_ACCESS_KEY';

Currency::rates()
        ->setAccessKey($accessKey)
        ->historical('2020-01-01')
        ->symbols(['USD', 'EUR', 'CZK'])
        ->base('GBP')
        ->amount(5.66)
        ->round(2)
        ->source('ecb')
        ->get();

4. Timeframe (timeseries) Rates

Timeframe (timeseries) are for daily historical rates between two dates of your choice, with a maximum time frame of 365 days. This will return an array or null on failure.

use AmrShawky\LaravelCurrency\Facade\Currency;

$accessKey = 'YOUR_API_ACCESS_KEY';

Currency::rates()
        ->setAccessKey($accessKey)
        ->timeFrame('2021-05-01', '2021-05-02') //`YYYY-MM-DD` Required dates range parameters
        ->symbols(['USD']) //[optional] An array of currency codes to limit output currencies
        ->base('GBP') //[optional] Changing base currency (default: EUR). Enter the three-letter currency code of your preferred base currency.
        ->amount(5.66) //[optional] Specify the amount to be converted (default: 1)
        ->round(2) //[optional] Round numbers to decimal places
        ->source('ecb') //[optional] Switch data source between forex `default`, bank view or crypto currencies.
        ->get();
        
/**
[
    '2021-05-01' => [
        "USD" => 1.201995
    ],
    '2021-05-02' => [
        "USD" => 1.2027
    ]
]
 */

5. Change (fluctuations)

Retrieve information about how currencies fluctuate on a day-to-day basis, with a maximum time frame of 365 days. This will return an array or null on failure.

use AmrShawky\LaravelCurrency\Facade\Currency;

$accessKey = 'YOUR_API_ACCESS_KEY';

Currency::rates()
        ->setAccessKey($accessKey)
        ->change('2021-03-29', '2021-04-15') //`YYYY-MM-DD` Required dates range parameters
        ->symbols(['USD']) //[optional] An array of currency codes to limit output currencies
        ->base('GBP') //[optional] Changing base currency (default: EUR). Enter the three-letter currency code of your preferred base currency.
        ->amount(5.66) //[optional] Specify the amount to be converted (default: 1)
        ->round(2) //[optional] Round numbers to decimal places
        ->source('ecb') //[optional] Switch data source between forex `default`, bank view or crypto currencies.
        ->get();
        
/**
 [
    'USD' => [
        "start_rate" => 1.376454, 
        "end_rate"   => 1.37816, 
        "change"     => -0.001706, 
        "change_pct" => -0.001239
        ]
 ]
 */

Throwing Exceptions

The default behavior is to return null for errors that occur during the request (connection timeout, DNS errors, client or server error status code, missing API success parameter, etc.).

If you would like to throw an exception instead, you may use the throw method, The throw method returns the currency instance, allowing you to chain other methods:

use AmrShawky\LaravelCurrency\Facade\Currency;

$accessKey = 'YOUR_API_ACCESS_KEY';

Currency::convert()
        ->setAccessKey($accessKey)
        ->from('USD')
        ->to('EUR')
        ->amount(20)
        ->throw()
        ->get();

If you would like to perform some additional logic before the exception is thrown, you may pass a closure to the throw method:

use AmrShawky\LaravelCurrency\Facade\Currency;

$accessKey = 'YOUR_API_ACCESS_KEY';

Currency::convert()
        ->setAccessKey($accessKey)
        ->from('USD')
        ->to('EUR')
        ->amount(20)
        ->throw(function ($response, $e) {
            //
        })
        ->get();

Other Methods

  • You may use the withoutVerifying method to indicate that TLS certificates should not be verified when sending the request:
use AmrShawky\LaravelCurrency\Facade\Currency;

$accessKey = 'YOUR_API_ACCESS_KEY';

Currency::convert()
        ->setAccessKey($accessKey)
        ->from('USD')
        ->to('EUR')
        ->withoutVerifying()
        ->get();
  • You may specify additional Guzzle request options using the withOptions method. The withOptions method accepts an array of key / value pairs:
use AmrShawky\LaravelCurrency\Facade\Currency;

$accessKey = 'YOUR_API_ACCESS_KEY';

Currency::rates()
        ->setAccessKey($accessKey)
        ->historical('2021-04-30')
        ->withOptions([
            'debug'   => true,
            'timeout' => 3.0
        ])
        ->get();
  • The when method will execute the given callback when the first argument given to the method evaluates to true:
use AmrShawky\LaravelCurrency\Facade\Currency;

$accessKey = 'YOUR_API_ACCESS_KEY';

Currency::rates()
        ->setAccessKey($accessKey)
        ->latest()
        ->when(true, function ($rates) {
            // will execute
            $rates->symbols(['USD', 'EUR', 'EGP'])
                  ->base('GBP');
        })
        ->when(false, function ($rates) {
            // won't execute
            $rates->symbols(['HKD']);
        })
        ->get();

Testing

Currency uses Laravel facades which makes it easy to mock so it's not actually executed during the test:

use AmrShawky\LaravelCurrency\Facade\Currency;

$accessKey = 'YOUR_API_ACCESS_KEY';

Currency::shouldReceive('convert')
        ->once()
        ->andReturn(1.50);


Currency::shouldReceive('rates')
         ->once()
         ->andReturn(['EUR' => 1,'USD' => 1.215707]);

More information regarding list of bank sources here

For a list of all supported symbols here and list of crypto currencies here

License

The MIT License (MIT). Please see LICENSE for more information.

laravel-currency's People

Contributors

amrshawky avatar xdemonme avatar parth391 avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.