search
HomeBackend DevelopmentPHP TutorialHow to use PHP to develop applications using the Bitcoin Coinbase wallet library (detailed steps)

The content of this article is about how to use the Bitcoin Coinbase wallet library to develop applications in PHP (detailed steps). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

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

Important: Since this library is targeting the newer API v2, v2 permissions are required (i.e. wallet:accounts:read). If you are still using v1, please use an older version of this library.

Installation

Use Composer to install the library. If you are not familiar with Composer or the dependency manager, please read the Composer documentation.

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

Authentication

API Key

Use the API key and secret key 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 user accounts other than your own. This library does not handle the handshake process and assumes you have the access token at initialization time. You can use an OAuth2 client (such as league/oauth2-client) to handle the handshake process.

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 Funds endpoint requires a 2FA token in some cases (read more here). Throws a specific exception if needed.

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

$transaction = Transaction::send([
    'toEmail' => 'test@test.com',
    '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',
    ]);
}

Paging

Several endpoints are paginated. By default, the library only fetches 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 make all the necessary requests to load the complete collection.

use Coinbase\Wallet\Enum\Param;

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

WARNING

It is wise to heed the warnings. If a standard PSR-3 logger is configured, the library will log all warnings.

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

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

Resource Reference

In some cases, the API will return a resource reference in place of the extended resource object. These references can be extended by refreshing.

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

You can also use the expand parameter request API to return expanded resources in the initial request.

use Coinbase\Wallet\Enum\Param;

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

You can use resource references when creating new resources, thereby avoiding the overhead of requesting resources 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
]);

Response

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

$data = $deposit->getRawData();

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

$data = $client->decodeLastResponse();

Active Recording Methods

This library includes support for the Active Recording method on resource objects. You must enable this feature when booting the application.

$client->enableActiveRecord();

When enabled, you can call active recording 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. See the official documentation for more details.

Market Data

List supported local 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();

User

Get authorization information

$auth = $client->getCurrentAuthorization();

Find user information

$auth = $client->getCurrentAuthorization();

Get current user

$user = $client->getCurrentUser();

Update current user

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

Account

List all accounts

$accounts = $client->getAccounts();

List account details

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

List primary account details

$account = $client->getPrimaryAccount();

Make account primary

$client->setPrimaryAccount($account);

Create a new Bitcoin account

use Coinbase\Wallet\Resource\Account;

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

Update account

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

Delete account

$client->deleteAccount($account);

Address

List the receiving address of the account

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

Get the receiving address information

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

List the transaction of the address

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

Create a new receiving address

use Coinbase\Wallet\Resource\Address;

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

Transaction

List transaction list

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

Get transaction information

$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 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);

Apply 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);

Complete request

$account->completeTransaction($transaction);

Buy

List purchase

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

Get purchase information

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

Buy Bitcoin

use Coinbase\Wallet\Resource\Buy;

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

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

Purchase confirmation

This only needs to be done if commit=false is passed when creating the purchase.

use Coinbase\Wallet\Enum\Param;

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

Sell

Sell List

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

Get Sales Information

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

Sell Bitcoin

use Coinbase\Wallet\Resource\Sell;

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

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

Sell Confirmation

This only needs to be done if commit=false is passed when creating the sell.

use Coinbase\Wallet\Enum\Param;

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

Deposit

List deposit list

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

Get deposit information

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

Deposit

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);

Submit deposit

This only needs to be done if commit=false is passed when creating the deposit.

use Coinbase\Wallet\Enum\Param;

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

Withdrawal

List withdrawal order

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

Cancel

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

Withdrawal

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);

Submit exit

This only needs to be done if commit=true is passed when calling the withdrawal method.

use Coinbase\Wallet\Enum\Param;

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

Payment methods

List payment methods

$paymentMethods = $client->getPaymentMethods();

Get payment methods

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

Merchant

Get merchant

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

Order

List Order

$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);

Checkout

List Checkout

$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";

Checkout

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

Get Checkout Order

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

Create Checkout Account order

$order = $client->createNewCheckoutOrder($checkout);

通知webhook和验证

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

贡献和测试

测试套件使用PHPUnit构建。通过运行phpunit命令运行单元测试套件。

phpunit

还有一组集成测试,它们向API发出实际请求并检查生成的对象。要运行这些测试,必须将phpunit.xml.dist复制到phpunit.xml,为CB_API_KEYCB_API_SECRET变量提供值,并在运行测试套件时指定integration组。

phpunit --group integration

The above is the detailed content of How to use PHP to develop applications using the Bitcoin Coinbase wallet library (detailed steps). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault思否. If there is any infringement, please contact admin@php.cn delete
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software