krich/nem-php

PHP (Laravel 或纯 PHP) 的 Composer 包,用于使用与 NIS 兼容的 NEM 区块链 REST API 和 SDK 的包装器。

v0.2.14 2018-10-25 17:39 UTC

README

Build Status Total Downloads Latest Stable Version Latest Unstable Version License

此包旨在提供一个易于使用的 PHP Laravel 命名空间,帮助开发人员通过其 NIS API 与 NEM 区块链进行通信。

此包应有助于任何在 Laravel/Lumen/Symfony 应用程序中使用 NEM 区块链的开发人员。

此包目前仍在开发中,请勿在生产环境中使用。

此包的作者不对由此包引起的任何金钱损失或恶意使用形式承担责任。请谨慎使用此包。

此包在 MIT 许可下授权。

文档

在开发期间将添加易于阅读的文档,并可在 Github Wiki 上找到,网址为 evias/nem-php Wiki

目前,项目已集成 phpdocumentor 以从源代码自动生成 API 文档。如果您想生成文档,必须运行 phpdocphpdocmd 命令,首个稳定版本将包含生成的文档版本。

# First build the API documentation
./vendor/bin/phpdoc -d src/ -t build/ --template="xml"

# Then generate the Markdown
./vendor/bin/phpdocmd build/structure.xml docs/

奖金

如果您喜欢这个倡议,并且为了良好的心情,我建议您花几分钟时间通过发送一些 XEM(或您认为有一天会支付我几杯啤酒的任何代币)到我的钱包来捐赠一杯啤酒或三杯(因为比利时人喜欢这样)。

NB72EM6TTSX72O47T3GQFL345AB5WYKIDODKPPYW

安装

您可以使用 Composer 安装此包。您只需要要求 evias/nem-php。

composer require evias/nem-php

您也可以通过克隆此存储库或下载 Packagist 存档手动下载此包。

一旦您在 composer.json 文件中(或使用上述命令)要求了此包,您就可以安装此包的依赖项。

composer install

单元测试

该库提供了实现 SDK 功能的单元测试套件。

单元测试套件已在 Travis-CI 上配置,并显示当前构建状态。

  • Build Status

如果您想运行单元测试套件,您可以使用 PHPUnit 提供的可执行文件,该文件位于 vendor/bin/phpunit 下。

作为替代,您可以在 nem-php 克隆根目录中创建此可执行文件的符号链接。

ln -s vendor/bin/phpunit 

现在,您可以在终端中简单地运行 phpunit,它将启动火箭.. 嘛,单元测试套件。

Laravel 高级功能

修改您的 config/app.php 配置文件以包含 NEM\ServiceProvider 服务提供者。注意 providers 配置数组,并添加以下类

'providers' => [
    NEM\ServiceProvider::class,
],

如果您想使用此库提供的 Laravel Facades,您还需要在 config/app.php 配置文件下的 aliases 配置数组中列出别名,如下所示

'aliases' => [
    'NemSDK' => NEM\Facades\NemSDK::class,
],

使用/示例

安装 evias/nem-php 包后,您将能够使用 API 类向配置的 NIS 发送 API 请求。默认情况下,config/nem.php 文件定义了要使用的 localhost NIS,这可以更改。

如果您正在使用Laravel或Lumen,则需要将此包的服务提供者注册到您的应用程序中

    // Laravel/Lumen registering the service provider
    $app = Laravel\Lumen\Application(realpath(__DIR__));
    $app->register(NEM\ServiceProvider::class);

示例1:使用服务提供者(仅限Laravel)

    // Example 1: Using the Service Provider
    // --------------------------------------
    // The Service Provider for Laravel/Lumen will bind "nem.config",
    // "nem" and "nem.ncc" in the IoC. "nem" and "nem.ncc" are pre-
    // configured instances of the API class using APP_ENV for the environment.
    $nemConfig = $app["nem.config"]
    $nemAPI = $app["nem"];
    $nccAPI = $app["nem.ncc"];

示例2:使用API包装器

    // Example 2: Instantiating the API class
    // --------------------------------------
    // You can also create a new instance of the API
    $nemAPI = new NEM\API();
    $nemAPI->setOptions([
        "protocol" => "http",
        "use_ssl" => false,
        "host" 	  => "go.nem.ninja",
        "port"    => 7890,
        "endpoint" => "/",
    ]);

    // If you wish you can define your own RequestHandler, have a look at the
    // NEM\Contracts\RequestHandler interface.
    $nemAPI->setOptions(["handler_class" => Path\To\My\Handler::class]);

示例3:向NIS API发送GET/POST请求并获取JSON响应

    // Example 3: Sending GET/POST JSON requests
    // -----------------------------------------
    // The API wrapper class can be used to send API requests to the
    // configured NIS host with following snippet:
    $response = $nemAPI->getJSON("heartbeat", "");

    // sending JSON through POST and receiving JSON back.
    $postData = ["myField" => "hasThisValue", "yourField" => "isNotEmpty"];
    $response = $nemAPI->postJSON("post/endpoint", json_encode($postData));

示例4:自定义头部和响应回调配置

    // Example 4: Custom headers and Callback configuration
    // -----------------------------------------------------
    // The 3rd parameter of the get() and post() methods lets you pass
    // an options array to the RequestHandler. To add specific headers for
    // example you would do as follows:
    $response = $nemAPI->getJSON("hearbeat", "", ["headers" => ["Content-Type" => "text/xml"]]);

    // You may also define onSuccess, onError and onReject callbacks to be executed
    // when the Guzzle Promises respectively complete, encounter an error or are denied.
    // @see Psr\Http\Message\ResponseInterface
    // @see GuzzleHttp\Exception\RequestException
    $response = $nemAPI->getJSON("heartbeat", "", [
        "onSuccess" => function(ResponseInterface $response) {
            echo $response->getBody();
        },
        "onError" => function(RequestException $exception) {
            echo "This is bad: " . $exception->getMessage();
        },
        "onReject" => function($reason) {
            echo "Request could not be completed: " . $reason;
        }
    ]);

示例5:使用SDK创建NEM NIS兼容 对象

    // Example 5: Use the SDK to create NEM *NIS compliant* Objects
    // ------------------------------------------------------------
    // You can create an instance and pass the *connection configuration*
    $sdk = new NEM\SDK([
        "protocol" => "http",
        "use_ssl" => false,
        "host" 	  => "go.nem.ninja",
        "port"    => 7890,
        "endpoint" => "/",
    ]);

    // Or you can use an already initialized API client
    $sdk = new NEM\SDK([], new NEM\API());
    $account = $sdk->models()->account(["address" => "TDWZ55R5VIHSH5WWK6CEGAIP7D35XVFZ3RU2S5UQ"]);

    // The \NEM\Contracts\DataTransferObject interface tells us that Models
    // always have a toDTO() method which will format the said object into
    // its *NIS compliant* object.

    // Dump [AccountMetaDataPair](https://bob.nem.ninja/docs/#accountMetaDataPair) object
    var_dump($account->toDTO());

示例6:使用SDK的NIS Web服务实现

    // Example 6: Use the SDK NIS Web Service implementations
    // ------------------------------------------------------------
    $sdk = new NEM\SDK();
    $service = $sdk->account();

    // Generate a new account
    $account = $service->generateAccount(); // $account is an instance of \NEM\Models\Account

    // Read account data *from the NEM blockchain* using the Address
    $account = $service->getFromAddress("TDWZ55R5VIHSH5WWK6CEGAIP7D35XVFZ3RU2S5UQ");

    // Read account data *from the NEM blockchain* using the Public Key
    $account = $service->getFromPublicKey("d90c08cfbbf918d9304ddd45f6432564c390a5facff3df17ed5c096c4ccf0d04");

示例7:使用SDK读取账户的交易

    // Example 7: Use the SDK to read an account's transactions
    // ------------------------------------------------------------
    $sdk = new NEM\SDK();
    $service = $sdk->account();

    // Get incoming transaction for an account by its address
    // $incomings will be an instance of \NEM\Models\ModelCollection
    $incomings = $service->incomingTransactions("TDWZ55R5VIHSH5WWK6CEGAIP7D35XVFZ3RU2S5UQ");

    // Get outgoing transaction for an account by its address
    $outgoings = $service->outgoingTransactions("TDWZ55R5VIHSH5WWK6CEGAIP7D35XVFZ3RU2S5UQ");

    // Get unconfirmed transaction for an account by its address
    $unconfirmed = $service->unconfirmedTransactions("TDWZ55R5VIHSH5WWK6CEGAIP7D35XVFZ3RU2S5UQ");

示例8:使用十六进制或二进制私钥推导公钥

    // Example 8: Derive a Public Key with a hexadecimal or binary Private Key
    // --------------------------------------------------------------------------
    $privateKey = "e77c84331edbfa3d209c4e68809c98a634ad6e8891e4174455c33be9dd25fce5";
    $publicKey  = "d90c08cfbbf918d9304ddd45f6432564c390a5facff3df17ed5c096c4ccf0d04";
    $keypair = new NEM\Core\KeyPair($privateKey);
    var_dump($keypair->getPublicKey("hex")); // will output: 

    // Create with *provided public key* (no derivation - faster)
    $keypair = new NEM\Core\KeyPair($privateKey, $publicKey);

示例9:创建新的密钥对和地址(随机生成)

    // Example 9: Create New KeyPair and Address (randomly)
    // --------------------------------------------------------------------------
    $keypair = new NEM\Core\KeyPair();
    $address = NEM\Models\Address::fromPublicKey($keypair->getPublicKey());

    var_dump($keypair->getPrivateKey("hex"), $address->toClean());

示例10:使用NEM密钥对签名数据

    // Example 10: Sign Data with a NEM KeyPair
    // --------------------------------------------------------------------------
    $keypair = new NEM\Core\KeyPair("abf4cf55a2b3f742d7543d9cc17f50447b969e6e06f5ea9195d428ab12b7318d");

    var_dump($keypair->sign("nem-php by eVias!")->getHex());
    // this will show you the following hexadecimal signature:
    // 177908f0cb5e56a0da11bfc3b38f6d749c4c870c9b356313db6460925e4584a9304e6aa1a5ba50ec2f773bbdfbfc03285a35d986d056df27b7d05a74f6c9b501

    // you can now use this signature and verify it using the Public Key

故障排除/问题解决

使用MacOS MAMP或MAMP Pro安装依赖项

可能发生的情况是您的PHP服务器没有安装正确的版本,或者没有加载正确的扩展,因此这里有一个小片段可以为您提供所需的精确PHP版本(您还需要编译httpd)。

首先,您需要重新构建httpd服务

mkdir ~/httpd-2.2.34/

# Download httpd source code
cd ~/Downloads
wgets http://apache.belnet.be//httpd/httpd-2.2.34.tar.bz2
tar xvzf httpd-2.2.34.tar.bz2

# We now have the HTTPD source code unarchived
cd httpd-2.2.34
./configure
make
make install

上述步骤仅因为MAMP不包含Apache构建/文件夹(您现在可以在~/httpd-2.2.34/下找到它)。好,下一步是重新编译PHP 作为Apache模块,这是MAMP所要求的。以下片段将允许您下载并编译PHP包,启用GMP、GD、MySQL、XML、CURL、GETTEXT、MBSTRING和BCMATH模块。

# This is where the *built* PHP will be installed.
mkdir ~/php-7.1.8/

# Download php source code
cd ~/Downloads
wgets http://de2.php.net/get/php-7.1.8.tar.bz2/from/this/mirror
tar xvzf php-7.1.8.tar.bz2

# We now have the PHP source code unarchived
cd php-7.1.8

# MacOS
brew install intltool icu4c gettext
brew link icu4c gettext
./configure --with-apxs2=/Applications/MAMP/Library/bin/apxs --prefix=/Users/greg/php-7.1.8 --enable-intl --with-gmp --with-xmlrpc --enable-bcmath --with-curl=/usr --with-gettext=/usr/local/Cellar/gettext/ --with-gd --with-pdo-mysql --with-openssl=/usr/local/Cellar/openssl/1.0.2n/ --enable-mbstring
make
make install
# End-MacOS

# Linux
./configure --prefix=/home/greg/php-7.1.8 --enable-intl --with-gmp --with-xmlrpc --enable-bcmath --with-curl=/usr --with-gettext --with-gd --with-pdo-mysql --with-openssl
make
make install
# End-Linux

构建PHP源代码后,您还需要将系统链接到该文件。以下是一个简单的解决方案,但务必在覆盖可执行文件之前备份任何文件。

PHP的编译将安装一个文件:~/httpd-2.2.34/modules/libphp7.so,您必须将系统链接到该文件,以便使用正确的PHP模块。使用以下片段链接PHPapache模块和您的MAMP安装中的PHP可执行文件。

mkdir /Applications/MAMP/Library/build
cp -R /Users/greg/httpd-2.2.34/build/* /Applications/MAMP/Library/build/
sudo ln -s /Users/greg/httpd-2.2.34/modules/libphp7.so /Applications/MAMP/bin/php/php7.1.8/modules/
sudo ln -s /Users/greg/php-7.1.8/bin/php /usr/local/bin/php

变更日志

以下列出了重要版本。有关项目的完整历史记录,请参阅变更日志

许可证

本软件根据MIT许可证发布。

© 2017-2018 Grégory Saive greg@evias.be,版权所有。