当前位置: 首页 > 后端技术 > PHP

PHP如何使用比特币Coinbase钱包库

时间:2023-03-30 00:44:02 PHP

这是Coinbase钱包APIv2的官方客户端库。我们提供了一个直观且稳定的界面来将Coinbase钱包集成到您的PHP项目中。重要说明:由于此库针对较新的APIv2,因此需要v2权限(即wallet:accounts:read)。如果您仍在使用v1,请使用该库的旧版本。使用Composer安装库。如果您不熟悉Composer或依赖管理器,请阅读Composer文档。"require":{"coinbase/coinbase":"~2.0"}验证API密钥使用API密钥和秘密访问您自己的Coinbase帐户。useCoinbase\Wallet\Client;useCoinbase\Wallet\Configuration;$configuration=Configuration::apiKey($apiKey,$apiSecret);$client=Client::create($configuration);OAuth2使用OAuth2认证访问非本人用户帐号。这个库不处理握手过程,并假设你在初始化时有一个访问令牌。您可以使用OAuth2客户端,例如league/oauth2-client来处理握手过程。useCoinbase\Wallet\Client;useCoinbase\Wallet\Configuration;//有刷新令牌$configuration=Configuration::oauth($accessToken,$refreshToken);//没有刷新令牌$configuration=Configuration::oauth($访问令牌);$client=Client::create($configuration);在某些情况下,双因素身份验证发送资金端点需要2FA令牌(在此处阅读更多信息)。如有必要,将抛出特定的异常。使用Coinbase\Wallet\Enum\Param;使用Coinbase\Wallet\Exception\TwoFactorRequiredException;使用Coinbase\Wallet\Resource\Transaction;$transaction=Transaction::send(['toEmail'=>'test@test.com','比特币金额'=>1]);$account=$client->getPrimaryAccount();try{$client->createAccountTransaction($account,$transaction);}catch(TwoFactorRequiredException$e){//向用户显示2FA对话框并收集2FA令牌//使用令牌重试调用$client->createAccountTransaction($account,$transaction,[Param::TWO_FACTOR_TOKEN=>'123456',]);}Paging几个端点正在分页。默认情况下,库只会获取给定请求的第一页数据。您不仅可以轻松加载结果的第一页,还可以轻松加载更多内容。$transactions=$client->getAccountTransactions($account);while($transactions->hasNextPage()){$client->loadNextTransactions($transactions);}您还可以使用fetch_all参数让库发出所有必要的请求。使用Coinbase\Wallet\Enum\Param;$transactions=$client->getAccountTransactions($account,[Param::FETCH_ALL=>true,]); 警告注意警告是明智的。如果配置了标准PSR-3记录器,库将记录所有警告。使用Coinbase\Wallet\Client;使用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返回扩展后的资源。使用Coinbase\Wallet\Enum\Param;$deposit=$this->client->getAccountDeposit($account,$depositId,[Param::EXPAND=['transaction'],]);在创建新资源时可以使用资源引用,从而避免从API请求资源的开销。使用Coinbase\Wallet\Resource\Deposit;使用Coinbase\Wallet\Resource\PaymentMethod;$deposit=newDeposit(['paymentMethod'=>PaymentMethod::reference($paymentMethodId)]);//或者使用便捷方法$deposit=newDeposit(['paymentMethodId'=>$paymentMethodId]);响应有多种方法可以访问原始响应数据。首先,每个资源对象都有一个getRawData()方法,您可以使用该方法访问任何未映射到对象属性的字段。$data=$deposit->getRawData();来自最后一个HTTP响应的原始数据在客户端对象上也可用。$data=$client->decodeLastResponse();ActiveRecord方法该库包括对资源对象上的ActiveRecord方法的支持。引导应用程序时必须启用此功能。$client->enableActiveRecord();启用后,您可以在资源对象上调用活动记录方法。使用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('NewName');$client->updateCurrentUser($user);account列出所有账户$accounts=$client->getAccounts();列出帐户详细信息$account=$client->getAccount($accountId);列出主帐户详细信息$account=$client->getPrimaryAccount();将帐户设置为主$client->setPrimaryAccount($account);创建一个新的比特币账户使用Coinbase\Wallet\Resource\Account;$account=newAccount(['name'=>'NewAccount']);$client->createAccount($account);updateaccount$account->setName('新账户名');$client->updateAccount($account):删除账户$client->deleteA帐户($帐户);address列出账户的接收地址$addresses=$client->getAccountAddresses($account);获取接收地址信息$address=$client->getAccountAddress($account,$addressId);列出交易的地址$transactions=$client->getAddressTransactions($address);使用Coinbase\Wallet\Resource\Address创建一个新的接收地址;$address=newAddress(['name'=>'NewAddress']);$client->createAccountAddress($account,$address);交易列表交易$transactions=$client->getAccountTransactions($account);获取交易信息$transaction=$client->getAccountTransaction($account,$transactionId);发送资金使用Coinbase\Wallet\Enum\CurrencyCode;使用Coinbase\Wallet\Resource\Transaction;使用Coinbase\Wallet\Value\Money;$transaction=Transaction::send(['toBitcoinAddress'=>'ADDRESS','amount'=>newMoney(5,CurrencyCode::USD),'description'=>'你的第一个比特币!','fee'=>'0.0001'//只有在BTC0.0001下的交易才需要]);尝试{$client->createAccountTransaction($账户,$交易);}catch(Exception$e){echo$e->getMessage();}将资金转入新账户useCoinbase\Wallet\Resource\Transaction;useCoinbase\Wallet\Resource\Account;$fromAccount=Account::reference($accountId);$toAccount=newAccount(['name'=>'新账户']);$client->createAccount($toAccount);$transaction=Transaction::transfer(['to'=>$toAccount,'bitcoinAmount'=>1,'description'=>'你的第一个比特币!']);$client->createAccountTransaction($fromAccount,$transaction);申请资金useCoinbase\Wallet\Enum\CurrencyCode;useCoinbase\Wallet\Resource\Transaction;useCoinbase\Wallet\Value\Money;$transaction=Transaction::request(['amount'=>newMoney(8,CurrencyCode::USD),'description'=>'Burrito']);$client->createAccountTransaction($transaction);重新发送请求$account->resendTransaction($transaction);取消请求$account->cancelTransaction($transaction);完成请求$account->completeTransaction($交易);buy列出购买清单$buys=$client->getAccountBuys($account);获取购买信息$buy=$client->getAccountBuy($account,$buyId);购买比特币使用Coinbase\Wallet\Resource\Buy;$buy=newBuy(['bitcoinAmount'=>1]);$client->createAccountBuy($account,$buy);购买确认如果你在创建购买时传递commit=false就执行此操作使用Coinbase\Wallet\Enum\Param;$client->createAccountBuy($account,$buy,[Param::COMMIT=>false]);$client->commitBuy($buy);销售清单$sells=$client->getAccountSells($account);获取销售信息$sell=$client->getAccountSell($account,$sellId);使用Coinbase\Wallet\Resource\Sell出售比特币;$sell=newSell(['bitcoinAmount'=>1]);$client->createAccountSell($account,$sell);销售确认只有在创建销售时通过commit=false时才执行此操作。使用Coinbase\Wallet\Enum\Param;$client->createAccountSell($account,$sell,[Param::COMMIT=>false]);$client->commitSell($sell);Deposits列表存款$deposits=$client->getAccountDeposits($account);获取存款信息$deposit=$client->getAccountDeposit($account,$depositId);存款使用Coinbase\Wallet\Enum\CurrencyCode;使用Coinbase\Wallet\Resource\Deposit;使用Coinbase\Wallet\Value\Money;$deposit=newDeposit(['amount'=>newMoney(10,CurrencyCode::USD)]);$client->createAccountDeposit($帐户,$存款);如果创建存款你只需要在存款时通过commit=false的情况下执行此操作。使用Coinbase\Wallet\Enum\Param;$client->createAccountDeposit($account,$deposit,[Param::COMMIT=>false]);$client->commitDeposit($deposit);取款列表取款备注$withdrawals=$client->getAccountWithdrawals($account);取消$withdrawal=$client->getAccountWithdrawal($account,$withdrawalId);取款使用Coinbase\Wallet\Enum\CurrencyCode;使用Coinbase\Wallet\Resource\Withdrawal;使用Coinbase\Wallet\Value\Money;$withdrawal=newWithdrawal(['amount'=>newMoney(10,CurrencyCode::USD)]);$client->createAccountWithdrawal($account,$withdrawal);如果调用提交并退出你只需要在退出方法中传递commit=true时执行此操作。使用Coinbase\Wallet\Enum\Param;$client->createAccountWithdrawal($account,$withdrawal,[Param::COMMIT=>false]);$client->commitWithdrawal($withdrawal);paymentmethods列出支付方式$paymentMethods=$client->getPaymentMethods();获取支付方式$paymentMethod=$client->getPaymentMethod($paymentMethodId);商家获取商家$merchant=$client->getMerchant($merchantId);订单列表订单$orders=$client->getOrders();获取订单$order=$client->getOrder($orderId);创建订单使用Coinbase\Wallet\Resource\Order;使用Coinbase\Wallet\Value\Money;$order=newOrder(['name'=>'Order#1234','amount'=>Money::btc(1)]);$client->createOrder($order);退款订单使用Coinbase\Wallet\Enum\CurrencyCode;$client->refundOrder($order,CurrencyCode::BTC);结帐列表结帐$checkouts=$client->getCheckouts();使用Coinbase\Wallet\Resource\Checkout创建结帐;$params=array('name'=>'MyOrder','amount'=>newMoney(100,'USD'),'metadata'=>array('order_id'=>$custom_order_id));$checkout=newCheckout($params);$client->createCheckout($checkout);$code=$checkout->getEmbedCode();$redirect_url="https://www.coinbase.com/checkouts/$代码”;结帐$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变量提供值,并在运行测试套件时指定集成组。phpunit--groupintegration建议您浏览我的各种编程语言的区块链教程和区块链技术博客,以深入了解区块链、比特币、加密货币、以太坊和智能合约。Php比特币开发教程,本课程面向初学者,内容涵盖了比特币的核心概念,如区块链存储、去中心化共识机制、密钥和脚本、交易和UTXO等,同时还详细讲解了如何使用PhpIntegrating比特币在代码中的支持功能,如创建地址、管理钱包、构造裸交易等,是Php工程师不可多得的比特币开发学习教程。PHPEthereum主要介绍使用PHP进行智能合约开发交互、账户创建、交易、转账、代币开发、过滤器和交易等,这里是原文