Table of Contents
Installation
Authentication
API Key
OAuth2
Two-Factor Authentication
Paging
WARNING
Resource Reference
Response
Active Recording Methods
Usage
Market Data
User
Account
Address
Transaction
Buy
Sell
Deposit
Withdrawal
Payment methods
Merchant
Order
Checkout
通知webhook和验证
贡献和测试
Home Backend Development PHP Tutorial How to use PHP to develop applications using the Bitcoin Coinbase wallet library (detailed steps)

How to use PHP to develop applications using the Bitcoin Coinbase wallet library (detailed steps)

Oct 19, 2018 pm 03:50 PM
php Blockchain rear end Bitcoin programmer

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"
}
Copy after login

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);
Copy after login

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);
Copy after login

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',
    ]);
}
Copy after login

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);
}
Copy after login

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,
]);
Copy after login

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);
Copy after login

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);
}
Copy after login

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'],
]);
Copy after login

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
]);
Copy after login

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();
Copy after login

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

$data = $client->decodeLastResponse();
Copy after login

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();
Copy after login

When enabled, you can call active recording methods on resource objects.

use Coinbase\Wallet\Enum\Param;

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

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();
Copy after login

List exchange rates

$rates = $client->getExchangeRates();
Copy after login

Buy price

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

Sell price

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

Spot price

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

Current server time

$time = $client->getTime();
Copy after login

User

Get authorization information

$auth = $client->getCurrentAuthorization();
Copy after login
Copy after login

Find user information

$auth = $client->getCurrentAuthorization();
Copy after login
Copy after login

Get current user

$user = $client->getCurrentUser();
Copy after login

Update current user

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

Account

List all accounts

$accounts = $client->getAccounts();
Copy after login

List account details

$account = $client->getAccount($accountId);
Copy after login

List primary account details

$account = $client->getPrimaryAccount();
Copy after login

Make account primary

$client->setPrimaryAccount($account);
Copy after login

Create a new Bitcoin account

use Coinbase\Wallet\Resource\Account;

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

Update account

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

Delete account

$client->deleteAccount($account);
Copy after login

Address

List the receiving address of the account

$addresses = $client->getAccountAddresses($account);
Copy after login

Get the receiving address information

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

List the transaction of the address

$transactions = $client->getAddressTransactions($address);
Copy after login

Create a new receiving address

use Coinbase\Wallet\Resource\Address;

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

Transaction

List transaction list

$transactions = $client->getAccountTransactions($account);
Copy after login

Get transaction information

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

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(); 
}
Copy after login

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);
Copy after login

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);
Copy after login

Resend request

$account->resendTransaction($transaction);
Copy after login

Cancel request

$account->cancelTransaction($transaction);
Copy after login

Complete request

$account->completeTransaction($transaction);
Copy after login

Buy

List purchase

$buys = $client->getAccountBuys($account);
Copy after login

Get purchase information

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

Buy Bitcoin

use Coinbase\Wallet\Resource\Buy;

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

$client->createAccountBuy($account, $buy);
Copy after login

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);
Copy after login

Sell

Sell List

$sells = $client->getAccountSells($account);
Copy after login

Get Sales Information

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

Sell Bitcoin

use Coinbase\Wallet\Resource\Sell;

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

$client->createAccountSell($account, $sell);
Copy after login

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);
Copy after login

Deposit

List deposit list

$deposits = $client->getAccountDeposits($account);
Copy after login

Get deposit information

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

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);
Copy after login

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);
Copy after login

Withdrawal

List withdrawal order

$withdrawals = $client->getAccountWithdrawals($account);
Copy after login

Cancel

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

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);
Copy after login

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);
Copy after login

Payment methods

List payment methods

$paymentMethods = $client->getPaymentMethods();
Copy after login

Get payment methods

$paymentMethod = $client->getPaymentMethod($paymentMethodId);
Copy after login

Merchant

Get merchant

$merchant = $client->getMerchant($merchantId);
Copy after login

Order

List Order

$orders = $client->getOrders();
Copy after login

Get Order

$order = $client->getOrder($orderId);
Copy after login

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);
Copy after login

Refund Order

use Coinbase\Wallet\Enum\CurrencyCode;

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

Checkout

List Checkout

$checkouts = $client->getCheckouts();
Copy after login

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";
Copy after login

Checkout

$checkout = $client->getCheckout($checkoutId);
Copy after login

Get Checkout Order

$orders = $client->getCheckoutOrders($checkout);
Copy after login

Create Checkout Account order

$order = $client->createNewCheckoutOrder($checkout);
Copy after login

通知webhook和验证

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

贡献和测试

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

phpunit
Copy after login

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

phpunit --group integration
Copy after login

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Top 10 Digital Virtual Currency Apps Rankings: Top 10 Digital Currency Exchanges in Currency Circle Trading Top 10 Digital Virtual Currency Apps Rankings: Top 10 Digital Currency Exchanges in Currency Circle Trading Apr 22, 2025 pm 03:00 PM

The top ten digital virtual currency apps are: 1. OKX, 2. Binance, 3. gate.io, 4. Coinbase, 5. Kraken, 6. Huobi, 7. KuCoin, 8. Bitfinex, 9. Bitstamp, 10. Poloniex. These exchanges are selected based on factors such as transaction volume, user experience and security, and all provide a variety of digital currency trading services and an efficient trading experience.

Meme Coin Exchange Ranking Meme Coin Main Exchange Top 10 Spots Meme Coin Exchange Ranking Meme Coin Main Exchange Top 10 Spots Apr 22, 2025 am 09:57 AM

The most suitable platforms for trading Meme coins include: 1. Binance, the world's largest, with high liquidity and low handling fees; 2. OkX, an efficient trading engine, supporting a variety of Meme coins; 3. XBIT, decentralized, supporting cross-chain trading; 4. Redim (Solana DEX), low cost, combined with Serum order book; 5. PancakeSwap (BSC DEX), low transaction fees and fast speed; 6. Orca (Solana DEX), user experience optimization; 7. Coinbase, high security, suitable for beginners; 8. Huobi, well-known in Asia, rich trading pairs; 9. DEXRabbit, intelligent

The latest updates to the oldest virtual currency rankings The latest updates to the oldest virtual currency rankings Apr 22, 2025 am 07:18 AM

The ranking of virtual currencies’ “oldest” is as follows: 1. Bitcoin (BTC), issued on January 3, 2009, is the first decentralized digital currency. 2. Litecoin (LTC), released on October 7, 2011, is known as the "lightweight version of Bitcoin". 3. Ripple (XRP), issued in 2011, is designed for cross-border payments. 4. Dogecoin (DOGE), issued on December 6, 2013, is a "meme coin" based on the Litecoin code. 5. Ethereum (ETH), released on July 30, 2015, is the first platform to support smart contracts. 6. Tether (USDT), issued in 2014, is the first stablecoin to be anchored to the US dollar 1:1. 7. ADA,

What are the digital currency trading apps suitable for beginners? Learn about the coin circle in one article What are the digital currency trading apps suitable for beginners? Learn about the coin circle in one article Apr 22, 2025 am 08:45 AM

When choosing a digital currency trading platform suitable for beginners, you need to consider security, ease of use, educational resources and cost transparency: 1. Priority is given to platforms that provide cold storage, two-factor verification and asset insurance; 2. Apps with a simple interface and clear operation are more suitable for beginners; 3. The platform should provide learning tools such as tutorials and market analysis; 4. Pay attention to hidden costs such as transaction fees and cash withdrawal fees.

The top ten free platform recommendations for real-time data on currency circle markets are released The top ten free platform recommendations for real-time data on currency circle markets are released Apr 22, 2025 am 08:12 AM

Cryptocurrency data platforms suitable for beginners include CoinMarketCap and non-small trumpet. 1. CoinMarketCap provides global real-time price, market value, and trading volume rankings for novice and basic analysis needs. 2. The non-small quotation provides a Chinese-friendly interface, suitable for Chinese users to quickly screen low-risk potential projects.

Recommended top 10 for easy access to digital currency trading apps (latest ranking in 25) Recommended top 10 for easy access to digital currency trading apps (latest ranking in 25) Apr 22, 2025 am 07:45 AM

The core advantage of gate.io (global version) is that the interface is minimalist, supports Chinese, and the fiat currency trading process is intuitive; Binance (simplified version) has the highest global trading volume, and the simple version model only retains spot trading; OKX (Hong Kong version) has the simple version of the interface is simple, supports Cantonese/Mandarin, and has a low threshold for derivative trading; Huobi Global Station (Hong Kong version) has the core advantage of being an old exchange, launches a meta-universe trading terminal; KuCoin (Chinese Community Edition) has the core advantage of supporting 800 currencies, and the interface adopts WeChat interaction; Kraken (Hong Kong version) has the core advantage of being an old American exchange, holding a Hong Kong SVF license, and the interface is simple; HashKey Exchange (Hong Kong licensed) has the core advantage of being a well-known licensed exchange in Hong Kong, supporting France

A list of special services for major virtual currency trading platforms A list of special services for major virtual currency trading platforms Apr 22, 2025 am 08:09 AM

Institutional investors should choose compliant platforms such as Coinbase Pro and Genesis Trading, focusing on cold storage ratios and audit transparency; retail investors should choose large platforms such as Binance and Huobi, focusing on user experience and security; users in compliance-sensitive areas can conduct fiat currency trading through Circle Trade and Huobi Global, and mainland Chinese users need to go through compliant over-the-counter channels.

Can two exchanges convert coins to each other? Can two exchanges convert coins to each other? Can two exchanges convert coins to each other? Can two exchanges convert coins to each other? Apr 22, 2025 am 08:57 AM

Can. The two exchanges can transfer coins to each other as long as they support the same currency and network. The steps include: 1. Obtain the collection address, 2. Initiate a withdrawal request, 3. Wait for confirmation. Notes: 1. Select the correct transfer network, 2. Check the address carefully, 3. Understand the handling fee, 4. Pay attention to the account time, 5. Confirm that the exchange supports this currency, 6. Pay attention to the minimum withdrawal amount.

See all articles