PHPackages                             matmar10/coinbase-php - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [HTTP &amp; Networking](/categories/http)
4. /
5. matmar10/coinbase-php

ActiveLibrary[HTTP &amp; Networking](/categories/http)

matmar10/coinbase-php
=====================

Coinbase API library for PHP &gt;=5.3.3

1.0.2(11y ago)044MITPHPPHP &gt;=5.3.3

Since May 20Pushed 11y ago2 watchersCompare

[ Source](https://github.com/matmar10/coinbase-php)[ Packagist](https://packagist.org/packages/matmar10/coinbase-php)[ Docs](http://coinbase.com)[ RSS](/packages/matmar10-coinbase-php/feed)WikiDiscussions master Synced 1w ago

READMEChangelogDependenciesVersions (4)Used By (0)

Coinbase PHP Client Library
===========================

[](#coinbase-php-client-library)

\*NOTE: this is a straight fork of  with namespace and Psr0 autoload support \*

An easy way to buy, send, and accept [bitcoin](http://en.wikipedia.org/wiki/Bitcoin) through the [Coinbase API](https://coinbase.com/docs/api/overview).

This library supports both the [API key authentication method](https://coinbase.com/docs/api/overview) and OAuth. The below examples use an API key - for instructions on how to use OAuth, see [OAuth Authentication](#oauth-authentication).

Installation
------------

[](#installation)

Obtain the latest version of the Coinbase PHP library with:

```
git clone https://github.com/coinbase/coinbase-php

```

Then, add the following to your PHP script:

```
require_once("/path/to/coinbase-php/lib/Coinbase.php");

```

Usage
-----

[](#usage)

Start by [enabling an API Key on your account](https://coinbase.com/account/integrations).

Next, create an instance of the client and pass it your API Key as the first (and only) parameter.

```
$coinbase = new Coinbase($_ENV['COINBASE_API_KEY'])
```

Notice here that we did not hard code the API key into our codebase, but set it in an environment variable instead. This is just one example, but keeping your credentials separate from your code base is a good [security practice](https://coinbase.com/docs/api/overview#security).

Now you can call methods on `$coinbase` similar to the ones described in the [API reference](https://coinbase.com/api/doc). For example:

```
$balance = $coinbase->getBalance();
echo "Balance is " . $balance . " BTC";
```

Currency amounts are returned as Strings. To avoid precision errors, use the [PHP arbitrary precision math functions ](http://www.php.net/manual/en/ref.bc.php) to work with money amounts.

Examples
--------

[](#examples)

### Check your balance

[](#check-your-balance)

```
echo $coinbase->getBalance() . " BTC";
// '200.123 BTC'
```

### Send bitcoin

[](#send-bitcoin)

`public function sendMoney($to, $amount, $notes=null, $userFee=null, $amountCurrency=null)`

```
$response = $coinbase->sendMoney("user@example.com", "2");
echo $response->success ? 'true' : 'false';
// 'true'
echo $response->transaction->status;
// 'pending'
echo $response->transaction->id;
// '518d8567ed3ddcd4fd000034'
```

The first parameter can also be a bitcoin address and the third parameter can be a note or description of the transaction. Descriptions are only visible on Coinbase (not on the general bitcoin network).

```
$response = $coinbase->sendMoney("mpJKwdmJKYjiyfNo26eRp4j6qGwuUUnw9x", "0.1", "thanks for the coffee!");
echo $response->transaction->notes;
// 'thanks for the coffee!'
```

You can also send money in a number of currencies (see `getCurrencies()`) using the fifth parameter. The amount will be automatically converted to the correct BTC amount using the current exchange rate.

```
$response = $coinbase->sendMoney("user@example.com", "2", null, null, "CAD");
echo $response->transaction->amount->amount;
// '0.0169'
```

### Request bitcoin

[](#request-bitcoin)

This will send an email to the recipient, requesting payment, and give them an easy way to pay.

```
$response = $coinbase->requestMoney('client@example.com', 50, "contractor hours in January (website redesign for 50 BTC)");
echo $response->transaction->request ? 'true' : 'false';
// 'true'
echo $response->transaction->id;
// '501a3554f8182b2754000003'

$response = $coinbase->resendRequest('501a3554f8182b2754000003');
echo $response->success ? 'true' : 'false';
// 'true'

$response = $coinbase->cancelRequest('501a3554f8182b2754000003');
echo $response->success ? 'true' : 'false';
// 'true'

// From the other account:
$response = $coinbase->completeRequest('501a3554f8182b2754000003');
echo $response->success ? 'true' : 'false';
// 'true'
```

### List your current transactions

[](#list-your-current-transactions)

Sorted in descending order by timestamp, 30 per page. You can pass an integer as the first param to page through results, for example `$coinbase->getTransactions(2)`.

```
$response = $coinbase->getTransactions();
echo $response->current_page;
// '1'
echo $response->num_pages;
// '2'
echo $response->transactions[0]->id;
// '5018f833f8182b129c00002f'
```

Transactions will always have an `id` attribute which is the primary way to identity them through the Coinbase api. They will also have a `hsh` (bitcoin hash) attribute once they've been broadcast to the network (usually within a few seconds).

### Check bitcoin prices

[](#check-bitcoin-prices)

Check the buy or sell price by passing a `quantity` of bitcoin that you'd like to buy or sell. This price includes Coinbase's fee of 1% and the bank transfer fee of $0.15.

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

### Buy or sell bitcoin

[](#buy-or-sell-bitcoin)

Buying and selling bitcoin requires you to [link and verify a bank account](https://coinbase.com/payment_methods) through the web interface first.

Then you can call `buy` or `sell` and pass a `$quantity` of bitcoin you want to buy.

On a buy, we'll debit your bank account and the bitcoin will arrive in your Coinbase account four business days later (this is shown as the `payout_date` below). This is how long it takes for the bank transfer to complete and verify, although we're working on shortening this window. In some cases, we may not be able to guarantee a price, and buy requests will fail. In that case, set the second parameter (`$agreeBtcAmountVaries`) to true in order to purchase bitcoin at the future market price when your money arrives.

On a sell we'll credit your bank account in a similar way and it will arrive within two business days.

```
$response = $coinbase->buy('1.0');
echo $response->transfer->code;
// '6H7GYLXZ'
echo $response->transfer->btc->amount;
// '1.00000000'
echo $response->transfer->total->amount;
// '$17.95'
echo $response->transfer->payout_date;
// '2013-02-01T18:00:00-08:00' (ISO 8601 format - can be parsed with the strtotime() function)
```

```
$response = $coinbase->sell('1.0');
echo $response->transfer->code;
// 'RD2OC8AL'
echo $response->transfer->btc->amount;
// '1.00000000'
echo $response->transfer->total->amount;
// '$17.95'
echo $response->transfer->payout_date;
// '2013-02-01T18:00:00-08:00' (ISO 8601 format - can be parsed with the strtotime() function)
```

### Create a payment button

[](#create-a-payment-button)

This will create the code for a payment button (and modal window) that you can use to accept bitcoin on your website. You can read [more about payment buttons here and try a demo](https://coinbase.com/docs/merchant_tools/payment_buttons).

The method signature is `public function createButton($name, $price, $currency, $custom=null, $options=array())`. The `custom` param will get passed through in [callbacks](https://coinbase.com/docs/merchant_tools/callbacks) to your site. The list of valid `options` [are described here](https://coinbase.com/api/doc/buttons/create.html).

```
$response = $coinbase->createButton("Your Order #1234", "42.95", "EUR", "my custom tracking code for this order", array(
            "description" => "1 widget at €42.95"
        ));
echo $response->button->code;
// '93865b9cae83706ae59220c013bc0afd'
echo $response->embedHtml;
// ''
```

### Exchange rates and currency utilties

[](#exchange-rates-and-currency-utilties)

You can fetch a list of all supported currencies and ISO codes with the `getCurrencies()` method.

```
$currencies = $coinbase->getCurrencies();
echo $currencies[0]->name;
// 'Afghan Afghani (AFN)'
```

`getExchangeRate()` will return a list of exchange rates. Pass two parameters to get a single exchange rate.

```
$rates = $coinbase->getExchangeRate();
echo $rates->btc_to_cad;
// '117.13892'
echo $coinbase->getExchangeRate('btc', 'cad');
// '117.13892'
```

### Create a new user

[](#create-a-new-user)

```
$response = $coinbase->createUser("newuser@example.com", "some password");
echo $response->user->email;
// 'newuser@example.com'
echo $response->user->receive_address;
// 'mpJKwdmJKYjiyfNo26eRp4j6qGwuUUnw9x'
```

A receive address is returned also in case you need to send the new user a payment right away.

### Get autocomplete contacts

[](#get-autocomplete-contacts)

This will return a list of contacts the user has previously sent to or received from. Useful for auto completion. By default, 30 contacts are returned at a time; use the `$page` and `$limit` parameters to adjust how pagination works.

```
$response = $coinbase->getContacts("exa");
echo implode(', ', $response->contacts);
// 'user1@example.com, user2@example.com'
```

Adding new methods
------------------

[](#adding-new-methods)

You can see a [list of method calls here](https://github.com/coinbase/coinbase-php/blob/master/lib/Coinbase/Coinbase.php) and how they are implemented. They are a wrapper around the [Coinbase JSON API](https://coinbase.com/api/doc).

If there are any methods listed in the [API Reference](https://coinbase.com/api/doc) that don't have an explicit function name in the library, you can also call `get`, `post`, `put`, or `delete` with a `$path` and optional `$params` array for a quick implementation. The raw JSON object will be returned. For example:

```
var_dump($coinbase->get('/account/balance'));
// object(stdClass)#4 (2) {
//   ["amount"]=>
//   string(10) "0.56902981"
//   ["currency"]=>
//   string(3) "BTC"
// }
```

Or feel free to add a new wrapper method and submit a pull request.

OAuth Authentication
--------------------

[](#oauth-authentication)

To authenticate with OAuth, first create an OAuth application at . When a user wishes to connect their Coinbase account, redirect them to a URL created with `Coinbase_OAuth::createAuthorizeUrl`:

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

After the user has authorized your application, they will be redirected back to the redirect URL specified above. A `code` parameter will be included - pass this into `getTokens` to receive a set of tokens:

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

Store these tokens safely, and use them to make Coinbase API requests in the future. For example:

```
$coinbase = new Coinbase($coinbaseOauth, $tokens);
$coinbase->getBalance();
```

A full example implementation is available in the `example` directory.

Security notes
--------------

[](#security-notes)

If someone gains access to your API Key they will have complete control of your Coinbase account. This includes the abillity to send all of your bitcoins elsewhere.

For this reason, API access is disabled on all Coinbase accounts by default. If you decide to enable API key access you should take precautions to store your API key securely in your application. How to do this is application specific, but it's something you should [research](http://programmers.stackexchange.com/questions/65601/is-it-smart-to-store-application-keys-ids-etc-directly-inside-an-application) if you have never done this before.

Testing
-------

[](#testing)

If you'd like to contribute code or modify this library, you can run the test suite by executing `/path/to/coinbase-php/test/Coinbase.php` in a web browser or on the command line with `php`.

###  Health Score

27

—

LowBetter than 49% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity8

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity60

Established project with proven stability

 Bus Factor1

Top contributor holds 88.6% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~209 days

Total

3

Last Release

4327d ago

PHP version history (2 changes)1.0.0PHP &gt;=5.2.0

1.0.2PHP &gt;=5.3.3

### Community

Maintainers

![](https://www.gravatar.com/avatar/9dede0530c32ff7421ef5cc42a19b9be4b8926111ae0bc3111993429a73c6b9b?d=identicon)[matmar10](/maintainers/matmar10)

---

Top Contributors

[![isaacwaller](https://avatars.githubusercontent.com/u/107115?v=4)](https://github.com/isaacwaller "isaacwaller (31 commits)")[![matmar10](https://avatars.githubusercontent.com/u/19975?v=4)](https://github.com/matmar10 "matmar10 (2 commits)")[![barmstrong](https://avatars.githubusercontent.com/u/25322?v=4)](https://github.com/barmstrong "barmstrong (1 commits)")[![lian](https://avatars.githubusercontent.com/u/6937?v=4)](https://github.com/lian "lian (1 commits)")

---

Tags

apirestbitcoinlibcoinbase

### Embed Badge

![Health badge](/badges/matmar10-coinbase-php/health.svg)

```
[![Health](https://phpackages.com/badges/matmar10-coinbase-php/health.svg)](https://phpackages.com/packages/matmar10-coinbase-php)
```

###  Alternatives

[nategood/httpful

A Readable, Chainable, REST friendly, PHP HTTP Client

1.8k17.2M267](/packages/nategood-httpful)[mediamonks/rest-api-bundle

MediaMonks Rest API Symfony Bundle

1656.2k1](/packages/mediamonks-rest-api-bundle)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
