Giter VIP home page Giter VIP logo

coinbase-php's Introduction

Coinbase Wallet PHP Library

Build Status Latest Stable Version Total Downloads Latest Unstable Version License

This is the official client library for the Coinbase Wallet API v2. We provide an intuitive, stable interface to integrate Coinbase Wallet into your PHP project.

Important: As this library is targeted for newer API v2, it requires v2 permissions (i.e. wallet:accounts:read). If you're still using v1, please use the older version of this library.

Installation

Install the library using Composer. Please read the Composer Documentation if you are unfamiliar with Composer or dependency managers in general.

"require": {
    "coinbase/coinbase": "~2.0"
}

Authentication

API Key

Use an API key and secret to access your own Coinbase account.

use Coinbase\Wallet\Client;
use Coinbase\Wallet\Configuration;

$configuration = Configuration::apiKey($apiKey, $apiSecret);
$client = Client::create($configuration);

OAuth2

Use OAuth2 authentication to access a user's account other than your own. This library does not handle the handshake process, and assumes you have an access token when it's initialized. You can handle the handshake process using an OAuth2 client such as league/oauth2-client.

use Coinbase\Wallet\Client;
use Coinbase\Wallet\Configuration;

// with a refresh token
$configuration = Configuration::oauth($accessToken, $refreshToken);

// without a refresh token
$configuration = Configuration::oauth($accessToken);

$client = Client::create($configuration);

Two factor authentication

The send money endpoint requires a 2FA token in certain situations (read more here). A specific exception is thrown when this is required.

use Coinbase\Wallet\Enum\Param;
use Coinbase\Wallet\Exception\TwoFactorRequiredException;
use Coinbase\Wallet\Resource\Transaction;

$transaction = Transaction::send([
    'toEmail' => '[email protected]',
    'bitcoinAmount' => 1
]);

$account = $client->getPrimaryAccount();
try {
    $client->createAccountTransaction($account, $transaction);
} catch (TwoFactorRequiredException $e) {
    // show 2FA dialog to user and collect 2FA token

    // retry call with token
    $client->createAccountTransaction($account, $transaction, [
        Param::TWO_FACTOR_TOKEN => '123456',
    ]);
}

Pagination

Several endpoints are paginated. By default, the library will only fetch the first page of data for a given request. You can easily load more than just the first page of results.

$transactions = $client->getAccountTransactions($account);
while ($transactions->hasNextPage()) {
    $client->loadNextTransactions($transactions);
}

You can also use the fetch_all parameter to have the library issue all the necessary requests to load the complete collection.

use Coinbase\Wallet\Enum\Param;

$transactions = $client->getAccountTransactions($account, [
    Param::FETCH_ALL => true,
]);

Warnings

It's prudent to be conscious of warnings. The library will log all warnings to a standard PSR-3 logger if one is configured.

use Coinbase\Wallet\Client;
use Coinbase\Wallet\Configuration;

$configuration = Configuration::apiKey($apiKey, $apiSecret);
$configuration->setLogger($logger);
$client = Client::create($configuration);

Resource references

In some cases the API will return resource references in place of expanded resource objects. These references can be expanded by refreshing them.

$deposit = $this->client->getAccountDeposit($account, $depositId);
$transaction = $deposit->getTransaction();
if (!$transaction->isExpanded()) {
    $this->client->refreshTransaction($transaction);
}

You can also request that the API return an expanded resource in the initial request by using the expand parameter.

use Coinbase\Wallet\Enum\Param;

$deposit = $this->client->getAccountDeposit($account, $depositId, [
    Param::EXPAND = ['transaction'],
]);

Resource references can be used when creating new resources, avoiding the overhead of requesting a resource from the API.

use Coinbase\Wallet\Resource\Deposit;
use Coinbase\Wallet\Resource\PaymentMethod;

$deposit = new Deposit([
    'paymentMethod' => PaymentMethod::reference($paymentMethodId)
]);

// or use the convenience method
$deposit = new Deposit([
    'paymentMethodId' => $paymentMethodId
]);

Responses

There are multiple ways to access raw response data. First, each resource object has a getRawData() method which you can use to access any field that are not mapped to the object properties.

$data = $deposit->getRawData();

Raw data from the last HTTP response is also available on the client object.

$data = $client->decodeLastResponse();

Active record methods

The library includes support for active record methods on resource objects. You must enable this functionality when bootstrapping your application.

$client->enableActiveRecord();

Once enabled, you can call active record methods on resource objects.

use Coinbase\Wallet\Enum\Param;

$transactions = $account->getTransactions([
    Param::FETCH_ALL => true,
]);

Usage

This is not intended to provide complete documentation of the API. For more detail, please refer to the official documentation.

List supported native currencies

$currencies = $client->getCurrencies();

List exchange rates

$rates = $client->getExchangeRates();

Buy price

$buyPrice = $client->getBuyPrice('BTC-USD');

Sell price

$sellPrice = $client->getSellPrice('BTC-USD');

Spot price

$spotPrice = $client->getSpotPrice('BTC-USD');

Current server time

$time = $client->getTime();

Get authorization info

$auth = $client->getCurrentAuthorization();

Lookup user info

$user = $client->getUser($userId);

Get current user

$user = $client->getCurrentUser();

Update current user

$user->setName('New Name');
$client->updateCurrentUser($user);

List all accounts

$accounts = $client->getAccounts();

List account details

$account = $client->getAccount($accountId);

List primary account details

$account = $client->getPrimaryAccount();

Set account as primary

$client->setPrimaryAccount($account);

Create a new bitcoin account

use Coinbase\Wallet\Resource\Account;

$account = new Account([
    'name' => 'New Account'
]);
$client->createAccount($account);

Update an account

$account->setName('New Account Name');
$client->updateAccount($account):

Delete an account

$client->deleteAccount($account);

List receive addresses for account

$addresses = $client->getAccountAddresses($account);

Get receive address info

$address = $client->getAccountAddress($account, $addressId);

List transactions for address

$transactions = $client->getAddressTransactions($address);

Create a new receive address

use Coinbase\Wallet\Resource\Address;

$address = new Address([
    'name' => 'New Address'
]);
$client->createAccountAddress($account, $address);

List transactions

$transactions = $client->getAccountTransactions($account);

Get transaction info

$transaction = $client->getAccountTransaction($account, $transactionId);

Send funds

use Coinbase\Wallet\Enum\CurrencyCode;
use Coinbase\Wallet\Resource\Transaction;
use Coinbase\Wallet\Value\Money;

$transaction = Transaction::send([
    'toBitcoinAddress' => 'ADDRESS',
    'amount'           => new Money(5, CurrencyCode::USD),
    'description'      => 'Your first bitcoin!',
    'fee'              => '0.0001' // only required for transactions under BTC0.0001
]);

try { $client->createAccountTransaction($account, $transaction); }
catch(Exception $e) {
     echo $e->getMessage(); 
}

Transfer funds to a new account

use Coinbase\Wallet\Resource\Transaction;
use Coinbase\Wallet\Resource\Account;

$fromAccount = Account::reference($accountId);

$toAccount = new Account([
    'name' => 'New Account'
]);
$client->createAccount($toAccount);

$transaction = Transaction::transfer([
    'to'            => $toAccount,
    'bitcoinAmount' => 1,
    'description'   => 'Your first bitcoin!'
]);

$client->createAccountTransaction($fromAccount, $transaction);

Request funds

use Coinbase\Wallet\Enum\CurrencyCode;
use Coinbase\Wallet\Resource\Transaction;
use Coinbase\Wallet\Value\Money;

$transaction = Transaction::request([
    'amount'      => new Money(8, CurrencyCode::USD),
    'description' => 'Burrito'
]);

$client->createAccountTransaction($transaction);

Resend request

$account->resendTransaction($transaction);

Cancel request

$account->cancelTransaction($transaction);

Fulfill request

$account->completeTransaction($transaction);

List buys

$buys = $client->getAccountBuys($account);

Get buy info

$buy = $client->getAccountBuy($account, $buyId);

Buy bitcoins

use Coinbase\Wallet\Resource\Buy;

$buy = new Buy([
    'bitcoinAmount' => 1
]);

$client->createAccountBuy($account, $buy);

Commit a buy

You only need to do this if you pass commit=false when you create the buy.

use Coinbase\Wallet\Enum\Param;

$client->createAccountBuy($account, $buy, [Param::COMMIT => false]);
$client->commitBuy($buy);

List sells

$sells = $client->getSells($account);

Get sell info

$sell = $client->getAccountSell($account, $sellId);

Sell bitcoins

use Coinbase\Wallet\Resource\Sell;

$sell = new Sell([
    'bitcoinAmount' => 1
]);

$client->createAccountSell($account, $sell);

Commit a sell

You only need to do this if you pass commit=false when you create the sell.

use Coinbase\Wallet\Enum\Param;

$client->createAccountSell($account, $sell, [Param::COMMIT => false]);
$client->commitSell($sell);

List deposits

$deposits = $client->getAccountDeposits($account);

Get deposit info

$deposit = $client->getAccountDeposit($account, $depositId);

Deposit funds

use Coinbase\Wallet\Enum\CurrencyCode;
use Coinbase\Wallet\Resource\Deposit;
use Coinbase\Wallet\Value\Money;

$deposit = new Deposit([
    'amount' => new Money(10, CurrencyCode::USD)
]);

$client->createAccountDeposit($account, $deposit);

Commit a deposit

You only need to do this if you pass commit=false when you create the deposit.

use Coinbase\Wallet\Enum\Param;

$client->createAccountDeposit($account, $deposit, [Param::COMMIT => false]);
$client->commitDeposit($deposit);

List withdrawals

$withdrawals = $client->getAccountWithdrawals($account);

Get withdrawal

$withdrawal = $client->getAccountWithdrawal($account, $withdrawalId);

Withdraw funds

use Coinbase\Wallet\Enum\CurrencyCode;
use Coinbase\Wallet\Resource\Withdrawal;
use Coinbase\Wallet\Value\Money;

$withdrawal = new Withdrawal([
    'amount' => new Money(10, CurrencyCode::USD)
]);

$client->createAccountWithdrawal($account, $withdrawal);

Commit a withdrawal

You only need to do this if you pass commit=true when you call the withdrawal method.

use Coinbase\Wallet\Enum\Param;

$client->createAccountWithdrawal($account, $withdrawal, [Param::COMMIT => false]);
$client->commitWithdrawal($withdrawal);

List payment methods

$paymentMethods = $client->getPaymentMethods();

Get payment method

$paymentMethod = $client->getPaymentMethod($paymentMethodId);

Get merchant

$merchant = $client->getMerchant($merchantId);

List orders

$orders = $client->getOrders();

Get order

$order = $client->getOrder($orderId);

Create order

use Coinbase\Wallet\Resource\Order;
use Coinbase\Wallet\Value\Money;

$order = new Order([
    'name' => 'Order #1234',
    'amount' => Money::btc(1)
]);

$client->createOrder($order);

Refund order

use Coinbase\Wallet\Enum\CurrencyCode;

$client->refundOrder($order, CurrencyCode::BTC);

Checkouts

List checkouts

$checkouts = $client->getCheckouts();

Create checkout

use Coinbase\Wallet\Resource\Checkout;

$params = array(
    'name'               => 'My Order',
    'amount'             => new Money(100, 'USD'),
    'metadata'           => array( 'order_id' => $custom_order_id )
);

$checkout = new Checkout($params);
$client->createCheckout($checkout);
$code = $checkout->getEmbedCode();
$redirect_url = "https://www.coinbase.com/checkouts/$code";

Get checkout

$checkout = $client->getCheckout($checkoutId);

Get checkout's orders

$orders = $client->getCheckoutOrders($checkout);

Create order for checkout

$order = $client->createNewCheckoutOrder($checkout);
$raw_body = file_get_contents('php://input');
$signature = $_SERVER['HTTP_CB_SIGNATURE'];
$authenticity = $client->verifyCallback($raw_body, $signature); // boolean

Contributing and testing

The test suite is built using PHPUnit. Run the suite of unit tests by running the phpunit command.

phpunit

There is also a collection of integration tests that issues real requests to the API and inspects the resulting objects. To run these tests, you must copy phpunit.xml.dist to phpunit.xml, provide values for the CB_API_KEY and CB_API_SECRET variables, and specify the integration group when running the test suite.

phpunit --group integration

coinbase-php's People

Contributors

aianus avatar chrisshennan avatar codermarcel avatar comeacoder avatar davidliedle avatar fero-sk avatar floranpagliai avatar gbutiri avatar go0sedev avatar hackinet avatar jborseth avatar jimbursch avatar jorilallo avatar jsgv avatar kamaelua avatar kriswallsmith avatar luiz-brandao avatar noplanman avatar renapoliveira avatar sds avatar sh6khan avatar sofwar avatar stefanyohansson avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

coinbase-php's Issues

Composer Autoload causes issue with OAuth

If you use composer and load your code like this:

    $coinbaseOauth = new \Coinbase_OAuth($client_id, $client_secret, $redirect);
    return new \Coinbase($coinbaseOauth, array(
         "refresh_token" => $this->getCustomerRefreshToken(),
         "access_token" => $this->getCustomerAccessToken(),
     ));

It will complain that you're redeclaring \Coinbase_Oauth. This is because the file it's loading for Coinbase is lib/Coinbase.php which does a bunch of superfluous (at least for composer) requires. We really want the file lib/Coinbase.php to have the contents of
lib/Coinbase/Coinbase.php.

Not sure how best to fix this as it seems like a refactor may be necessary.

getorder() always errors 'Order not found with that id'

For example:
$coinbase = Coinbase::withApiKey($_API_KEY, $_API_SECRET);
$buttoncode = $coinbase->createButton('name',0.001,'BTC')->button->code;
$order = $coinbase->createOrderFromButtonCode($buttoncode);
$id = $order->order->id;
$order = $coinbase->getorder($id);

Returns:

Fatal error: Uncaught exception 'Coinbase_ApiException' with message 'Order not found with that id' in /path/to/Coinbase/Rpc.php:107 Stack trace: #0 /path/to/Coinbase/Coinbase.php(64): Coinbase_Rpc->request('GET', 'orders/HC3ETHKD', Array) #1 /path/to/Coinbase/Coinbase.php(333): Coinbase->get('orders/HC3ETHKD', Array) #2 /path/to/c.php(24): Coinbase->getOrder('HC3ETHKD') #3 {main} thrown in /path/to/Coinbase/Rpc.php on line 107

UPDATE: This is returned when you check an order that has not had money send to it yet. After a while, the function completes with status 'expired'. I think this error should be handled within that API.

The variable_price option does not appear to work

I have had a look at the code and I am not sure why it does not work, however, every attempt to create a button with a variable price has failed. I have tested every other option and they work. Please fix this issue!

getSellPrice

https://api.coinbase.com/v1/prices/sell?qty=1
returns:

{"btc":{"amount":"1.00000000","currency":"BTC"},"subtotal":{"amount":"267.38","currency":"USD"},"fees":[{"coinbase":{"amount":"2.52","currency":"USD"}},{"bank":{"amount":"0.15","currency":"USD"}}],"total":{"amount":"264.71","currency":"USD"},"amount":"264.71","currency":"USD"}

but:

    public function getSellPrice($qty=1)
    {
        return $this->get("prices/sell", array( "qty" => $qty ))->amount;
    }


function getSellPrice(){
    global $coinbase;
    return $coinbase->getSellPrice();
}

returns:
string(7) "9801.00"

Error "Uncaught exception"

Hello

I'm getting this error for the create button

Fatal error: Uncaught exception 'Coinbase_ApiException' with message 'Status code 401' in C:\wamp\www\easypayonline\curly\add-ons\coinbase-php\lib\Coinbase\Requestor.php:23 Stack trace: #0 C:\wamp\www\easypayonline\curly\add-ons\coinbase-php\lib\Coinbase\Rpc.php(70): Coinbase_Requestor->doCurlRequest(Resource id #15) #1 C:\wamp\www\easypayonline\curly\add-ons\coinbase-php\lib\Coinbase\Coinbase.php(39): Coinbase_Rpc->request('POST', 'buttons', Array) #2 C:\wamp\www\easypayonline\curly\add-ons\coinbase-php\lib\Coinbase\Coinbase.php(175): Coinbase->post('buttons', Array) #3 C:\wamp\www\easypayonline\curly\add-ons\coinbase-php\lib\Coinbase\Coinbase.php(169): Coinbase->createButtonWithOptions(Array) #4 C:\wamp\www\easypayonline\curly\add-ons\checkoutbc.php(30): Coinbase->createButton('Your Order #123...', '42.95', 'EUR', 'my custom track...', Array) #5 C:\wamp\www\easypayonline\curly\checkout.php(344): include('C:\wamp\www\eas...') #6 {main} thrown in C:\wamp\www\easypayonline\curly\add-ons\coinbase-php\lib\Coinbase\Requestor.php on line 23

When I try to do the try // catch I get this

object(Coinbase_ApiException)#4 (8) { ["message:protected"]=> string(15) "Status code 401" ["string:private"]=> string(0) "" ["code:protected"]=> int(0) ["file:protected"]=> string(79) "C:\wamp\www\easypayonline\curly\add-ons\coinbase-php\lib\Coinbase\Requestor.php" ["line:protected"]=> int(22) ["trace:private"]=> array(6) { [0]=> array(6) { ["file"]=> string(73) "C:\wamp\www\easypayonline\curly\add-ons\coinbase-php\lib\Coinbase\Rpc.php" ["line"]=> int(70) ["function"]=> string(13) "doCurlRequest" ["class"]=> string(18) "Coinbase_Requestor" ["type"]=> string(2) "->" ["args"]=> array(1) { [0]=> resource(15) of type (Unknown) } } [1]=> array(6) { ["file"]=> string(78) "C:\wamp\www\easypayonline\curly\add-ons\coinbase-php\lib\Coinbase\Coinbase.php" ["line"]=> int(39) ["function"]=> string(7) "request" ["class"]=> string(12) "Coinbase_Rpc" ["type"]=> string(2) "->" ["args"]=> array(3) { [0]=> string(4) "POST" [1]=> string(7) "buttons" [2]=> array(1) { ["button"]=> array(5) { ["name"]=> string(16) "Your Order #1234" ["price_string"]=> string(5) "42.95" ["price_currency_iso"]=> string(3) "EUR" ["custom"]=> string(38) "my custom tracking code for this order" ["description"]=> string(17) "1 widget at 42.95" } } } } [2]=> array(6) { ["file"]=> string(78) "C:\wamp\www\easypayonline\curly\add-ons\coinbase-php\lib\Coinbase\Coinbase.php" ["line"]=> int(175) ["function"]=> string(4) "post" ["class"]=> string(8) "Coinbase" ["type"]=> string(2) "->" ["args"]=> array(2) { [0]=> string(7) "buttons" [1]=> array(1) { ["button"]=> array(5) { ["name"]=> string(16) "Your Order #1234" ["price_string"]=> string(5) "42.95" ["price_currency_iso"]=> string(3) "EUR" ["custom"]=> string(38) "my custom tracking code for this order" ["description"]=> string(17) "1 widget at 42.95" } } } } [3]=> array(6) { ["file"]=> string(78) "C:\wamp\www\easypayonline\curly\add-ons\coinbase-php\lib\Coinbase\Coinbase.php" ["line"]=> int(169) ["function"]=> string(23) "createButtonWithOptions" ["class"]=> string(8) "Coinbase" ["type"]=> string(2) "->" ["args"]=> array(1) { [0]=> array(5) { ["name"]=> string(16) "Your Order #1234" ["price_string"]=> string(5) "42.95" ["price_currency_iso"]=> string(3) "EUR" ["custom"]=> string(38) "my custom tracking code for this order" ["description"]=> string(17) "1 widget at 42.95" } } } [4]=> array(6) { ["file"]=> string(54) "C:\wamp\www\easypayonline\curly\add-ons\checkoutbc.php" ["line"]=> int(26) ["function"]=> string(12) "createButton" ["class"]=> string(8) "Coinbase" ["type"]=> string(2) "->" ["args"]=> array(5) { [0]=> string(16) "Your Order #1234" [1]=> string(5) "42.95" [2]=> string(3) "EUR" [3]=> string(38) "my custom tracking code for this order" [4]=> array(1) { ["description"]=> string(17) "1 widget at 42.95" } } } [5]=> array(4) { ["file"]=> string(44) "C:\wamp\www\easypayonline\curly\checkout.php" ["line"]=> int(344) ["args"]=> array(1) { [0]=> string(54) "C:\wamp\www\easypayonline\curly\add-ons\checkoutbc.php" } ["function"]=> string(7) "include" } } ["http_code"]=> int(401) ["response"]=> string(1) " " }

Could you please help me find where is this going wrong?

Thank you.

Client::createAccountAddress void

Hi all,

After testing some api i found, on your docs, that we can create an account address.

use Coinbase\Wallet\Resource\Address;

$address = new Address([
    'name' => 'New Address'
]);
$client->createAccountAddress($account, $address);

the problem is that createAccountAddress() don't return anything. So, we don't have access to newly generated ResourceCollection|Address.

Maybe you should change $client->createAccountAddress from:

     $this->postAndMap(..);
}

to

     return $this->postAndMap(..);
}

what do you think?

best
FA

Intialize Coinbase object with OAuth tokens

I know there are multiple ways to initialize the Coinbase object. If using your API Key, you can write this:

$coinbase = new Coinbase($api_key); 

The issue I'm having is how to write the Coinbase object using the OAuth access/refresh tokens AFTER authenticating.

During authentication, you write this:

$coinbase = new Coinbase($coinbaseOauth, $tokens);

However, as $coinbaseOauth only appears capable of being set during the OAuth step, I'm wondering else can you make use of the $tokens.

Thoughts?

getExchangeRate

getExchangeRate currently is pulling 10000.00 in the sandbox
yet on coinbase it showing 1 BTC is 10100.00
http://prntscr.com/7qg591

Does it do this on non sandbox too? api not current with live time tracking of values?

OAuth redirect url issue

I can't get any redirect urls to work including the example one:

// Note: your redirect URL should use HTTPS. $_REDIRECT_URL = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];

The documentation says to use https, but that doesn't work for me either. The error message is always The redirect uri included is not valid.

Can there be more documentation on this? And an example of a working url?

Unrecognized resource type: application

Hi all!

I'm getting this error when I'm running
$account = $client->getAccount($wallet); $address = $client->getAccountAddress($account,$address_id); $transactionaddr = $client->getAddressTransactions($address);

ERROR : Unrecognized resource type: application

I have tested getApplication() and had no luck so far.

It looks like the API can't check the transactions from Coinbase mobile Apps.
Am I doing something wrong?

Thanks in advance for your help!

Status code 409

PHP Fatal error: Uncaught exception 'Coinbase_ApiException' with message 'Status code 409'

409 Conflict

The request could not be completed due to a conflict with the current state of the resource. This code is only allowed in situations where it is expected that the user might be able to resolve the conflict and resubmit the request. The response body SHOULD include enough

information for the user to recognize the source of the conflict. Ideally, the response entity would include enough information for the user or user agent to fix the problem; however, that might not be possible and is not required.

Conflicts are most likely to occur in response to a PUT request. For example, if versioning were being used and the entity being PUT included changes to a resource which conflict with those made by an earlier (third-party) request, the server might use the 409 response to indicate that it can't complete the request. In this case, the response entity would likely contain a list of the differences between the two versions in a format defined by the response Content-Type.

PHP Fatal error: Uncaught exception 'Coinbase_ApiException' with message 'Status code 409' in /var/www/html/api/coinbase-php/lib/Coinbase/Requestor.php:22\nStack trace:\n#0 /var/www/html/api/coinbase-php/lib/Coinbase/Rpc.php(95): Coinbase_Requestor->doCurlRequest(Resource id #1)\n#1 /var/www/html/api/coinbase-php/lib/Coinbase/Coinbase.php(64): Coinbase_Rpc->request('GET', 'accounts/5588a7...', Array)\n#2 /var/www/html/api/coinbase-php/lib/Coinbase/Coinbase.php(104): Coinbase->get('accounts/5588a7...', Array)\n#3 /var/www/html/api/coinbase-php/functions.php(149): Coinbase->getbtcaddress('5588a7bc9e97f8c...')\n#4 /var/www/html/api/coinbase-php/functions.php(22): getAllAddresses(2)\n#5 /var/www/html/header.php(1): require_once('/var/www/html/a...')\n#6 /var/www/html/index.php(5): include('/var/www/html/h...')\n#7 {main}\n thrown in /var/www/html/api/coinbase-php/lib/Coinbase/Requestor.php on line 22

"API Key + Secret" Authentication Not Supported

The new authentication using an API Key + Secret is not implemented in this library. In fact I've been trying to implement this myself, but keep running into "Whoops! It looks like we encountered a problem." errors. There seems to be a shortage of working examples for this new authentication method...

How to get transaction status and id on transaction using coinbase button

i wrote the code like this.but it fails. any other methods to get the status and id

response = $coinbase->createButton("Your Order #1234", "0.0003", "BTC", "my custom tracking code for this order", array(
"description" => "1 widget at €42.95"
));

$response->embedHtml;

$response->success ? 'true' : 'false';
// 'true'
$status=$response->transaction->status;
// 'pending'
$id=$response->transaction->id;

is_a() is Deprecated

Getting this when operating in strict standards mode:

Unknown: is_a(): Deprecated. Please use the instanceof operator in /path/Coinbase/Coinbase.php on line 29

I'm happy to submit a pull request to fix this if needs be.

Coinbase createAccountAddress() returns null, address will be generated

When using this code it shows null all the time, but a new address is generated. What's wrong with coinbase API?

$configuration = Configuration::apiKey("xy", "xy");
    $client = Client::create($configuration);


    $account = $client->getPrimaryAccount();
    $address = new Address([
        'name' => null
    ]);

   $return =  $client->createAccountAddress($account, $address);

   die((var_dump($return));

Need a way to lookup the old V1 API Coinbase order using CoinbaseV2 API

Currently we are using Coinbase v1 APIs for our merchant solution and have following information in callback url

{"order":{"id":"W28I95JR","uuid":"f690517b-d19d-5b91-af9a-7cfe9891501e","resource_path":"/v2/orders/f690517b-d19d-5b91-af9a-7cfe9891501e","metadata":null,"created_at":"2016-06-05T01:01:53-07:00","status":"completed","event":{"type":"completed"}........

We as a merchant store, id (OIrderNumber) (eg. W28I95JR , in coinbase V2 API its refer as Code field) in our system and order can be looked by by V1 API using orders/ by passing id (W28I95JR) to get all relevant information.

Now we are planning to use Coinbase V2 api and we have only information stored is coinbase order Number( id field in above example i.e W28I95JR) ,and we want to look up an order using this Order Number,and we are not finding any way to lookup order using V2 API.

We found V2 API (/v2/orders/) to lookup the order but it need the uuid field to be passed and not worked by passing the Order Number.

Can you please suggest how to lookup the old V1 orders using V2 Coinbase API using Order Number (id field) ?

Error when sending funds

Hi guys , I'm having an error when sending funds , the code I am using is this:

$transacao = Transaction::send();

    $transacao->setToBitcoinAddress($endereco);
    $transacao->setAmount(new Money($montante, CurrencyCode::BTC));
    $transacao->setDescription($description);

 try {
        $client->createAccountTransaction($conta, $transacao);
    } catch (ClientException $e) {
        $e->getRequest();
        $e->getRespose();
    }

When I open the page I get this error:

Fatal error: Uncaught exception 'InvalidArgumentException' with message 'Invalid resource type: boolean' in /home/u951323236/public_html/php/vendor/guzzlehttp/psr7/src/functions.php:113 Stack trace: #0 /home/u951323236/public_html/php/vendor/guzzlehttp/guzzle/src/Client.php(360): GuzzleHttp\Psr7\stream_for(false) #1 /home/u951323236/public_html/php/vendor/guzzlehttp/guzzle/src/Client.php(264): GuzzleHttp\Client->applyOptions(Object(GuzzleHttp\Psr7\Request), Array) #2 /home/u951323236/public_html/php/vendor/guzzlehttp/guzzle/src/Client.php(98): GuzzleHttp\Client->transfer(Object(GuzzleHttp\Psr7\Request), Array) #3 /home/u951323236/public_html/php/vendor/guzzlehttp/guzzle/src/Client.php(104): GuzzleHttp\Client->sendAsync(Object(GuzzleHttp\Psr7\Request), Array) #4 /home/u951323236/public_html/php/vendor/coinbase/coinbase/src/HttpClient.php(135): GuzzleHttp\Client->send(Object(GuzzleHttp\Psr7\Request), Array) #5 /home/u951323236/public_html/php/vendor/coinbase/coinbase/src/HttpClient.php(121): Coinbase\Wallet\HttpClient->send in /home/u951323236/public_html/php/vendor/guzzlehttp/psr7/src/functions.php on line 113

Sorry for my english 😄

can't autoload with composer

the composer.json need fix the authload psr-0 key:

now: "psr-0": {"Coinbase_": "lib/"}

it should be : "psr-0": {"Coinbase": "lib/"}

Unhandled exception on createAccountBuy

Hi guys, I can't seem to find any way of dealing with the Fatal Exception that I receive when using the following:

`
$client = Client::create($configuration);

$account = $client->getPrimaryAccount();

$buy = new Buy([
    'bitcoinAmount' => $tokens['amount']
    ]);

try {

    $client->createAccountBuy($account, $buy);

} catch (ClientException $e) {

    var_dump($e->getResponse()); die;

}

}`

Which works fine if the user has sufficient funds in their account to buy the btc with. However, if an error response is sent back instead, I get a message like:

Fatal error: Uncaught exception 'GuzzleHttp\Exception\ClientException' with message 'Client error: POST https://api.sandbox.coinbase.com/v2/accounts/555d9af2-d78b-5ce5-9a1f-031f394a3a51/buys resulted in a 422 Unprocessable Entity response:
{"errors":[{"id":"validation_error","message":"This would exceed your bank purchase limit of $1,000.00 per day. Please w (truncated...)
' in /home/coinbase/httpdocs/include/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:107
Stack trace:
#0 /home/coinbase/httpdocs/include/vendor/guzzlehttp/guzzle/src/Middleware.php(65): GuzzleHttp\Exception\RequestException::create(Object(GuzzleHttp\Psr7\Request), Object(GuzzleHttp\Psr7\Response))
#1 /home/coinbase/httpdocs/include/vendor/guzzlehttp/promises/src/Promise.php(201): GuzzleHttp\Middleware::GuzzleHttp{closure}(Object(GuzzleHttp\Psr7\Response))
#2 /home/coinbase/httpdocs/include/vendor/guzzlehttp/promises/src/Promise.php(154): GuzzleHttp\Promise\Promise::callHandler(1, Object(Gu in /home/

I asked how I could resolve this on the coinbase forum and was told to log an issue here, so I have.

Thanks in advance!

simpletest/autorun.php is missing.

Warning: require_once(H:\xampp\htdocs\prepaidvcardcom\order\coinbase\coinbase\test/simpletest/autorun.php): failed to open stream: No such file or directory in H:\xampp\htdocs\prepaidvcardcom\order\coinbase\coinbase\test\Coinbase.php on line 2

simpletest/autorun.php is missing. please uload this file.

Coinbase Mod

I have PHP Pro BId v11 and i installed the coinbase mod,it was working good till it stopped,,Anyone for help?

Fatal error: Uncaught exception 'Coinbase_ConnectionException' with message 'Network error error:0D0890A1:asn1 encoding routines:func(137):reason(161) (35)' in /home/bitcoins/public_html/includes/lib/Coinbase/Requestor.php:15 Stack trace: #0 /home/bitcoins/public_html/includes/lib/Coinbase/Rpc.php(70): Coinbase_Requestor->doCurlRequest(Resource id #146) #1 /home/bitcoins/public_html/includes/lib/Coinbase/Coinbase.php(39): Coinbase_Rpc->request('POST', 'buttons', Array) #2 /home/bitcoins/public_html/includes/lib/Coinbase/Coinbase.php(178): Coinbase->post('buttons', Array) #3 /home/bitcoins/public_html/includes/lib/Coinbase/Coinbase.php(172): Coinbase->createButtonWithOptions(Array) #4 /home/bitcoins/public_html/includes/class_fees.php(127): Coinbase->createButton('Direct Payment ...', 0.16, 'BTC', '43TBL50', Array) #5 /home/bitcoins/public_html/includes/class_fees.php(1008): fees->form_bitcoin('43TBL50', '28a3b1fecfdb991...', 0.16, 'BTC', false, 'Direct Payment ...') #6 /home/bitcoins/public_html/includes/class_item.php(36 in /home/bitcoins/public_html/includes/lib/Coinbase/Requestor.php on line 15

Documentation for get()

Tiny issue, but I banged my head against the wall for hours...

In the documentation you show:

var_dump($coinbase->get('/account/balance'));

For get() to work, you need to leave off the initial slash:

var_dump($coinbase->get('account/balance'));

Authentication issue Coinbase

We are getting the following error when we try to connect our merchant account to coinbase "Sorry, but there was an error while connecting your account (Could not get tokens - code 401)" anyone have any ideas how to overcome this issue? We are using Coinbase Magento extension and it installed seamlessly. It is when we go to connect from our store to coinbase that we get the error.

createButton() error

I copy pasted the code on the Readme (php version) and everything seems to be working quite well. However I get the following error when I try to create a payment button using $coinbase->createButton()

Fatal error: Uncaught exception 'Coinbase_ApiException' with message 'Invalid response body' in ....

Unhandled exception in createAccountTransaction() if bad tx data is given

If createAccountTransaction is called with a transaction with an invalid address, or an amount is given that can't be sent, the following error is thrown:

Fatal error: Uncaught exception 'GuzzleHttp\Exception\ClientException' with message 'Client error: 422'

Code to reproduce:

<?php
  require_once('vendor/autoload.php');

  use Coinbase\Wallet\Client;
  use Coinbase\Wallet\Configuration;
  use Coinbase\Wallet\Resource\Transaction;
  use Coinbase\Wallet\Value\Money;
  use Coinbase\Wallet\Enum\CurrencyCode;
  use Coinbase\Wallet\Value\Fee;
  use Coinbase\Wallet\Enum\Param;
  use Coinbase\Wallet\Resource\Address;

  $apiKey="apikey";
  $apiSecret="apisecret";

  # a bad address and/or an invalid amount will cause the issue
  $address = 'bad_address';
  $btcvalue = 'amount_greater_than_wallet_balance';

  $configuration=Configuration::apiKey($apiKey, $apiSecret);
  $client=Client::create($configuration);
  $account=$client -> getPrimaryAccount();
  $transaction = Transaction::send([
    'toBitcoinAddress' => $address,
    'amount' => new Money($btcvalue, CurrencyCode::BTC),
    'description' => "bad transaction"
  ]);
  $client->createAccountTransaction($account, $transaction);
  echo $transaction->getId();
?>

More discussion here:
https://community.coinbase.com/t/getting-status-result-php/8427/4
https://community.coinbase.com/t/error-guzzlehttp/7577/3

Can't Authenticate Using Built-In Functions

What am I doing wrong? I'm following the documentation. I'm providing the correct headers but keeps failing.

$configuration = Configuration::apiKey($apiKey, $apiSecret);
$authentication = $configuration->getAuthentication();

$headers = $auth->getRequestHeaders('GET', '/v2/prices/buy?currency=USD', '');
$headers['CB-VERSION'] = Configuration::DEFAULT_API_VERSION;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.coinbase.com/v2/prices/buy?currency=USD");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_CAINFO, __DIR__ . "/vendor/coinbase/coinbase/etc/ca-coinbase.crt");

$response = curl_exec($ch);

var_dump($response);

curl_close($ch);

The result, with the headers (replaced a fake access key for posting):

array(4) {
  ["CB-ACCESS-KEY"]=>
  string(16) "KJSDKFJLDSFIJ"
  ["CB-ACCESS-SIGN"]=>
  string(64) "ceb8b94e246b894a9636808640bdd9c2fab3c1b9d16372aff2b184cbbe76bd95"
  ["CB-ACCESS-TIMESTAMP"]=>
  int(1440100264)
  ["CB-VERSION"]=>
  string(10) "2015-07-07"
}
string(240) "{"errors":[{"id":"invalid_token","message":"The access token is invalid"}],"warnings":[{"id":"missing_version","message":"Please supply API version (YYYY-MM-DD) as CB-VERSION header","url":"https://developers.coinbase.com/api#versioning"}]}"

So, my headers look correct according to the docs. I'm providing CB-VERSION. I don't get it.

try catch

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

//catch exception
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}

above is an example of a try catch..
I noticed a lot of calls do not have try catch and will error our the website if =using the coinbase-php class.
I would like to request someone go in and use try catch to prevent fatal errors.

inside line 22 of Requestor.php

Is there a "SEND MANY" function... To send to several BTC addresses at once??

Is there a "SEND MANY" function... To send to several BTC addresses at once??
I'm looking to implement your api on my website but I'm not sure how I would send to many addresses in one transaction.

I need this to reduce transaction fees. I'm sending lots of little transactions to many different addresses.

Thanks in advance.

getExchangeRates method declaration doesn't match API

The declaration for getExchanceRates in the PHP client is expecting an array but the API is expecting a string. If you send just a string via the PHP classes, it returns warnings about the data type and the API assumes USD. If you wrap the currency in an array, the server still returns the base currency as USD even if it was BTC.

e.g.
$response = $this->client->getExchangeRates(array($base_currency));

Server doc
https://developers.coinbase.com/api/v2#exchange-rates

Price can't be blank

Hi,
I'm having an issue with creating buttons... When I first tried it in April it worked...
Now I get the error "Price can't be blank" - even with the example (ApiKeyExample.php).

Kind regards
Mario

BTW, the response from the Server is:
array(2) { ["statusCode"]=> int(200) ["body"]=> string(515) "{"success":false,"errors":["Price can't be blank"],"button":{"code":"fd0f6d06b7e7b02cd9049ea9b79fd63b","type":"buy_now","subscription?":false,"repeat":null,"style":"buy_now_large","text":"Pay With Bitcoin","name":"Alpaca socks","description":"","custom":"","callback_url":null,"success_url":null,"cancel_url":null,"info_url":null,"auto_redirect":false,"auto_redirect_success":false,"auto_redirect_cancel":false,"price":null,"variable_price":false,"choose_price":false,"include_address":false,"include_email":false}}" }

api v2

v2 has a new auth must update it here,
also consider passing which api to use in a config, along with sandbox/prod url endpoints.

account_id option for /api/v1/buttons

'account_id' is the first parameter listed at https://coinbase.com/api/doc/1.0/buttons/create.html
but there aren't any examples with it.

I was trying to specify for which account the button is created. The default is your primary account. After reviewing the code it did not seem to be included.

I thought it would be as simple as adding a property to the coinbase class 'walletname' and modifying the function createButtonWithOptions() to include something like
if ( $this->walletname == null ) {
$response = $this->post("buttons", array("button" => $options ));
} else {
$response = $this->post("buttons", array("account_id" => $this->walletname, "button" => $options ));
}

I could not seem to get that working. Any ideas why? Could it have something to do with the way the curl options are formatted in the Coinbase_Rpc class. Or the way the server expects the options to be formatted?

Any help would be appreciated. Thank you.

Sandbox Api keys are not working

Hi,

For testing, I created a sandbox account and new API tokens. But, everytime I request anything using that, I get this:

Coinbase_ApiException
Status code 401

Please help.

IPN documentation is unclear

I couldn't find a better place to open this issue!

Regarding: https://coinbase.com/docs/merchant_tools/callbacks

A. The order IPN documentation is unclear about the difference between event and status.
B. The full set of values for event and status is never documented. Status is documented is being completed or cancelled, but I see elsewhere that it can also be new.
C. The Status documentation says "see below for cancellation details" but no other details exist on that page regarding "cancellations".
D. If the Event is mispayment, what will the Status be?
E. If the Status is canceled, what will Event be?
F. Are there any other undocumented values and which takes precedence, Status or Events?

Success URL and Cancel URL

I have an issue when creating a button. callback_url is working fine and get the right json response, but after that redirecting to success_url or cancel_url is not happening, it stays on the same page displaying PAID. I've verified the URLs and they are fine, but is not redirecting automatically. Here is the source code:

        $response = $coinbase->createButton(
            $job_title, 
            $price,
            $currency, 
            $pid, 
            array(
                    "description" => $job_title,
                    "callback_url" => $callback_url,
                    "success_url" => $success_url,
                    "cancel_url" =>  $cancel_url
                ));

        echo $response->embedHtml;

Unrecognized resource type: bitcoin_network

Mapper fails when calling $client->getAccountTransactions($account) and the returned transaction has originated from bitcoin network (no way to map into an object). Example transaction:

{
  "id": "eb6620e4-995d-5542-adda-dcaf3537705d",
  "type": "send",
  ...
  "from": {
    "resource": "bitcoin_network"
  }
}

worst details ever on github

i do not understand why you guys not give proper information. if you update composer it will give lib of api v1 but of not v2. Please check details and give proper documentation before release.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.