PHP如何使用比特币Coinbase钱包库开发应用(详细步骤)
这是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 Coinbase\Wallet\Client; use Coinbase\Wallet\Configuration; $configuration = Configuration::apiKey($apiKey, $apiSecret); $client = Client::create($configuration);
OAuth2
使用OAuth2身份验证访问你自己以外的用户帐户。此库不处理握手过程,并假定你在初始化时具有访问token。你可以使用OAuth2客户端(例如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);
双因素身份验证
发送资金端点在某些情况下需要2FA令牌(在此处阅读更多内容)。如果需要,则抛出特定异常。
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', ]); }
分页
几个端点是分页的。默认情况下,库只会获取给定请求的第一页数据。你可以轻松加载不仅仅是第一页结果。
$transactions = $client->getAccountTransactions($account); while ($transactions->hasNextPage()) { $client->loadNextTransactions($transactions); }
你还可以使用fetch_all
参数让库发出加载完整集合的所有必要请求。
use Coinbase\Wallet\Enum\Param; $transactions = $client->getAccountTransactions($account, [ Param::FETCH_ALL => true, ]);
警告
注意警告是明智的。如果配置了一个标准PSR-3记录器,库将记录所有警告。
use Coinbase\Wallet\Client; use Coinbase\Wallet\Configuration; $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 Coinbase\Wallet\Enum\Param; $deposit = $this->client->getAccountDeposit($account, $depositId, [ Param::EXPAND = ['transaction'], ]);
创建新资源时可以使用资源引用,从而避免从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 ]);
响应
有多种方法可以访问原始响应数据。首先,每个资源对象都有一个getRawData()
方法,你可以使用该方法访问未映射到对象属性的任何字段。
$data = $deposit->getRawData();
来自最后一个HTTP响应的原始数据也可在客户端对象上使用。
$data = $client->decodeLastResponse();
活动记录方法
该库包括对资源对象上的活动记录方法的支持。你必须在引导应用程序时启用此功能。
$client->enableActiveRecord();
启用后,你可以在资源对象上调用活动记录方法。
use Coinbase\Wallet\Enum\Param; $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 Coinbase\Wallet\Resource\Account; $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 Coinbase\Wallet\Resource\Address; $address = new Address([ 'name' => 'New Address' ]); $client->createAccountAddress($account, $address);
交易
列出交易清单
$transactions = $client->getAccountTransactions($account);
获取交易信息
$transaction = $client->getAccountTransaction($account, $transactionId);
发送资金
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(); }
将资金转入新帐户
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);
申请资金
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);
重新发送请求
$account->resendTransaction($transaction);
取消请求
$account->cancelTransaction($transaction);
完成请求
$account->completeTransaction($transaction);
买入
列出购买清单
$buys = $client->getAccountBuys($account);
获取购买信息
$buy = $client->getAccountBuy($account, $buyId);
买入比特币
use Coinbase\Wallet\Resource\Buy; $buy = new Buy([ 'bitcoinAmount' => 1 ]); $client->createAccountBuy($account, $buy);
购买确认
如果在创建购买时传递commit=false
,则只需执行此操作。
use Coinbase\Wallet\Enum\Param; $client->createAccountBuy($account, $buy, [Param::COMMIT => false]); $client->commitBuy($buy);
卖出
出售清单
$sells = $client->getAccountSells($account);
获取销售信息
$sell = $client->getAccountSell($account, $sellId);
卖比特币
use Coinbase\Wallet\Resource\Sell; $sell = new Sell([ 'bitcoinAmount' => 1 ]); $client->createAccountSell($account, $sell);
出售确认
如果在创建sell时传递commit=false
,则只需执行此操作。
use Coinbase\Wallet\Enum\Param; $client->createAccountSell($account, $sell, [Param::COMMIT => false]); $client->commitSell($sell);
存款
列出存款清单
$deposits = $client->getAccountDeposits($account);
获取存款信息
$deposit = $client->getAccountDeposit($account, $depositId);
存款
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=false
,则只需执行此操作。
use Coinbase\Wallet\Enum\Param; $client->createAccountDeposit($account, $deposit, [Param::COMMIT => false]); $client->commitDeposit($deposit);
取款
列出提款单
$withdrawals = $client->getAccountWithdrawals($account);
取消
$withdrawal = $client->getAccountWithdrawal($account, $withdrawalId);
提款
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=true
,则只需执行此操作。
use Coinbase\Wallet\Enum\Param; $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 Coinbase\Wallet\Resource\Order; use Coinbase\Wallet\Value\Money; $order = new Order([ 'name' => 'Order #1234', 'amount' => Money::btc(1) ]); $client->createOrder($order);
退款订单
use Coinbase\Wallet\Enum\CurrencyCode; $client->refundOrder($order, CurrencyCode::BTC);
结账
列出结帐单
$checkouts = $client->getCheckouts();
创建结帐单
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 = $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如何使用比特币Coinbase钱包库开发应用(详细步骤)的详细内容,更多请关注其它相关文章!
下一篇: 详解Json如何转化为Java对象的示例