PHP如何使用比特币Coinbase钱包库开发应用(详细步骤)

来源:不言 发布时间:2018-10-25 15:16:24 阅读量:889

本篇文章给大家带来的内容是关于PHP如何使用比特币Coinbase钱包库开发应用(详细步骤),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

这是Coinbase Wallet API v2的官方客户端库。我们提供直观,稳定的界面,将Coinbase Wallet集成到的PHP项目中。

重要提示:由于此库是针对较新的API v2的,因此需要v2权限(即wallet:accounts:read)。如果你仍在使用v1,请使用此库的旧版本。

安装

使用Composer安装库。如果你不熟悉Composer或依赖管理器,请阅读Composer文档。

1

2

3

"require": {

    "coinbase/coinbase": "~2.0"

}

认证

API密钥

使用API密钥和密钥访问你自己的Coinbase帐户。

1

2

3

4

5

use Coinbase\Wallet\Client;

use Coinbase\Wallet\Configuration;

 

$configuration = Configuration::apiKey($apiKey, $apiSecret);

$client = Client::create($configuration);

OAuth2

使用OAuth2身份验证访问你自己以外的用户帐户。此库不处理握手过程,并假定你在初始化时具有访问token。你可以使用OAuth2客户端(例如league/oauth2-client)处理握手过程。

1

2

3

4

5

6

7

8

9

10

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令牌(在此处阅读更多内容)。如果需要,则抛出特定异常。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

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',

    ]);

}

分页

几个端点是分页的。默认情况下,库只会获取给定请求的第一页数据。你可以轻松加载不仅仅是第一页结果。

1

2

3

4

$transactions = $client->getAccountTransactions($account);

while ($transactions->hasNextPage()) {

    $client->loadNextTransactions($transactions);

}

你还可以使用fetch_all参数让库发出加载完整集合的所有必要请求。

1

2

3

4

5

use Coinbase\Wallet\Enum\Param;

 

$transactions = $client->getAccountTransactions($account, [

    Param::FETCH_ALL => true,

]);

 警告

注意警告是明智的。如果配置了一个标准PSR-3记录器,库将记录所有警告。

1

2

3

4

5

6

use Coinbase\Wallet\Client;

use Coinbase\Wallet\Configuration;

 

$configuration = Configuration::apiKey($apiKey, $apiSecret);

$configuration->setLogger($logger);

$client = Client::create($configuration);

资源引用

在某些情况下,API将返回资源引用来代替扩展的资源对象。可以通过刷新来扩展这些引用。

1

2

3

4

5

$deposit = $this->client->getAccountDeposit($account, $depositId);

$transaction = $deposit->getTransaction();

if (!$transaction->isExpanded()) {

    $this->client->refreshTransaction($transaction);

}

你还可以使用expand参数请求API在初始请求中返回扩展资源。

1

2

3

4

5

use Coinbase\Wallet\Enum\Param;

 

$deposit = $this->client->getAccountDeposit($account, $depositId, [

    Param::EXPAND = ['transaction'],

]);

创建新资源时可以使用资源引用,从而避免从API请求资源的开销。

1

2

3

4

5

6

7

8

9

10

11

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()方法,你可以使用该方法访问未映射到对象属性的任何字段。

1

$data = $deposit->getRawData();

来自最后一个HTTP响应的原始数据也可在客户端对象上使用。

1

$data = $client->decodeLastResponse();

活动记录方法

该库包括对资源对象上的活动记录方法的支持。你必须在引导应用程序时启用此功能。

1

$client->enableActiveRecord();

启用后,你可以在资源对象上调用活动记录方法。

1

2

3

4

5

use Coinbase\Wallet\Enum\Param;

 

$transactions = $account->getTransactions([

    Param::FETCH_ALL => true,

]);

用法

这并不是为了提供API的完整文档。有关更多详细信息,请参阅官方文档。

市场数据

列出支持的本地货币

1

$currencies = $client->getCurrencies();

列出汇率

1

$rates = $client->getExchangeRates();

买入价

1

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

卖出价

1

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

现货价格

1

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

当前服务器时间

1

$time = $client->getTime();

用户

获取授权信息

1

$auth = $client->getCurrentAuthorization();

查找用户信息

1

$auth = $client->getCurrentAuthorization();

获取当前用户

1

$user = $client->getCurrentUser();

更新当前用户

1

2

$user->setName('New Name');

$client->updateCurrentUser($user);

帐号

列出所有帐户

1

$accounts = $client->getAccounts();

列出帐户详细信息

1

$account = $client->getAccount($accountId);

列出主要帐户详细信息

1

$account = $client->getPrimaryAccount();

将帐户设为主要帐户

1

$client->setPrimaryAccount($account);

创建一个新的比特币账户

1

2

3

4

5

6

use Coinbase\Wallet\Resource\Account;

 

$account = new Account([

    'name' => 'New Account'

]);

$client->createAccount($account);

更新帐户

1

2

$account->setName('New Account Name');

$client->updateAccount($account):

删除帐户

1

$client->deleteAccount($account);

地址

列出帐户的接收地址

1

$addresses = $client->getAccountAddresses($account);

获取接收地址信息

1

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

列出地址的交易

1

$transactions = $client->getAddressTransactions($address);

创建一个新的接收地址

1

2

3

4

5

6

use Coinbase\Wallet\Resource\Address;

 

$address = new Address([

    'name' => 'New Address'

]);

$client->createAccountAddress($account, $address);

交易

列出交易清单

1

$transactions = $client->getAccountTransactions($account);

获取交易信息

1

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

发送资金

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

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();

}

将资金转入新帐户

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

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);

申请资金

1

2

3

4

5

6

7

8

9

10

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);

重新发送请求

1

$account->resendTransaction($transaction);

取消请求

1

$account->cancelTransaction($transaction);

完成请求

1

$account->completeTransaction($transaction);

买入

列出购买清单

1

$buys = $client->getAccountBuys($account);

获取购买信息

1

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

买入比特币

1

2

3

4

5

6

7

use Coinbase\Wallet\Resource\Buy;

 

$buy = new Buy([

    'bitcoinAmount' => 1

]);

 

$client->createAccountBuy($account, $buy);

购买确认

如果在创建购买时传递commit=false,则只需执行此操作。

1

2

3

4

use Coinbase\Wallet\Enum\Param;

 

$client->createAccountBuy($account, $buy, [Param::COMMIT => false]);

$client->commitBuy($buy);

卖出

出售清单

1

$sells = $client->getAccountSells($account);

获取销售信息

1

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

卖比特币

1

2

3

4

5

6

7

use Coinbase\Wallet\Resource\Sell;

 

$sell = new Sell([

    'bitcoinAmount' => 1

]);

 

$client->createAccountSell($account, $sell);

出售确认

如果在创建sell时传递commit=false,则只需执行此操作。

1

2

3

4

use Coinbase\Wallet\Enum\Param;

 

$client->createAccountSell($account, $sell, [Param::COMMIT => false]);

$client->commitSell($sell);

存款

列出存款清单

1

$deposits = $client->getAccountDeposits($account);

获取存款信息

1

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

存款

1

2

3

4

5

6

7

8

9

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,则只需执行此操作。

1

2

3

4

use Coinbase\Wallet\Enum\Param;

 

$client->createAccountDeposit($account, $deposit, [Param::COMMIT => false]);

$client->commitDeposit($deposit);

取款

列出提款单

1

$withdrawals = $client->getAccountWithdrawals($account);

取消

1

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

提款

1

2

3

4

5

6

7

8

9

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,则只需执行此操作。

1

2

3

4

use Coinbase\Wallet\Enum\Param;

 

$client->createAccountWithdrawal($account, $withdrawal, [Param::COMMIT => false]);

$client->commitWithdrawal($withdrawal);

支付方式

列出付款方式

1

$paymentMethods = $client->getPaymentMethods();

获取付款方式

1

$paymentMethod = $client->getPaymentMethod($paymentMethodId);

商家

获得商家

1

$merchant = $client->getMerchant($merchantId);

订单

列出订单

1

$orders = $client->getOrders();

获得订单

1

$order = $client->getOrder($orderId);

创建订单

1

2

3

4

5

6

7

8

9

use Coinbase\Wallet\Resource\Order;

use Coinbase\Wallet\Value\Money;

 

$order = new Order([

    'name' => 'Order #1234',

    'amount' => Money::btc(1)

]);

 

$client->createOrder($order);

退款订单

1

2

3

use Coinbase\Wallet\Enum\CurrencyCode;

 

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

结账

列出结帐单

1

$checkouts = $client->getCheckouts();

创建结帐单

1

2

3

4

5

6

7

8

9

10

11

12

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";

结帐

1

$checkout = $client->getCheckout($checkoutId);

获取结帐的订单

1

$orders = $client->getCheckoutOrders($checkout);

创建结帐订单

1

$order = $client->createNewCheckoutOrder($checkout);

通知webhook和验证

1

2

3

$raw_body = file_get_contents('php://input');

$signature = $_SERVER['HTTP_CB_SIGNATURE'];

$authenticity = $client->verifyCallback($raw_body, $signature); // boolean

贡献和测试

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

1

phpunit

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

1

phpunit --group integration


标签: PHP
分享:
评论:
你还没有登录,请先