這是Coinbase Wallet API v2的官方客戶端庫。我們提供直觀,穩定的介面,將Coinbase Wallet整合到的PHP專案中。
重要提示:由於此庫是針對較新的API v2的,因此需要v2許可權(即wallet:accounts:read
)。如果你仍在使用v1,請使用此庫的舊版本。
安裝
使用Composer安裝庫。如果你不熟悉Composer或依賴管理器,請閱讀Composer文件。
"require": {
"coinbase/coinbase": "~2.0"
}
認證
API金鑰
使用API金鑰和金鑰訪問你自己的Coinbase帳戶。
use CoinbaseWalletClient;
use CoinbaseWalletConfiguration;
$configuration = Configuration::apiKey($apiKey, $apiSecret);
$client = Client::create($configuration);
OAuth2
使用OAuth2身份驗證訪問你自己以外的使用者帳戶。此庫不處理握手過程,並假定你在初始化時具有訪問token。你可以使用OAuth2客戶端(例如league/oauth2-client)處理握手過程。
use CoinbaseWalletClient;
use CoinbaseWalletConfiguration;
// with a refresh token
$configuration = Configuration::oauth($accessToken, $refreshToken);
// without a refresh token
$configuration = Configuration::oauth($accessToken);
$client = Client::create($configuration);
雙因素身份驗證
傳送資金端點在某些情況下需要2FA令牌(在此處閱讀更多內容)。如果需要,則丟擲特定異常。
use CoinbaseWalletEnumParam;
use CoinbaseWalletExceptionTwoFactorRequiredException;
use CoinbaseWalletResourceTransaction;
$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`,
]);
}
分頁
幾個端點是分頁的。預設情況下,庫只會獲取給定請求的第一頁資料。你可以輕鬆載入不僅僅是第一頁結果。
$transactions = $client->getAccountTransactions($account);
while ($transactions->hasNextPage()) {
$client->loadNextTransactions($transactions);
}
你還可以使用fetch_all
引數讓庫發出載入完整集合的所有必要請求。
use CoinbaseWalletEnumParam;
$transactions = $client->getAccountTransactions($account, [
Param::FETCH_ALL => true,
]);
警告
注意警告是明智的。如果配置了一個標準PSR-3記錄器,庫將記錄所有警告。
use CoinbaseWalletClient;
use CoinbaseWalletConfiguration;
$configuration = Configuration::apiKey($apiKey, $apiSecret);
$configuration->setLogger($logger);
$client = Client::create($configuration);
資源引用
在某些情況下,API將返回資源引用來代替擴充套件的資源物件。可以通過重新整理來擴充套件這些引用。
$deposit = $this->client->getAccountDeposit($account, $depositId);
$transaction = $deposit->getTransaction();
if (!$transaction->isExpanded()) {
$this->client->refreshTransaction($transaction);
}
你還可以使用expand
引數請求API在初始請求中返回擴充套件資源。
use CoinbaseWalletEnumParam;
$deposit = $this->client->getAccountDeposit($account, $depositId, [
Param::EXPAND = [`transaction`],
]);
建立新資源時可以使用資源引用,從而避免從API請求資源的開銷。
use CoinbaseWalletResourceDeposit;
use CoinbaseWalletResourcePaymentMethod;
$deposit = new Deposit([
`paymentMethod` => PaymentMethod::reference($paymentMethodId)
]);
// or use the convenience method
$deposit = new Deposit([
`paymentMethodId` => $paymentMethodId
]);
響應
有多種方法可以訪問原始響應資料。首先,每個資源物件都有一個getRawData()
方法,你可以使用該方法訪問未對映到物件屬性的任何欄位。
$data = $deposit->getRawData();
來自最後一個HTTP響應的原始資料也可在客戶端物件上使用。
$data = $client->decodeLastResponse();
活動記錄方法
該庫包括對資源物件上的活動記錄方法的支援。你必須在引導應用程式時啟用此功能。
$client->enableActiveRecord();
啟用後,你可以在資源物件上呼叫活動記錄方法。
use CoinbaseWalletEnumParam;
$transactions = $account->getTransactions([
Param::FETCH_ALL => true,
]);
用法
這並不是為了提供API的完整文件。有關更多詳細資訊,請參閱官方文件。
市場資料
列出支援的本地貨幣
$currencies = $client->getCurrencies();
列出匯率
$rates = $client->getExchangeRates();
買入價
$buyPrice = $client->getBuyPrice(`BTC-USD`);
賣出價
$sellPrice = $client->getSellPrice(`BTC-USD`);
現貨價格
$spotPrice = $client->getSpotPrice(`BTC-USD`);
當前伺服器時間
$time = $client->getTime();
使用者
獲取授權資訊
$auth = $client->getCurrentAuthorization();
查詢使用者資訊
$auth = $client->getCurrentAuthorization();
獲取當前使用者
$user = $client->getCurrentUser();
更新當前使用者
$user->setName(`New Name`);
$client->updateCurrentUser($user);
帳號
列出所有帳戶
$accounts = $client->getAccounts();
列出帳戶詳細資訊
$account = $client->getAccount($accountId);
列出主要帳戶詳細資訊
$account = $client->getPrimaryAccount();
將帳戶設為主要帳戶
$client->setPrimaryAccount($account);
建立一個新的比特幣賬戶
use CoinbaseWalletResourceAccount;
$account = new Account([
`name` => `New Account`
]);
$client->createAccount($account);
更新帳戶
$account->setName(`New Account Name`);
$client->updateAccount($account):
刪除帳戶
$client->deleteAccount($account);
地址
列出帳戶的接收地址
$addresses = $client->getAccountAddresses($account);
獲取接收地址資訊
$address = $client->getAccountAddress($account, $addressId);
列出地址的交易
$transactions = $client->getAddressTransactions($address);
建立一個新的接收地址
use CoinbaseWalletResourceAddress;
$address = new Address([
`name` => `New Address`
]);
$client->createAccountAddress($account, $address);
交易
列出交易清單
$transactions = $client->getAccountTransactions($account);
獲取交易資訊
$transaction = $client->getAccountTransaction($account, $transactionId);
傳送資金
use CoinbaseWalletEnumCurrencyCode;
use CoinbaseWalletResourceTransaction;
use CoinbaseWalletValueMoney;
$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();
}
將資金轉入新帳戶
use CoinbaseWalletResourceTransaction;
use CoinbaseWalletResourceAccount;
$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);
申請資金
use CoinbaseWalletEnumCurrencyCode;
use CoinbaseWalletResourceTransaction;
use CoinbaseWalletValueMoney;
$transaction = Transaction::request([
`amount` => new Money(8, CurrencyCode::USD),
`description` => `Burrito`
]);
$client->createAccountTransaction($transaction);
重新傳送請求
$account->resendTransaction($transaction);
取消請求
$account->cancelTransaction($transaction);
完成請求
$account->completeTransaction($transaction);
買入
列出購買清單
$buys = $client->getAccountBuys($account);
獲取購買資訊
$buy = $client->getAccountBuy($account, $buyId);
買入比特幣
use CoinbaseWalletResourceBuy;
$buy = new Buy([
`bitcoinAmount` => 1
]);
$client->createAccountBuy($account, $buy);
購買確認
如果在建立購買時傳遞commit=false
,則只需執行此操作。
use CoinbaseWalletEnumParam;
$client->createAccountBuy($account, $buy, [Param::COMMIT => false]);
$client->commitBuy($buy);
賣出
出售清單
$sells = $client->getAccountSells($account);
獲取銷售資訊
$sell = $client->getAccountSell($account, $sellId);
賣比特幣
use CoinbaseWalletResourceSell;
$sell = new Sell([
`bitcoinAmount` => 1
]);
$client->createAccountSell($account, $sell);
出售確認
如果在建立sell時傳遞commit=false
,則只需執行此操作。
use CoinbaseWalletEnumParam;
$client->createAccountSell($account, $sell, [Param::COMMIT => false]);
$client->commitSell($sell);
存款
列出存款清單
$deposits = $client->getAccountDeposits($account);
獲取存款資訊
$deposit = $client->getAccountDeposit($account, $depositId);
存款
use CoinbaseWalletEnumCurrencyCode;
use CoinbaseWalletResourceDeposit;
use CoinbaseWalletValueMoney;
$deposit = new Deposit([
`amount` => new Money(10, CurrencyCode::USD)
]);
$client->createAccountDeposit($account, $deposit);
提交押金
如果在建立存款時傳遞commit=false
,則只需執行此操作。
use CoinbaseWalletEnumParam;
$client->createAccountDeposit($account, $deposit, [Param::COMMIT => false]);
$client->commitDeposit($deposit);
取款
列出提款單
$withdrawals = $client->getAccountWithdrawals($account);
取消
$withdrawal = $client->getAccountWithdrawal($account, $withdrawalId);
提款
use CoinbaseWalletEnumCurrencyCode;
use CoinbaseWalletResourceWithdrawal;
use CoinbaseWalletValueMoney;
$withdrawal = new Withdrawal([
`amount` => new Money(10, CurrencyCode::USD)
]);
$client->createAccountWithdrawal($account, $withdrawal);
提交退出
如果在呼叫提款方法時傳遞commit=true
,則只需執行此操作。
use CoinbaseWalletEnumParam;
$client->createAccountWithdrawal($account, $withdrawal, [Param::COMMIT => false]);
$client->commitWithdrawal($withdrawal);
支付方式
列出付款方式
$paymentMethods = $client->getPaymentMethods();
獲取付款方式
$paymentMethod = $client->getPaymentMethod($paymentMethodId);
商家
獲得商家
$merchant = $client->getMerchant($merchantId);
訂單
列出訂單
$orders = $client->getOrders();
獲得訂單
$order = $client->getOrder($orderId);
建立訂單
use CoinbaseWalletResourceOrder;
use CoinbaseWalletValueMoney;
$order = new Order([
`name` => `Order #1234`,
`amount` => Money::btc(1)
]);
$client->createOrder($order);
退款訂單
use CoinbaseWalletEnumCurrencyCode;
$client->refundOrder($order, CurrencyCode::BTC);
結賬
列出結帳單
$checkouts = $client->getCheckouts();
建立結帳單
use CoinbaseWalletResourceCheckout;
$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 = $client->getCheckout($checkoutId);
獲取結帳的訂單
$orders = $client->getCheckoutOrders($checkout);
建立結帳訂單
$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_KEY
和CB_API_SECRET
變數提供值,並在執行測試套件時指定integration
組。
phpunit --group integration
建議你瀏覽我的各種程式語言的區塊鏈教程和區塊鏈技術部落格,深入瞭解區塊鏈,比特幣,加密貨幣,以太坊,和智慧合約。
- php比特幣開發教程,本課程面向初學者,內容即涵蓋比特幣的核心概念,例如區塊鏈儲存、去中心化共識機制、金鑰與指令碼、交易與UTXO等,同時也詳細講解如何在Php程式碼中整合比特幣支援功能,例如建立地址、管理錢包、構造裸交易等,是Php工程師不可多得的比特幣開發學習課程。
- php以太坊,主要是介紹使用php進行智慧合約開發互動,進行賬號建立、交易、轉賬、代幣開發以及過濾器和交易等內容。
這裡是原文