Duplicate Transaction
How to Integrate Cryptocurrency APIs in PHP

How to Integrate Cryptocurrency APIs in PHP

The world of cryptocurrency has rapidly evolved, and PHP developers have multiple ways to incorporate crypto functionalities into web applications. This guide will walk you through different use cases, from fetching crypto prices and trading to sending payments and interacting with smart contracts, using PHP.

Understanding Cryptocurrency APIs

Cryptocurrency APIs offer a way to interact with blockchain networks, trading exchanges, and other crypto services. Depending on the API, you can:

  • Retrieve real-time prices of different cryptocurrencies.
  • Make trades on exchanges like Binance.
  • Send and receive crypto payments using platforms like Coinbase.
  • Interact with Ethereum smart contracts using libraries like Web3 PHP.

In the examples below, you’ll learn how to use cURL, Guzzle, and specialized libraries to integrate cryptocurrency APIs into your PHP applications.

1. Getting Cryptocurrency Prices Using CoinGecko API

CoinGecko is one of the most popular free APIs for retrieving real-time cryptocurrency data. The API offers extensive data, including price, market cap, trading volume, and more.

Fetching Bitcoin Price with CoinGecko API

This example shows how to use cURL to fetch the current Bitcoin price.


<?php
// CoinGecko API endpoint
$url = 'https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd';

// Initialize cURL
$ch = curl_init($url);

// Set options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute and get the response
$response = curl_exec($ch);
curl_close($ch);

// Decode the JSON response
$data = json_decode($response, true);

// Display the Bitcoin price
echo 'Bitcoin Price: $' . $data['bitcoin']['usd'];
?>;

In this code snippet, we use the CoinGecko API to retrieve the price of Bitcoin in USD and display it.

2. Trading on Binance API

The Binance API allows developers to interact with the Binance trading platform, offering functionality to place trades, check balances, and more.

Fetching Account Balance

To interact with the Binance API, you’ll need to generate an API key and secret from your Binance account.


<?php
$api_key = 'YOUR_BINANCE_API_KEY';
$api_secret = 'YOUR_BINANCE_API_SECRET';
$timestamp = time() * 1000;

// Create the signature for authentication
$query = "timestamp=$timestamp";
$signature = hash_hmac('sha256', $query, $api_secret);

// Binance API endpoint for account balance
$url = "https://api.binance.com/api/v3/account?$query&signature=$signature";

// Initialize cURL
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "X-MBX-APIKEY: $api_key"
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute and get the response
$response = curl_exec($ch);
curl_close($ch);

// Decode the JSON response
$data = json_decode($response, true);
print_r($data); // Print account details
?>;

This code snippet shows how to use the Binance API to fetch account balances using cURL with signature authentication.

3. Sending Crypto Payments with Coinbase Commerce API

Coinbase Commerce provides APIs for accepting cryptocurrency payments, making it easy for merchants to integrate crypto payments into their applications.

Creating a Charge

You can use the Coinbase Commerce API to create a new payment charge.


<?php
$api_key = 'YOUR_COINBASE_COMMERCE_API_KEY';

// Coinbase Commerce API endpoint
$url = 'https://api.commerce.coinbase.com/charges';

// Data to create a charge
$data = [
    'name' => 'Order #1234',
    'description' => 'Payment for services',
    'pricing_type' => 'fixed_price',
    'local_price' => [
        'amount' => '100.00',
        'currency' => 'USD'
    ]
];

// Initialize cURL
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'X-CC-Api-Key: ' . $api_key,
    'X-CC-Version: 2018-03-22'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute and get the response
$response = curl_exec($ch);
curl_close($ch);

// Decode the JSON response
$result = json_decode($response, true);
print_r($result); // Print the charge details
?>;

This example shows how to create a charge using the Coinbase Commerce API, making it suitable for accepting crypto payments.

4. Using Guzzle for a Crypto API

Guzzle is a popular PHP library for making HTTP requests, offering a more organized way to interact with APIs.

Fetching Ethereum Price from CoinGecko

First, install Guzzle with Composer:


composer require guzzlehttp/guzzle

Then use it to fetch the Ethereum price:


<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;

$client = new Client();
$response = $client->request('GET', 'https://api.coingecko.com/api/v3/simple/price', [
    'query' => [
        'ids' => 'ethereum',
        'vs_currencies' => 'usd'
    ]
]);

$data = json_decode($response->getBody(), true);
echo 'Ethereum Price: $' . $data['ethereum']['usd'];
?>;

Using Guzzle simplifies handling API requests and responses in PHP.

5. Sending Bitcoin Transactions with BlockCypher API

BlockCypher offers APIs for Bitcoin, Ethereum, and other blockchains, allowing developers to manage addresses, transactions, and more.

Creating a New Bitcoin Address


<?php
$api_key = 'YOUR_BLOCKCYPHER_API_KEY';
$url = 'https://api.blockcypher.com/v1/btc/main/addrs';

// Initialize cURL
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json'
]);

// Execute and get the response
$response = curl_exec($ch);
curl_close($ch);

// Decode the JSON response
$data = json_decode($response, true);

// Display the new Bitcoin address
echo 'New Bitcoin Address: ' . $data['address'];
?>;

BlockCypher provides a simple way to create new addresses and manage transactions.

6. Interacting with Ethereum Smart Contracts Using Web3 PHP

For Ethereum blockchain interactions, you can use Web3 PHP, a library that provides a convenient way to interact with Ethereum smart contracts.

Interacting with a Smart Contract

Install Web3 PHP using Composer:


composer require sc0vu/web3.php

Then use it to interact with Ethereum smart contracts:


<?php
require 'vendor/autoload.php';
use Web3\Web3;

$web3 = new Web3('https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID');
$web3->eth->getBalance('0xAddressHere', function ($err, $balance) {
    if ($err !== null) {
        echo 'Error: ' . $err->getMessage();
        return;
    }
    echo 'Balance: ' . $balance->toString();
});
?>;

Web3 PHP is a powerful tool for smart contract interactions.

Conclusion

Integrating cryptocurrency APIs in PHP allows developers to build applications that offer crypto trading, payments, and blockchain interactions. Whether you’re fetching prices, making trades, or accepting payments, these PHP examples will help you get started with crypto development.

Feel free to explore each use case further, depending on your project requirements. Happy coding!

Kourosh

Your Header Sidebar area is currently empty. Hurry up and add some widgets.