Convert Bitcoin to Local Currency using PHP

June 26, 2020
Written by
Ladapo Samuel
Contributor
Opinions expressed by Twilio contributors are their own
Reviewed by

Convert Bitcoin to Local Currency using php.png

There are different methods of converting bitcoins to local currency and vice versa such as blockchain exchange sites and wallet apps,  Today, this tutorial will walk you through creating your simple Bitcoin converter using SMS and PHP, allowing you to check current market rates on the go!

Technical Requirements

To complete this tutorial, you will need the following dependencies globally installed on your computer:

Set Up Your Development Environment

To kick start our project, we will need to create a project directory for it. You may use cryptoconverter as this is what I will be using. Create the following files in the project folder:

  • .env
  • webhook.php
  • functions.php

Next, we need to set up our .env file.

NOTE: The .env file is a hidden file used to store secret and private keys on our servers. It is not accessible by the browser, so we can store our API keys or credentials in it and access it from anywhere within our app on the server-side.

To allow the support of .env configs in our app, we need to install the dotenv package using Composer. We will also need to install the Guzzle package in order to easily make HTTPS requests from within our app. Run this command in your terminal inside of the project directory:

$ composer require vlucas/phpdotenv && composer require guzzlehttp/guzzle

There are many libraries that enable us to access the Twilio API more efficiently than using the traditional cURL requests. For this project, we will install the Twilio PHP SDK. Run the following command in your terminal in the project directory.

$ composer require twilio/sdk

Setup Twilio SMS Credentials & Phone Number

If you have not already done so, take a few minutes and head to your Twilio account to create a new number. We need to get the following information from the Twilio console to allow us to send and receive SMS from within our project:

  • Twilio Account SID
  • Twilio Auth Token
  • A Phone Number

Once we have these items, we can add them to our .env file.

 

# TWILIO CREDENTIALS
TWILIO_ACCOUNT_SID=""
TWILIO_AUTH_TOKEN=""
TWILIO_PHONE_NUMBER="+1999999999"

By now you should have all of the necessary details to connect your app to Twilio. Now let’s have a short math class!

Understanding How the Conversion Works

To convert Bitcoin (BTC) to local currency and vice versa, we need to first understand how it works so we can write a function to automate this process and then enable SMS conversions.

Let’s take a look at the following example. To convert from USD to BTC, we need to get the USD to BTC global ticker price from the blockchain. At the time of writing this article, the conversion rate is $7111.57 USD.

Assuming we’re converting $10 USD, we will follow the following formula; $10 USD /$7111.57 USD, which will equal 0.0014062 BTC.

To convert BTC back to USD, just run the previous formula in reverse by multiplying.

E.g 0.0014062 BTC to USD will equal $10 because 0.0014061 x $7111.57 is 10.

Create a Function to Convert Bitcoin to Local Currency

Let’s  create a simple helper function that processes the user’s SMS command e.g convert 1 BTC to USD or convert 40 USD to BTC.

Add the following code to your functions.php file.  This function will parse the user’s SMS command into a much more readable format that we can use for the conversion.

function processCommand($RawCommand)
{
    $resp = [];
    $reverse = 'false';
    $command = explode(" ", $RawCommand);

    if (count($command) === 5) {
        $amount = $command[1];
        $from = $command[2];
        $to = $command[4];

        if ($from === 'BTC') {
            $reverse = 'true';
            $symbol = $to;
        }
        if ($to === 'BTC') {
            $symbol = $from;
        }

        $resp = ['status' => 'success','data'=> [
            'amount' => $amount,
            'symbol' => $symbol,
            'reverse' => $reverse,
            'from' => $from,
            'to' => $to
        ]];
    } else {
        $resp = ['status' => 'error','message' => 'Command is not well structured'];
    }
    return $resp;
}

Now that we can process user’s commands, we need to create a function that does the conversion. Update the functions.php file with the following code:

function convertCurrency($message)
{
    $resp = [];
    $command = processCommand($message);
    try {
        if ($command['status'] === 'success') {
            $symbol = $command['data']['symbol'];
            $amount = $command['data']['amount'];
            $from = $command['data']['from'];
            $to = $command['data']['to'];

        
            $tickerUrl = $_ENV['CRYPTOCOMPARE_URL'];
            // print_r($tickerUrl);
            // Initialize Guzzle client
            $client = new GuzzleHttp\Client();
            $globalPriceCall = $client->get($tickerUrl, [
      'query'   => [
        'fsym' => 'BTC',
        'tsyms' => $command['data']['symbol']
      ],
  ])->getBody()->getContents();
  
            $globalPrice = json_decode($globalPriceCall);
  
            if ($command['data']['reverse'] === 'false') {
                $resp = ['from' => $from , 'to' => $to,'amount'=>round(($amount / $globalPrice->$symbol), 8) ];
            } else {
                $resp = ['from' => $from , 'to' => $to,'amount'=> number_format(($amount * $globalPrice->$symbol), 2) ];
            }
        }
        return $resp;
    } catch (exception $e) {
        return "An error occurred please try again later";
    }
}

We also need to update our .env file with the crypto exchange price source’s URL with the following:

#CRYPTOCOMPARE
CRYPTOCOMPARE_URL="https://min-api.cryptocompare.com/data/price"

The final functions.php file should look like the one below:

<?php
function processCommand($RawCommand)
{
    $resp = [];
    $reverse = 'false';
    $command = explode(" ", $RawCommand);

    if (count($command) === 5) {
        $amount = $command[1];
        $from = $command[2];
        $to = $command[4];

        if ($from === 'BTC') {
            $reverse = 'true';
            $symbol = $to;
        }
        if ($to === 'BTC') {
            $symbol = $from;
        }

        $resp = ['status' => 'success','data'=> [
            'amount' => $amount,
            'symbol' => $symbol,
            'reverse' => $reverse,
            'from' => $from,
            'to' => $to
        ]];
    } else {
        $resp = ['status' => 'error','message' => 'Command is not well structured'];
    }
    return $resp;
}

function convertCurrency($message)
{
    $resp = [];
    $command = processCommand($message);
    try {
        if ($command['status'] === 'success') {
            $symbol = $command['data']['symbol'];
            $amount = $command['data']['amount'];
            $from = $command['data']['from'];
            $to = $command['data']['to'];

        
            $tickerUrl = $_ENV[''CRYPTOCOMPARE_URL'];
            // print_r($tickerUrl);
            // Initialize Guzzle client
            $client = new GuzzleHttp\Client();
            $globalPriceCall = $client->get($tickerUrl, [
      'query'   => [
        'fsym' => 'BTC',
        'tsyms' => $command['data']['symbol']
      ],
  ])->getBody()->getContents();
  
            $globalPrice = json_decode($globalPriceCall);
  
            if ($command['data']['reverse'] === 'false') {
                $resp = ['from' => $from , 'to' => $to,'amount'=>round(($amount / $globalPrice->$symbol), 8) ];
            } else {
                $resp = ['from' => $from , 'to' => $to,'amount'=> number_format(($amount * $globalPrice->$symbol), 2) ];
            }
        }
        return $resp;
    } catch (exception $e) {
        return "An error occured please try again later";
    }
}

Create a Twilio Webhook

We will need to create a Twilio webhook in order to receive SMS conversion requests from users. Twilio has a webhook feature that sends a response to an endpoint whenever your Twilio phone number receives a message.

In the webhook.php file, copy and paste the following code  to create our own webhook that receives conversion requests

  <?php
require __DIR__ . "/vendor/autoload.php";
use Twilio\Rest\Client;

require_once('functions.php');

$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $message = $_REQUEST['Body'] ?? '';
    $from = $_REQUEST['From'] ?? '';
    if ($message !== '') {

        $account_sid = $_ENV["TWILIO_ACCOUNT_SID"];
        $auth_token = $_ENV["TWILIO_AUTH_TOKEN"];
        $twilio_number = $_ENV["TWILIO_PHONE_NUMBER"];

        $client = new Client($account_sid, $auth_token);
        $response = convertCurrency($message);
        $text = 'Conversion of '.$response['from']. ' to '. $response['to'] .' is '. $response['amount'];

        $client->messages->create(
            $from,
           [
        'from' => $twilio_number,
        'body' =>    $text
     ]
        );
    }
}

We will now use ngrok to make this webhook accessible through a public URL from our localhost.

From the terminal, run the command:

$ php -S localhost:3000

On a new terminal, run the command:

$ ./ngrok http 3000

Your terminal window should look like this:

ngrok screen

The Forwarding URL combined with the webhook.php endpoint will be used as the webhook URL. For example, mine is:

https://e4370d59.ngrok.io/webhook.php


The final step is hooking our Twilio number to the webhook we created. Navigate to the active numbers on your dashboard and click on the number you would like to use.

In the messaging section, there is an input box labeled “A MESSAGE COMES IN”. Replace the URL with our webhook URL and click “Save”!

Twilio Webhook setup

Testing Our App

Let’s test the application! Send convert 1 BTC to USD to your Twilio number to receive the converted results.

Sample SMS app

Conclusion

Good job! Now we can convert BTC to USD and vice versa using SMS. You can extend the project to allow multiple currencies such as Ethereum and bitcoin cash to enable a robust conversion system using SMS.

Bonus

Github Repo: https://github.com/ladaposamuel/bitcoin-converter-sms

 

Ladapo Samuel