Currency is a simple PHP library for current and historical currency exchange rates & crypto exchange rates. based on the free API exchangerate.host

Overview

Currency

Tests Packagist License Packagist Version Packagist Downloads

Currency is a simple PHP library for current and historical currency exchange rates & crypto exchange rates. based on the free API exchangerate.host - no API keys needed!

Requirements

  • PHP >= 7.2
  • guzzlehttp >= 6.0

Installation

composer require amrshawky/currency

Usage

1. Currency Conversion

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

require 'vendor/autoload.php';

use AmrShawky\Currency;

Currency::convert()
        ->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\Currency;

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

Available Methods

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

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

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

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

2. Latest Rates

To get latest rates you may chain the methods:

use AmrShawky\Currency;

Currency::rates()
        ->latest()
        ->get();

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

Currency::rates()
        ->latest()
        ->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\Currency;

Currency::rates()
        ->latest()
        ->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\Currency;

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

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

Currency::rates()
        ->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\Currency;

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

4. Timeseries Rates

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.

1.201995 ], '2021-05-02' => [ "USD" => 1.2027 ] ] */ ">
use AmrShawky\Currency;

Currency::rates()
        ->timeSeries('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. 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.

1.376454, "end_rate" => 1.37816, "change" => -0.001706, "change_pct" => -0.001239 ] ] */ ">
use AmrShawky\Currency;

Currency::rates()
        ->fluctuations('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\Currency;

Currency::convert()
        ->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\Currency;

Currency::convert()
        ->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\Currency;

Currency::convert()
        ->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\Currency;

Currency::rates()
        ->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\Currency;

Currency::rates()
        ->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();

License

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

You might also like...
Free ZIP Code API - Free Access to Worldwide Postal Code Data

About Zipcodebase - Free Zip Code API Zipcodebase is a zip code API that was founded in 2019 to solve common issues with postal code data. As we have

A customizable decentralized micro-blog (Twitter) and cms (Wordpress) that only you host and moderate.

Consider this -- each Miter account is individually hosted on a user's personal and private third party server (host) - either purchased or free - as

Shows you the current diocese that you're in, as well as the bishop.

Use config.php to create variables $dbuser and $dbpass for the database connection. Run `php -f ./coa/newcheck.php` to update database information fr

Yab copy to new - A Textpattern plugin. Copies the current article content to a new one.

yab_copy_to_new Displays a new button in article write tab to copy the current article to a new one. Version: 0.2 Table of contents Plugin requirement

Repman - PHP Repository Manager: packagist proxy and host for private packages

Repman - PHP Repository Manager Repman is a PHP repository manager. Main features: free and open source works as a proxy for packagist.org (speeds up

A money and currency library for PHP

Brick\Money A money and currency library for PHP. Introduction Working with financial data is a serious matter, and small rounding mistakes in an appl

Run Telegram PHP Bot on Windows Localhost without Host or VPN.

Run Telegram PHP Bot on Windows Localhost without Host or VPN.

Library download currency rate and save in database, It's designed to be extended by any available data source.

Library download currency rate and save in database, It's designed to be extended by any available data source.

This script allows to bypass Oracle Cloud Infrastructure 'Out of host capacity' error immediately when additional OCI capacity will appear in your Home Region / Availability domain.
This script allows to bypass Oracle Cloud Infrastructure 'Out of host capacity' error immediately when additional OCI capacity will appear in your Home Region / Availability domain.

Resolving Oracle Cloud "Out of Capacity" issue and getting free VPS with 4 ARM cores / 24GB of memory Very neat and useful configuration was recently

Releases(1.0.0)
Owner
Amr Shawky
PHP Developer
Amr Shawky
Buy and sell crypto top 100 crypto with our fake currency. Donate to and use our referal links for discounts

PLEASE ENABLE SQLITE3 AND GD OR GD2 IN XAMPP TO RUN THE APP! (SEE HOW_TO_SETUP_XAMPP.gif) ![alt text](https://github.com/Tby23rd/Project1-Cryptosimul

Tabitha Maru 0 Dec 26, 2021
A simple package for interacting with the exchangerate.host API

Table of Contents Overview Installation Usage Methods Exchange Rate Getting the Rate Between Two Currencies Getting the Rate Between More Than Two Cur

Ash Allen 23 Feb 16, 2022
Simple Symfony currency exchange demo application (CLI)

Symfony currency exchange demo Keynotes Using a small Symfony installation as possible Using SQLite database for simplicity but with price of some cav

Vladimir Martsul 9 Oct 21, 2022
World Currency list in PHP constants and in array (Currency::USD)

World Currency list in PHP constants and in array (Currency::USD) If you need to work with currencies in the code and describe each time "USD", "EUR"

Krepysh 4 Jun 27, 2022
Very easy to use a current limiting component, the code is very simple, based on the webman framework.

Very easy to use a current limiting component, the code is very simple, based on the webman framework.

nsp-team 13 Dec 29, 2022
Empower your business to accept payments globally, earn rewards and invest in crypto with lazerpay laravel sdk in your laravel project.

Lazerpay Laravel Package pipedev/lazerpay is a laravel sdk package that access to laravel api Installation PHP 5.4+ and Composer are required. To get

Muritala David 24 Dec 10, 2022
The Current US Version of PHP-Nuke Evolution Xtreme v3.0.1b-beta often known as Nuke-Evolution Xtreme. This is a hardened version of PHP-Nuke and is secure and safe. We are currently porting Xtreme over to PHP 8.0.3

2021 Nightly Builds Repository PHP-Nuke Evolution Xtreme Developers TheGhost - Ernest Allen Buffington (Lead Developer) SeaBeast08 - Sebastian Scott B

Ernest Buffington 7 Aug 28, 2022
Description: A simple plugin that sets the current admin page to always be at the top of the admin menu.

=== Sticky Admin Menu === Contributors: sc0ttkclark Donate link: https://www.scottkclark.com/ Tags: admin menu, sticky Requires at least: 4.4 Tested u

Scott Kingsley Clark 2 Sep 29, 2022
It is an open-source and free project, which is faced with the drawing lovers, providing a free and simple Gallery service

It is an open-source and free project, which is faced with the drawing lovers, providing a free and simple Gallery service

WeepingDogel 5 Dec 15, 2022
This document provides the details related to Remittance API. This APIs is used to initiate payment request from Mobile client/others exchange house.

City Bank Remittance API This is where your description should go. Limit it to a paragraph or two. Consider adding a small example. Installation You c

MD ARIFUL HAQUE 2 Oct 2, 2022