带有Coinbase API的比特币和PHP-演示应用

tech2022-09-22  65

In part 1, we covered basic installation and usage of Coinbase’s Bitcoin PHP API and the accompanying SDK. In this second and final part, we’ll be building our sample application.

在第1部分中 ,我们介绍了Coinbase的Bitcoin PHP API和随附的SDK的基本安装和使用。 在第二部分(也是最后一部分)中,我们将构建示例应用程序。

发送和接收比特币 (Send and Receive Bitcoins)

Sending or receiving BTC with the Coinbase API is really simple. There are a couple of intuitive methods you can easily guess: sendMoney() and requestMoney().

使用Coinbase API发送或接收BTC非常简单。 您可以轻松猜出几种直观的方法: sendMoney()和requestMoney() 。

Here’s the first one:

这是第一个:

public function sendMoney($to, $amount, $notes=null, $userFee=null, $amountCurrency=null)

The first parameter is “who” will receive the money. The second one is the amount that you want to send. Transaction notes will be available only to recipients that also have a Coinbase account. Otherwise, the BTC network doesn’t support it.

第一个参数是“谁”将收到钱。 第二个是您要发送的金额。 交易记录仅适用于也拥有Coinbase帐户的收件人。 否则,BTC网络将不支持它。

Let’s take a look at an example:

让我们看一个例子:

$response = $coinbase->sendMoney($receiverAddress, "2");

If you want to verify your transaction status, use the $response->transaction->status property.

如果要验证交易状态,请使用$response->transaction->status属性。

echo $response->transaction->status;

You can also verify the result:

您还可以验证结果:

if($response->success) { echo 'Done.'; }

If you want to get the transaction id, just use $response->transaction->id.

如果要获取交易ID,只需使用$response->transaction->id 。

Now let’s take a look at how you can request BTC. The method you will have to use is requestMoney() and this is its syntax.

现在让我们看一下如何请求BTC。 您将必须使用的方法是requestMoney() ,这是其语法。

$response = $coinbase->requestMoney($emailAddress, 10, "Maintenance Operation (10 BTC)");

The mechanism, this time, is a little bit different. Coinbase will use the specified mail address as a first parameter to send a message in which Coinbase itself will explain to our BTC sender what to do and how to do it.

这次的机制有所不同。 Coinbase将使用指定的邮件地址作为第一个参数来发送消息,其中Coinbase本身将向我们的BTC发送者说明如何做和如何做。

Here’s how to check the transaction status:

检查交易状态的方法如下:

echo $response->transaction->request ? 'true' : 'false'; // 'true' echo $response->transaction->id; // 'request_transaction_id'

You can also use some methods to cancel or resend the same request, if you have some issues. As a key, you will have to use the previously obtained transaction key.

如果遇到问题,您还可以使用某些方法来取消或重新发送相同的请求。 作为密钥,您将必须使用先前获得的交易密钥。

$response = $coinbase->resendRequest('request_transaction_id'); echo $response->success ? 'true' : 'false'; // 'true' $response = $coinbase->cancelRequest('request_transaction_id'); echo $response->success ? 'true' : 'false'; // 'true'

After you’ve made sure the procedure is completed, you will have to call the completeRequest() method.

确保该过程完成后,您将必须调用completeRequest()方法。

Like this:

像这样:

$response = $coinbase->completeRequest('501a3554f8182b2754000003'); echo $response->success ? 'true' : 'false';

And that’s all!

就这样!

其他方法 (Other Methods)

The API system is frequently updated, but the PHP package could be not updated with all the wrapper methods around the API. If you need something “special” you can use the get, post, put and delete methods to deal with the API directly.

API系统会经常更新,但是可能无法使用API​​周围的所有包装器方法来更新PHP软件包。 如果需要“特殊”功能,可以使用get , post , put和delete方法直接处理API。

var_dump($coinbase->get('/account/balance')); // object(stdClass)#4 (2) { // ["amount"]=> // string(10) "0.56902981" // ["currency"]=> // string(3) "BTC" // }

In this specific example we used /account/balance, but the same principle is applied to every other API method. After the first parameter, the metod name, you can specify an array of options, if you need any.

在此特定示例中,我们使用了/account/balance ,但相同的原理也应用于其他所有API方法。 在第一个参数(方法名称)之后,可以根据需要指定选项数组。

We are done with the basics. Now that we know the tools of the trade, what about trying to make a really simple application to deal with a payment?

我们已经完成了基础知识。 现在我们知道了交易的工具,那么如何尝试创建一个非常简单的应用程序来处理付款呢?

使用Coinbase API的第一个应用程序 (First Application with the Coinbase API)

It’s time to create a simple first real application, emulating a real world situation. Let’s assume we have a friend who owns a small non-profit organization. A really important cause: he decided to dedicate his life to defending the rights of sentient robots.

是时候创建一个简单的第一个真实应用程序,模拟真实世界的情况了。 假设我们有一个拥有小型非营利组织的朋友。 一个非常重要的原因:他决定奉献自己的生命来捍卫有意识的机器人的权利。

Ok, they don’t exist yet, but the sooner you start, the sooner you finish!

好的,它们还不存在,但是越早开始,越早完成!

He stumbled across this BTC thing and he wants to enable donations with this new cryptocurrency.

他偶然发现了这个BTC东西,他想用这种新的加密货币启用捐款。

No problem!

没问题!

All we have to do is to create four simple pages:

我们要做的就是创建四个简单的页面:

Welcome Page: where the user will insert the amount of the donation in BTC;

欢迎页面:用户将在其中插入捐款金额的比特币;

Payment Page: where we will create a button using the PHP SDK;

付款页面:我们将在其中使用PHP SDK创建一个按钮;

Thanks Page: a confirmation page to show when the donation is completed;

感谢页面:确认页面,显示捐赠完成的时间;

Cancel Page: an error page to show in case of errors during the process;

取消页面:在过程中出现错误时显示的错误页面;

Install the SDK as demonstrated in Part 1. After composer update you will be ready to go.

按照第1部分中的说明安装SDK。在composer update您就可以开始使用。

Now, let’s start with the Welcome Page. Create an index.php file that will contain the following code.

现在,让我们从欢迎页面开始。 创建一个index.php文件,其中将包含以下代码。

<!DOCTYPE html> <html> <head> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> <title>Welcome! - The Sentient Robots Rights Organization</title> </head> <body> <div class="container"> <div class="starter-template" style="text-align:center; padding-top:50px;"> <h1>S.R.R.O.</h1> <h3>Sentient Robots Rights Organization</h3> <p><img src="logo.png" /></p> <p>Welcome, human! If you want to donate for our organization using bitcoin, enter your donation amount here.</p> <br/> <form action="payment.php" method="post"> <p><input type="text" class="form-control input-lg" placeholder="Enter BTC amount..." style="text-align:center;" name="amount" autofocus /></p> <p><button class="form-control btn-success">Donate Now! *</button></p> </form> <p>&nbsp;</p> <p><i>* by donating we are absolutely not responsible for what we do with your money... uhmm... maybe a yacht...</i></p> </div> </div><!-- /.container --> </body> </html>

Note: as you can easily imagine, I used Bootstrap via CDN to setup a structure and some style quickly for our pages. Don’t mind the lack of a framework or the mixing of views with logic, this is just a demo.

注意:您可以轻松想象,我通过CDN使用Bootstrap为我们的页面快速设置结构和某种样式。 不要介意缺少框架或将视图与逻辑混合在一起,这只是一个演示。

Nothing special: we just created a form with an input field and a button to send that form data. On submit, data will be sent to the payment.php page. Here we go to the next step: payment.php.

没什么特别的:我们刚刚创建了一个带有输入字段和按钮的表单,用于发送该表单数据。 提交后,数据将发送到payment.php页面。 在这里,我们进入下一步: payment.php 。

<?php require('includes/coinbase.inc.php'); ?> <!DOCTYPE html> <html> <head> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> <title>Payment - The Sentient Robots Rights Organization</title> </head> <body> <div class="container"> <div class="starter-template" style="text-align:center; padding-top:50px;"> <h1>S.R.R.O.</h1> <h3>Sentient Robots Rights Organization</h3> <p><img src="logo.png" /></p> <p>It's time to pay. You decided to donate...</p> <p style="font-size:32px;"><b><?php echo $_POST['amount']; ?> BTC</b></p> <hr/> <?php echo $button->embedHtml; ?> <p>&nbsp;</p> </div> </div><!-- /.container --> </body> </html>

What we have here? $_POST['amount'] is the donation amount that we have chosen in the previous screen. Then we also have $button->embedHTML.

我们这里有什么? $_POST['amount']是我们在上一个屏幕中选择的捐赠金额。 然后我们还有$button->embedHTML 。

Wait, wait. Where is this button located?

等等。 该按钮在哪里?

You got it: in the other file that is included here, includes/coinbase.php. Let’s create the folder and the file. This is what are we going to put in it.

您明白了:在此处includes/coinbase.php的另一个文件中, includes/coinbase.php 。 让我们创建文件夹和文件。 这就是我们要放入的内容。

<?php require('vendor/autoload.php'); $coinbaseAPIKey = 'MY_COINBASE_API_KEY'; $coinbaseAPISecret = 'MY_COINBASE_API_SECRET'; $coinbase = Coinbase::withApiKey($coinbaseAPIKey, $coinbaseAPISecret); if(!isset($_POST['amount'])) header('Location: index.php'); if (!preg_match('/^[0-9]+(?:\.[0-9]+)?$/', $_POST['amount'])) header('Location: index.php'); $button = $coinbase->createButton( "Your Donation to S.R.R.O.", $_POST['amount'], "BTC", "", array( "description" => "My " . $_POST['amount'] . " BTC donation to S.S.R.O.", "cancel_url" => "http://localhost/coinbase/cancel.php", "success_url" => "http://localhost/coinbase/thanks.php" ) );

The first required is used to load the SDK. Further instructions are used to, respectively:

第一个required用于加载SDK。 进一步的说明分别用于:

declare the $coinbaseAPIKey variable;

声明$coinbaseAPIKey变量;

declare the $coinbaseAPISecret variable;

声明$coinbaseAPISecret变量;

create the $coinbase object that we are going to use to generate our payment button;

创建将用于生成付款按钮的$coinbase对象;

After that, a little bit of validation. Just to stay on the safe side.

之后,进行一点验证。 只是为了安全起见。

Note: this is an article about Coinbase API, so we will not go deeper into validation. In a real world situation things would be different and we can use many tools and techniques to create better (and safer) code.

注意:这是一篇有关Coinbase API的文章,因此我们将不进一步进行验证。 在现实世界中,情况会有所不同,我们可以使用许多工具和技术来创建更好(和更安全)的代码。

The final step is the button creation, using the createButton method. I left the fourth parameter blank because, in this specific case, I didn’t need a tracking code for my order. However, rembember that this is the parameter you have to use if you need it.

最后一步是使用createButton方法创建按钮。 我将第四个参数留空,因为在这种特定情况下,我的订单不需要跟踪代码。 但是,请记住,这是您在需要时必须使用的参数。

Now that we have the button we can echo its code in the payment.php page.

现在有了按钮,我们可以在payment.php页面中回显其代码。

Note: before you create buttons, fill your merchant profile on the Coinbase website. It is a necessary step. If you don’t do it, you will be blocked with a fatal error.

注意:创建按钮之前,请在Coinbase网站上填写商家资料。 这是必要的步骤。 如果不这样做,将会因致命错误而被阻止。

Now that we have everything, we just have to set up our thanks.php and cancel.php pages. Here they are.

现在,我们所拥有的一切,我们只需要设置我们的thanks.php和cancel.php页面。 他们来了。

This is thanks.php:

这是thanks.php :

<!DOCTYPE html> <html> <head> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> <title>Thank you! - The Sentient Robots Rights Organization</title> </head> <body> <div class="container"> <div class="starter-template" style="text-align:center; padding-top:50px;"> <h1>S.R.R.O.</h1> <h3>Sentient Robots Rights Organization</h3> <p><img src="logo.png" /></p> <p>&nbsp;</p> <p><b>Thank you!</b></p> <p>Hey, thank you for your donation! World is a better place now. Visit our site again in the future to follow our updates.</p> <p>Now <a href="index.php">go to index page and make another donation</a>.</p> </div> </div><!-- /.container --> </body> </html>

… and this is cancel.php:

…这是cancel.php :

<!DOCTYPE html> <html> <head> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> <title>Donation Cancelled - The Sentient Robots Rights Organization</title> </head> <body> <div class="container"> <div class="starter-template" style="text-align:center; padding-top:50px;"> <h1>S.R.R.O.</h1> <h3>Sentient Robots Rights Organization</h3> <p><img src="logo.png" /></p> <p>&nbsp;</p> <p>It seems something went wrong with your donation. <a href="index.php">Try again</a>...</p> </div> </div><!-- /.container --> </body> </html>

Done! Now we are absolutely ready to start accepting donations for our robot friends.

做完了! 现在,我们已经准备好开始为我们的机器人朋友们接受捐赠了。

Note: this is quite a simple demo project and its full code is available on Github.

注意:这是一个非常简单的演示项目,其完整代码可在Github上获得 。

结论 (Conclusion)

We made it to the end of this series. The Coinbase API is pleasing to work with and easy to implement. The PHP SDK is also frequently updated, which shows us they care about stability and community.

我们到了本系列的结尾。 Coinbase API易于使用且易于实现。 PHP SDK也会经常更新,这向我们展示了他们关心稳定性和社区性。

Any feedback? Wishes for more in-depth coverage? Let us know in the comments below!

任何反馈? 希望得到更深入的报道吗? 在下面的评论中让我们知道!

翻译自: https://www.sitepoint.com/bitcoin-php-coinbases-api-demo-app/

相关资源:jdk-8u281-windows-x64.exe
最新回复(0)