Bitcoin and PHP with Coinbase’s API – Basic Usage

Share this article

Have you ever thought about selling your services in exchange for Bitcoins? It’s not so strange – today, many big players are actually doing it. From OkCupid to KhanAcademy, even WordPress is accepting Bitcoin. Also, some countries are thinking about it as a currency. Today, we will see how to accept Bitcoin payments on your website/application in an easy way, with the Coinbase API (and its SDK).

Coinbase SDK

Coinbase has some interesting tools and SDKs available for everyone, with some pricing conditions that are convenient and affordable.

Here’s what you have to know about pricing:

  • Receiving payments with Coinbase is free;
  • You will have to pay a fee (1%) only if you want to transfer money on your bank account, but only if your sales exceed $1000000 (yes, one milion dollars);
  • The smallest payment you can do in the Bitcoin network is 0.001 BTC. Using a Coinbase wallet, however, that limit goes down to 1 Satoshi (0.00000001 BTC);

Another important (and interesting) thing is that you can choose to activate the “Instant Exchange” service, which converts a Bitcoin payment amount immediately into a currency of your choice without additional steps, automatically. Really cool if you want to avoid the currency instability and transfer your money as soon as you can.

That said… how do we implement this integration?

Integration Types

Just like many other online payment services, Coinbase offers two main ways of integration into your web app. The first one is faster and easier. The second one is a little more difficult, but also goes into more depth and is adequate for a bigger project.

The first integration type consists of using one of the Merchant Tools that Coinbase makes available. You can use buttons, pages and frames. If you are using a CMS or an e-commerce (WordPress, WooCommerce, Magento…) there are many plugins for your favorite one.

The second, of which we will see an example today, is a complete integration of the service without going to the Coinbase website to generate some standard button code. In fact, we will use the specific PHP SDK to do it.

What can we do with this SDK? The dedicated page on Coinbase is clear:

  • sell or buy bitcoins (or exchange with your currency);
  • send or request bitcoins via email or bitcoin address;
  • accept bitcoin payments as a merchant;
  • store your bitcoins in one or more wallets;
  • have access to bitcoin raw network data (blocks, transactions and so on…);
  • handle micro-payments and recurring payments;

A little bit of everything.

At this moment, there are three SDKs available: for Ruby, Java and PHP. There are also many unofficial libraries for other languages (Python, .NET, Node…). As I told you before, the SDK that we will use is the PHP SDK, which you can find on GitHub.

Note: before you go to the next step, I will presume that you are able to create an account on Coinbase, or you already have one.

The PHP SDK

Installation

Let’s start with the package installation for our project. If you take a look at the GitHub page of the SDK you will find nothing about doing it with Composer. However, simple searching will easily yield the packagist page of the coinbase/coinbase package.

You can install it with

{
	    "require": {
	        "coinbase/coinbase": "dev-master"
	    }
	}

in your composer.json file and a

composer update

Authentication

Before starting with the code let’s talk about authentication. Coinbase has two ways to authenticate you as a developer in order to access the API methods. You can choose a simple API Key access, with an API Secret to have more security. Or, if you want, you can use OAuth 2. The difference is not only about complexity, but also about the situation you have to deal with.

The Coinbase documentation is quite clear: if you want to use your account and make changes to it, you can use the API Key system. If you want to let the user use his account through your app (a client you build, for example), the best thing is to use OAuth.

API Key + Secret

Creating an API Key is really simple, once you have an account on Coinbase. All you have to do is to go here and click on “+ New API Key”.

For your first time, you will probably have to confirm your account with Authy.

The screen you’ll see will be one like this:

The New API Key Screen

You will have to specify the account you want to use and what permissions you want to assign to that specific key, in order to gain access. Also, you can choose one or more IPs to use as a whitelist. If you don’t specify anything, there will be no whitelist.

After that, confirm the procedure by clicking on “Create” and click on “Enable” when you want to activate the API Key.

OAuth 2.0

If you want to use OAuth 2.0 you will have to follow a similar procedure. This time, however, you will not create an API Key but an OAuth application. To do that, go to https://coinbase.com/oauth/applications. From there, click on “+ Create an Application”. You will see a screen like this one:

The New OAuth App Screen

Insert your application name, choose an icon if you want and specify a list of URLs for future redirect operations.

Note: every URL you are going to insert must use SSL (https://...). Everything else will be ignored.

Give your OK and you are done! You will see a confirmation message with your new ClientID and Client Secret. Things are not over, however: you can read other notes about authentication from the dedicated page.

Permissions

If you work with the API you will have to deal with permissions, for better security. Here you can see a complete list:

  • all: complete access to your account;
  • merchant: create payment buttons, forms, access to basic informations about the merchant, edit your info and create new addresses;
  • balance: access to your actual balance;
  • buttons: create payment buttons;
  • buy: buy bitcoins;
  • contacts: get a list of your contacts;
  • orders: get a list of your received orders;
  • sell: sell bitcoins;
  • transactions: get a history of your transactions;
  • send: send a certain amount of bitcoins from your account;
  • request: request bitcoins from your account;
  • transfers: get the history of buys and sells;
  • recurring_payments: get a list of recurring payments;
  • oauth_apps: see, create and edit OAuth applications;
  • reports: get and create new reports;

Basic SDK Use

Now that we have our SDK included in our project, our access set up, and we know what we need, it is time to start.

First of all, let’s take a look at the implementation of the authentication procedure.

Access via API Key and Secret

Nothing complex, just a single instruction.

$coinbase = Coinbase::withApiKey($coinbaseAPIKey, $coinbaseAPISecret);

Just use the API Key and the API Secret as parameters for the withApiKey() method. The resulting $coinbase object is the one that we’ll use for future examples.

Access via OAuth

After the OAuth application creation the next thing to do is to create a $coinbaseOauth object, specifying the Client ID and the Client Secret that we got previously. Just like this example:

$coinbaseOauth = new Coinbase_OAuth($_CLIENT_ID, $_CLIENT_SECRET, $_REDIRECT_URL);
	header("Location: " . $coinbaseOauth->createAuthorizeUrl("all"));

After the user completes the authorization process he will be redirected to the URL specified before, during the setup. A code parameter will also be added to get a valid token.

$tokens = $coinbaseOauth->getTokens($_GET['code']);

Then, the last step will be the creation of the $coinbase object using the token we now have.

$coinbase = Coinbase::withOauth($coinbaseOauth, $tokens);

You can use this object in the same way you can use the one you got from the API Key authentication, the API is the same.

Accessing your Data

Accessing to your data is quite easy. All you have to do is to use the $coinbase variable set before.

Let’s see how to check your balance:

echo $coinbase->getBalance() . " BTC";

Here you can see how to access user data:

$user = $coinbase->getUser()
	
	echo $user->name;
	echo $user->email;
	echo $user->time_zone;
	echo $user->native_currency;

Using the $coinbase object you can also gain access to some merchant properties.

$user->merchant->company_name;
	$user->merchant->logo;

Note: the logo property returns the logo URL.

Also, if you want, you can get a list of your contacts using getContacts().

$response = $coinbase->getContacts("user");

	foreach($response->contacts as $contact)
	{
		echo $contact;
		// 'guyaddress@provider.com'
	}

Currency Data

With this PHP SDK you can also gain access to some data about currencies.

$currencies = $coinbase->getCurrencies();
	echo $currencies[0]->name;

The getCurrencies() method returns a list of all the currencies actually active on the system, with their ISO codes.

Here’s how to get some information about the exchange rates:

$rates = $coinbase->getExchangeRate();
	
	echo $rates->btc_to_usd;
	// is the same as...
	echo $coinbase->getExchangeRate('btc', 'usd');

The getExchangeRate() can be used both with and without parameters (with two different results, as you can see).

You can also get some information about the buy and sell prices with getBuyPrice() and getSellPrice():

echo $coinbase->getBuyPrice('1');
	// '125.31'
	echo $coinbase->getSellPrice('1');
	// '122.41'

Note: the returned price includes the 1% Coinbase fee and the $0.15 bank one.

Create a Payment Button

The payment button creation method is really useful, if you consider the implementation difficulty and the final result. All you have to do is to call the createButton() method with a specific set of parameters.

Here’s the signature:

createButton($name, $price, $currency, $custom=null, $options=array())

… and here’s an example.

$paymentButton = $coinbase->createButton(
		"Order #1", 
		"19.99", 
		"EUR", 
		"TRACKING_CODE_1", 
		array(
        	"description" => "1 item at 19.99"
    	)
    );

Quite easy, huh?

The first $name parameter is the “title” for the payment you want to create. The next one, $price, is the amount of the payment you want. The third one is the currency you want to use, and $custom is a specific transaction code that will be sent back to you after the payment procedure.

Finally, the $options array will let you customize your button in every way: you will be able to customize the button appearance or the return URL after a successful payment, or a failed one. If you want to know more about that, I suggest you to take a look at the dedicated page on the official documentation.

Once you have the button it’s easy to get its embed code.

echo $response->button->code;
	// '93865b9cae83706ae59220c013bc0afd'
	
	echo $response->embedHtml;
	// '<div class=\"coinbase-button\" data-code=\"93865b9cae83706ae59220c013bc0afd\"></div><script src=\"https://coinbase.com/assets/button.js\" type=\"text/javascript\"></script>'

Then, you will have nothing to do but echo the $response->embedHtml.

Wrapping up

This concludes part 1 in which we covered the basic usage and installation of the Coinbase API SDK. In part 2, we’ll cover sending and receiving money, as well as build our sample application. Stay tuned!

Frequently Asked Questions (FAQs) on Bitcoin PHP and Coinbase’s API Basic Usage

How Can I Set Up Coinbase’s API for Bitcoin PHP?

Setting up Coinbase’s API for Bitcoin PHP involves a few steps. First, you need to create an API Key from your Coinbase account. Go to Settings, then API Access, and click on “+ New API Key”. You’ll need to provide your password and two-factor authentication code. Once the API Key is created, you can use it in your PHP code to interact with the Coinbase API. Remember to keep your API Key secure as it allows access to your Coinbase account.

What Are the Basic Functions of Coinbase’s API?

Coinbase’s API provides several functions for interacting with Bitcoin and other cryptocurrencies. These include creating a new Bitcoin address, sending Bitcoin to an address, requesting Bitcoin from an address, and getting information about a Bitcoin address. You can also get information about the current Bitcoin exchange rate and historical price data.

How Can I Handle Errors When Using Coinbase’s API?

When using Coinbase’s API, errors can be handled using try-catch blocks in your PHP code. The API will return an error message if something goes wrong, which you can catch and handle appropriately. For example, if the API returns an error when trying to send Bitcoin, you could catch this error and display a message to the user.

Can I Use Coinbase’s API to Accept Bitcoin Payments on My Website?

Yes, you can use Coinbase’s API to accept Bitcoin payments on your website. You can create a new Bitcoin address for each transaction, and then check that address for incoming payments. This allows you to accept Bitcoin payments without needing to handle any of the underlying blockchain technology yourself.

How Can I Test My Code When Using Coinbase’s API?

Coinbase provides a sandbox environment for testing your code. This allows you to make API calls without affecting your real Coinbase account. You can create a sandbox account from the Coinbase website, and then use the API Key from this account in your test code.

How Secure Is Coinbase’s API?

Coinbase’s API is designed with security in mind. All API calls are made over HTTPS, and sensitive data is encrypted. However, the security of your application also depends on how you handle your API Key and other sensitive data. Always keep your API Key secure and never share it with anyone.

Can I Use Coinbase’s API with Other Programming Languages?

Yes, Coinbase’s API is a RESTful API, which means it can be used with any programming language that can make HTTP requests. There are also official and unofficial libraries available for several languages, including Python, Ruby, and Java.

What Are the Rate Limits for Coinbase’s API?

Coinbase’s API has rate limits to prevent abuse. The exact limits depend on the type of API Key you have and whether your application is public or private. You can find more information about the rate limits in the Coinbase API documentation.

How Can I Monitor My Usage of Coinbase’s API?

Coinbase provides usage information for your API Key. This includes the number of API calls you’ve made, the amount of data you’ve sent and received, and any errors that have occurred. You can view this information from the API Access page in your Coinbase account.

Can I Use Coinbase’s API to Trade Other Cryptocurrencies?

Yes, Coinbase’s API supports several other cryptocurrencies in addition to Bitcoin. These include Ethereum, Litecoin, and Bitcoin Cash. You can use the API to get information about these cryptocurrencies, send and receive them, and trade them on the Coinbase exchange.

Francesco MalatestaFrancesco Malatesta
View Author

Francesco is a web developer and consultant from Italy. He is the founder of Laravel-Italia, the official Italian Laravel Community, and writes for HTML.IT, the first italian web development portal. He also translated some books about Laravel. In the meantime he follows other projects, works as a freelance backend consultant for PHP applications and studies IT Engineering in Rome. He loves to learn new things, not only about PHP or development but everything. He hopes to work for IBM, sooner or later.

apiauthenticationbitcoinBrunoSbtccoinbaseoauthOOPHPpaymentsPHP
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week