ExchangeRatesAPI - Currency Exchange Rates API SDK

Overview

ExchangeRatesAPI - Currency Exchange Rates API SDK

Latest Version Packagist Software License

This is an unofficial wrapper for the awesome, free ExchangeRatesAPI, which provides exchange rate lookups courtesy of the Central European Bank. It features a number of useful functions and can be installed easily using Composer.

4.0.0 update:
Following pricing changes for ExchangeRatesAPI, this project now uses ExchangeRates.host as its API provider. This should now be considered an unofficial SDK for . 4.0.0 should be backwards compatible with older versions which relied on the no-longer-free ExchangeRatesAPI.

Table of Contents:

  1. Installation
  2. Getting Started
  3. API Reference
  4. Supported Currencies
  5. Requirements
  6. Bugs & Features
  7. License

1. Installation:

The easiest installation method is to use Composer:

$ composer require benmajor/exchange-rates-api

Alternatively, you can download all files from the src/ directory and include them in your project. Important note: if you're manually installing the SDK, you must also install Guzzle Client.

2. Getting Started:

Since the CurrencyExchangeAPI does not require API keys or authentication in order to access and interrogate its API, getting started with this library is easy. The following examples show how to achieve various functions using the library.

Basic usage:
Fetch the latest exchange rates from the European Central Bank:

use \BenMajor\ExchangeRatesAPI\ExchangeRatesAPI;
use \BenMajor\ExchangeRatesAPI\Response;
use \BenMajor\ExchangeRatesAPI\Exception;

$access_key = '';
$use_ssl = false; # Free plans are restricted to non-SSL only.

$lookup = new ExchangeRatesAPI($access_key, $use_ssl);
$rates  = $lookup->fetch();

Historical data:
Get historical rates for any day since 1999:

$access_key = '';

$lookup = new ExchangeRatesAPI($access_key);
$rates  = $lookup->setFetchDate('2015-01-20')->fetch();

Get historical rates for a time period:

$access_key = '';

$lookup = new ExchangeRatesAPI($access_key);
$rates  = $lookup->addDateFrom('2015-01-20')->addDateTo('2015-01-21')->fetch();

Set the base currency:
By default, the base currency is set to Euro (EUR), but it can be changed:

$access_key = '';

$lookup = new ExchangeRatesAPI($access_key);
$rates  = $lookup->setBaseCurrency('GBP')->fetch();

Fetch specific rates:
If you do not want all current rates, it's possible to specify only the currencies you want using addRate(). The following code fetches only the exchange rate between GBP and EUR:

$access_key = '';

$lookup = new ExchangeRatesAPI($access_key);
$rates  = $lookup->addRate('EUR')->setBaseCurrency('GBP')->fetch();

Please refer to the API website for further information and full API docs.

Please note: By default, the fetch() method will return a new ExchangeRatesAPI\Response object. However, by passing a single argument of true to the fetch() method, you can retrieve a raw JSON resposne instead.

3. API Reference:

The following API reference lists the publicly-available methods for the

ExchangeRatesAPI Reference:

addDateFrom( string $from ):
Set the date from which to retrieve historic rates. $from should be a string containing an ISO 8601 date.

getDateFrom():
Returns the specified date from which to retrieve historic rates. Returns null if none is specified.

removeDateFrom():
Removes the specified start date for the retrieval of historic rates.

addDateTo( string $to ):
Set the end date for the retrieval of historic rates. $to should be a string containing an ISO 8601 date.

getDateTo():
Returns the specified end date for the retrieval of historic rates. Returns null if none is specified.

getAccessKey():
Returns the access_key that is currently in use.

getUseSSL():
Returns a boolean flag that determines which API URL will be used to perform requests. Free plans are restricted to non-SSL usage.

removeDateTo():
Removes the specified end date for the retrieval of historic rates.

currencyIsSupported( string $code ):
Checks if a specific currency code is supported. $code should be passed as an ISO 4217 code (e.g. EUR).
Returns true if supported, or false if not.

setBaseCurrency( string $code ):
Set the base currency to be used for exchange rates. $code should be passed an ISO 4217 code (e.g. EUR).
$code must be one of the supported currency codes.

getBaseCurrency():
Returns the currently specified base currency. If setBaseCurrency() hasn't been called, this will return the default base currency EUR.

addRates( array $codes ):
Adds multiple currencies to be retrieved. $codes should be an array of ISO 4217 codes (e.g. ["EUR", "GBP", "BGN"]).
Each code in the array must be of the supported currency codes.

addRate( string $code ):
Adds a new currency to be retrieved. $code should be passed an ISO 4217 code (e.g. EUR).
$code must be one of the supported currency codes.
If no rates are added, all rates will be returned.

removeRates( array $codes ):
Removes multiple currencies that has already been added to the retrieval list. $codes should be an array of ISO 4217 codes (e.g. ["EUR", "GBP", "BGN"]).
$code must be one of the supported currency codes.

removeRate( string $code ):
Removes a currency that has already been added to the retrieval list. $code should be passed an ISO 4217 code (e.g. EUR).
$code must be one of the supported currency codes.

setAccessKey( string $access_key ):
Sets access_key to be used in all requests.

setUseSSL( bool $use_ssl ):
Sets the API URL according to the selected mode (SSL or non-SSL). Free plans are restricted to non-SSL usage.

fetch( bool $returnJSON = false, bool $parseJSON = true ):
Send off the request to the API and return either a Response object, or the raw JSON response. If $returnJSON is set to true, a standard PHP object will be returned, rather than the ExchangeRatesAPI\Response object.

convert( string $to, float $amount, int $rounding ):
A convenience function to combine several methods in order to quickly perform a currency conversion:

$to: should be specified as the ISO 4217 currency code to convert to.
$amount: the amount to be converted.
$rounding: the amount to round the conversion. Default is 2.

This method call will return the converted currency amount in $to from the specified based currency.

getSupportedCurrencies( string $concat = null ):
Returns a list of supported currency codes. If $concat is null, an array of currency codes is returned. If $concat is specified as a string, a string will be returned, joined by $concat.

getRates( string $concat = null ):
Returns a list of the currently specified rates to retrieve. If $concat is null, an array of currency codes is returned. If $concat is specified as a string, a string will be returned, joined by $concat.

Response Reference:

This is the default object that is returned from the fetch(). Here is a list of the available methods on the Response object:

getStatusCode():
Returns the status code of the request (generally 200).

getTimestamp():
Returns the timestamp (formatted in ISO 8601 notation) the response was generated.

getBaseCurrency():
Returns the base currency of the request. If not base currency was specified using setBaseCurrency on the request, this will return the default (EUR).

getRates():
Returns a key/value pair array of the exchange rates that match against the request, for example:

[ 'GBP' => 1, 'EUR' => 1.1 ]

getRate( string $code ):
Retrieves the exchange rate for a specific currency, or returns the exchange rate if only one rate is present in the response.

4. Supported Currencies:

The library supports any currency currently available on the European Central Bank's web service, which can be found here.

5. Requirements:

This library requires PHP >= 7.0. No other platform requirements exist, but the library is dependent on Guzzle.

6. Bugs & Features:

If you have spotted any bugs, or would like to request additional features from the library, please file an issue via the Issue Tracker on the project's Github page: https://github.com/benmajor/ExchangeRatesAPI/issues.

7. License:

Licensed under the MIT License:

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Comments
  • No longer that free

    No longer that free

    Apparently, "the awesome, free ExchangeRatesAPI" is no longer that free. As of today, our services relying upon this API started to fail, and I discovered that exchangeratesapi.io started to require API key, and only 250 requests/month are free. Everyone needs to run their server.

    opened by crocodile2u 8
  • Support access to the date property of the API response

    Support access to the date property of the API response

    Two parts to this PR

    1. Arrange access to the date property if it's being returned by the API (can be relevant when requesting /latest endpoint to doublecheck which date we actually got -- as data is being updated 5 minutes after GTM midnight according to their FAQ): https://api.exchangerate.host/latest https://exchangerate.host/#/#faq
    2. Fix the endpoint & parameters names for the from-to kind of requests: https://api.exchangerate.host/timeseries?start_date=2020-01-01&end_date=2020-01-04
    opened by sashotoster 3
  • Library update to facilitate the new exchangeratesapi.io requirements

    Library update to facilitate the new exchangeratesapi.io requirements

    Added access_key and SSL/non-SSL to the library. I tried to maintain roughly the same coding standards, to avoid unnecessary back and forth tweaks and changes and to keep the overall readability consistent.

    opened by iganev 3
  • Support for `source` parameter

    Support for `source` parameter

    After switching to the https://exchangerate.host/ in #8 we have various data sources available at the API (see source parameter in https://exchangerate.host/#/docs).

    This PR supports:

    • setting source to one of the bank sources linked in the documentation (the not included crypto is, strictly speaking, a valid option too, but in case of regular currencies it returns the same result as the default, so I would consider it out of scope, see if you agree)
    • resetting source back to the API default (according to the docs, it's 'forex' which is not a valid option to be set explicitly as it returns false as a result)
    • verifying the provided string against the internal hardcoded list of supported sources (similar as it's done with currency codes)

    I'm slightly doubting about this last one, as in the current implementation the list has to be manually updated once a new source is introduced (not sure how often that can happen, but seems at least more likely than with the currencies). Possible alternatives I can think of:

    • keep verifying the sources, but instead of a hardcoded list make an API call to the sources endpoint (and probably cache the results? or maybe allow users to verify a source once and then skip the verification on set)
    • (probably the easiest) don't verify the source, leave it as user's responsibility to provide something that makes sense If the preferred solution is the first one, can it be postponed for another future PR?

    Please let me know what you think.

    P.S. I skipped the part of making an issue first, but so my justification for making a PR is that I would like to use your library with a custom source and currently I can't.

    opened by sashotoster 1
  • Undefined property: stdClass::$base

    Undefined property: stdClass::$base

    Just had an issue here, i think its related to the Endpoint Response?

    How to produce the error

            $lookup = new ExchangeRatesAPI();
            $rates  = $lookup->addRate('USD')->setBaseCurrency('SGD')->fetch();
            $rate = $rates->getRates();
            echo $rate;
    

    Screenshoot image

    Libraries Used "guzzlehttp/guzzle": "^6.4" "benmajor/exchange-rates-api": "^1.0" "php": "^7.1.3"

    opened by stevangd 1
  • PHP is not supported

    PHP is not supported

    I noticed in the list private $_currencies = [ 'USD', 'GBP', 'EUR', 'JPY', 'BGN', 'CZK', 'DKK', 'HUF', 'PLN', 'RON', 'SEK', 'CHF', 'ISK', 'NOK', 'HRK', 'RUB', 'TRY', 'AUD', 'BRL', 'CAD', 'CNY', 'HKD', 'IDR', 'ILS', 'INR', 'KRW', 'MXN', 'MYR', 'NZD', 'BHP', 'SGD', 'THB', 'ZAR' ];

    There are BHP currencies but no PHP So is there a mistake here?

    bug 
    opened by FA-tinhnd 1
  • Add/Remove multiple currencies at once. Fix removeRate

    Add/Remove multiple currencies at once. Fix removeRate

    First thanks for the nice wrapper.

    I found it useful if multiple currencies can be added/removed from the request/response at once. Also spotted a small issue in the removeRate method where it calls the internal verifyCurrencyCode without passing the actual currency code.

    opened by dmtar 1
  • Cannot call functions from ExchangeRatesAPI.php

    Cannot call functions from ExchangeRatesAPI.php

    Hi,

    I am trying to call some functions (E.g. trying to get the base currency below) from the ones available in ExchangeRatesAPI.php to my Wordpress site but they break my site when I do so. Whe I fetch the whole data body using Worpress function wp_remote_get() I can see the expected outcome but I need to show only one rate at a time and take 2 parameters for the 2 currencies so that's why I am trying to use the ExchangeRatesAPI.php functions. Am I doing something wrong or is there any other issue I should be aware of? Thanks in advance for any answer

    //https://github.com/benmajor/ExchangeRatesAPI#3-getting-started
    require_once 'C:\ExchangeRatesAPI-master\src\ExchangeRatesAPI.php';
    
    
    $request = wp_remote_get( 'https://api.exchangeratesapi.io/latest?base=USD' );
    if( is_wp_error( $request ) ) {
    	return false; // Bail early
    }
    $body = wp_remote_retrieve_body( $request );
    $data = json_decode( $body );
    //echo "<pre>"; //this is for cleaning the data in visualitation
    //print_r($data); //print output
    
    use \BenMajor\ExchangeRatesAPI\ExchangeRatesAPI;
    use \BenMajor\ExchangeRatesAPI\Response;
    use \BenMajor\ExchangeRatesAPI\Exception;
    
    $lookup = new ExchangeRatesAPI();
    $base  = $lookup->getBaseCurrency();
    
    function mytest(){
    $base=getBaseCurrency();
    return $base;}
    add_shortcode( 'base', 'mytest' );
    
    opened by Etv500 1
  • Add GuzzleHttp\Client as dependency on composer.json

    Add GuzzleHttp\Client as dependency on composer.json

    When the library is installed through composer and the project does not have GuzzleHttp previously installed, the error "'GuzzleHttp\Client' not found' is thrown.

    Screen Shot 2019-07-03 at 3 54 03 PM

    bug 
    opened by abdyfranco 1
  • Fix to return specific rate from response

    Fix to return specific rate from response

    This is a little fix to a bug I found. The following would error as it was trying to access an object as an array.

    $lookup = new \BenMajor\ExchangeRatesAPI\ExchangeRatesAPI();
    $rates  = $lookup->setBaseCurrency('GBP')->fetch();
    
    echo $rates->getRate('EUR');
    
    opened by glennjacobs 1
Releases(4.1.1)
Owner
Ben Major
Loves PHP, Slim, RedBean and React. Open-source advocate and full-stack web dev from the UK.
Ben Major
A php library for coinex exchange apis .

Coinex API PHP Coinex digital coin exchange API for PHP Requirements PHP>=7.1 CURL PHP module Install composer require roozbeh/coinex_php Acquire acce

Roozbeh Baabakaan 3 Nov 12, 2022
Cryptocurrency exchange script Codono supports Auto detection of deposits, Each user is assigned with Unique deposit per coin

#Cryptocurrency exchange script Codono supports Auto detection of deposits, Each user is assigned with Unique deposit per coin. Deposits are detected

null 9 Dec 26, 2022
Shopware PHP SDK is a simple SDK implementation of Shopware 6 APIs

Shopware PHP SDK is a simple SDK implementation of Shopware 6 APIs. It helps to access the API in an object-oriented way.

Thuong Le 77 Dec 19, 2022
The 1Password Connect PHP SDK provides your PHP applications access to the 1Password Connect API hosted on your infrastructure and leverage the power of 1Password Secrets Automation

1Password Connect PHP SDK The 1Password Connect PHP SDK provides your PHP applications access to the 1Password Connect API hosted on your infrastructu

Michelangelo van Dam 12 Dec 26, 2022
SDK of the LINE Login API for PHP

LINE Login for PHP SDK of the LINE Login API for PHP Documentation See the official API documentation for more information. Installation Use the packa

null 4 Sep 15, 2022
Esse SDK em PHP foi desenvolvido no intuito de tornar mais prático a integração com nossa API.

Sobre Beedoo SDK Acessar documentação completa da Beedoo API. A API é organizada seguindo a arquitetura REST, boas práticas, convenções e padrões como

Beedoo Edtech 5 Dec 2, 2021
An SDK built to facilitate application development for Facebook Ads API.

Facebook Business SDK for PHP Introduction The Facebook Business SDK is a one-stop shop to help our partners better serve their businesses. Partners a

Meta 719 Dec 28, 2022
A PHP SDK for accessing the OpenAI GPT-3 API

OpenAI GPT-3 Api Client in PHP Installation You can install the package via composer: composer require orhanerday/open-ai Usage use Orhanerday\OpenAi\

Orhan erday 462 Jan 2, 2023
The Facebook SDK for PHP provides a native interface to the Graph API and Facebook Login

Facebook SDK for PHP (v5) This repository contains the open source PHP SDK that allows you to access the Facebook Platform from your PHP app. Installa

Meta Archive 3.1k Dec 30, 2022
PHP SDK for the Sellix Developers API (developers.sellix.io)

PHP SDK for the Sellix Developers API (developers.sellix.io). Quickly get started and create products, payments and more using PHP.

Sellix 7 Nov 23, 2022
Mark Sign - Gateway API PHP SDK

Mark Sign - Gateway API PHP SDK

Mark Sign 3 Feb 22, 2022
Light PHP SDK to interact with the Doma(in)Validity API.

Doma(in)Validity PHP SDK. Light PHP SDK to interact with the Doma(in)Validity API. Usage <?php require_once 'vendor/autoload.php'; use Domainvalidit

Doma(In)Validity 2 May 3, 2022
A PHP SDK for the ScreenshotOne.com API to take screenshots of any URL

phpsdk An official Screenshot API client for PHP. It takes minutes to start taking screenshots. Just sign up to get access and secret keys, import the

ScreenshotOne.com 4 Jun 14, 2022
BT Open API SDK in PHP

Mosel, a sdk package for BT open APIs This package is still under construction (july 13th 2022). Open Api are described in the Bouygues Telecom Develo

BboxLab 0 Jul 7, 2022
Unofficial Firebase Admin SDK for PHP

Firebase Admin PHP SDK Table of Contents Overview Installation Documentation Support License Overview Firebase provides the tools and infrastructure y

kreait 1.9k Jan 3, 2023
Notion PHP SDK

Notion PHP SDK This is an unofficial PHP SDK for the new public Notion API. It's work in progress as we didn't get the change to be included to the pr

Codecycler 43 Nov 29, 2022
The official Symfony SDK for Sentry (sentry.io)

sentry-symfony Symfony integration for Sentry. Benefits Use sentry-symfony for: A fast Sentry setup Easy configuration in your Symfony app Automatic w

Sentry 628 Dec 29, 2022
Fully unit tested Facebook SDK v5 integration for Laravel & Lumen

Laravel Facebook SDK A fully unit-tested package for easily integrating the Facebook SDK v5 into Laravel and Lumen 5.0, 5.1, 5.2, & 5.3. This is packa

Sammy Kaye Powers 697 Nov 6, 2022
爱发电非官方简易 PHP SDK

afdian-php-sdk 爱发电非官方简易 PHP SDK by Akkariin 这是一个简单的 SDK,可以用于查询爱发电的订单和赞助者信息 Installation 将项目 clone 到本地即可 git clone https://github.com/ZeroDream-CN/afdi

ZeroDream-CN 17 Nov 7, 2022