이 기사의 내용은 Bitcoin Coinbase 지갑 라이브러리를 사용하여 PHP로 애플리케이션을 개발하는 방법에 대한 것입니다. 이는 특정 참조 가치가 있으므로 도움이 될 수 있습니다.
Coinbase Wallet API v2의 공식 클라이언트 라이브러리입니다. 우리는 Coinbase Wallet을 PHP 프로젝트에 통합할 수 있는 직관적이고 안정적인 인터페이스를 제공합니다.
중요: 이 라이브러리는 최신 API v2를 대상으로 하기 때문에 v2 권한(예: wallet:accounts:read
)이 필요합니다. 아직 v1을 사용하고 계시다면 이 라이브러리의 이전 버전을 사용하시기 바랍니다. wallet:accounts:read
)。如果你仍在使用v1,请使用此库的旧版本。
使用Composer安装库。如果你不熟悉Composer或依赖管理器,请阅读Composer文档。
"require": { "coinbase/coinbase": "~2.0" }
使用API密钥和密钥访问你自己的Coinbase帐户。
use Coinbase\Wallet\Client; use Coinbase\Wallet\Configuration; $configuration = Configuration::apiKey($apiKey, $apiSecret); $client = Client::create($configuration);
使用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();
fetch_all
매개변수를 사용하여 라이브러리가 전체 컬렉션을 로드하는 데 필요한 모든 요청을 하도록 할 수도 있습니다.
$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);
expand
매개변수 요청 API를 사용하여 초기 요청에서 확장된 리소스를 반환할 수도 있습니다.
$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";
getRawData()
메서드가 있습니다. 🎜$checkout = $client->getCheckout($checkoutId);
$orders = $client->getCheckoutOrders($checkout);
$order = $client->createNewCheckoutOrder($checkout);
$raw_body = file_get_contents('php://input'); $signature = $_SERVER['HTTP_CB_SIGNATURE']; $authenticity = $client->verifyCallback($raw_body, $signature); // boolean
phpunit
phpunit --group integration
commit=false
시 통과한 경우 이 작업만 수행하면 됩니다. 🎜rrreee🎜Sell🎜🎜Sell List🎜rrreee🎜판매 정보 가져오기🎜rrreee🎜Sell Bitcoin🎜rrreee🎜SellConfirmation🎜🎜판매 생성 시 commit=false
를 전달하면 이 작업을 수행하면 됩니다. 🎜rrreee🎜Deposits🎜🎜입금 목록🎜rrreee🎜입금 정보 확인 🎜rrreee🎜Deposits🎜rrreee🎜Submitamino🎜🎜입금 생성 시 commit=false
를 통과한 경우에만 이 작업을 수행하면 됩니다. 🎜rrreee🎜Withdraw🎜🎜출금 주문 나열🎜rrreee🎜Cancel🎜rrreee🎜Withdraw🎜rrreee🎜Submit to exit🎜🎜출금 메소드 호출 시 commit=true
를 전달한 경우 이 작업을 실행하면 됩니다. 🎜rrreee🎜결제 방법🎜🎜결제 방법 목록🎜rrreee🎜결제 방법 가져오기🎜rrreee🎜Merchant🎜🎜판매자 가져오기🎜rrreee🎜Orders🎜🎜주문 목록 보기🎜rrreee🎜주문 받기🎜rrreee🎜주문 만들기🎜rrre ee🎜주문 환불 🎜rrreee🎜 Checkout🎜🎜결제 주문 목록 표시🎜rrreee🎜결제 주문 만들기🎜rrreee🎜Checkout🎜rrreee🎜결제 주문 받기🎜rrreee🎜결제 주문 만들기🎜$order = $client->createNewCheckoutOrder($checkout);
$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
위 내용은 Bitcoin Coinbase 지갑 라이브러리를 사용하여 PHP를 사용하여 애플리케이션을 개발하는 방법(자세한 단계)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!