finTree/laravel-client

Laravel 客户端,用于与 Fintreen.com API 交互。

1.0.5 2023-12-15 20:37 UTC

This package is auto-updated.

Last update: 2024-09-15 22:17:03 UTC


README

Fintreen.com 的 Laravel 客户端,用于加密支付网关 API

MIT License

Fintreen.com Laravel 客户端


在 apiary 上查看文档

报告错误 · 请求功能 .

>>> PHP 客户端 <<<

已在 php 8.0, 8.1, 8.2 上测试。也应在 php 8.3 上表现良好。已在 laravel 9, 10 上测试。

使用 composer2 安装包。

安装

1. 将以下环境变量添加到您的 .env 文件中

#set true if you are using Laravel Backpack
FINTREEN_USE_BAKCPACK=false
FINTREEN_TEST_MODE=false
FINTREEN_TOKEN="yourfintreentoken" 
FINTREEN_EMAIL="yourfintreenemail"

2. 安装客户端

composer req fintreen/laravel-client

3. 发布配置

php artisan vendor:publish --tag=config

4. 迁移

php artisan migrate

Laravel BackPack + Settings 集成

如果您正在使用 Laravel BackPackSettings 扩展,您可以在 .env 中使用 FINTREEN_USE_BAKCPACK=true。这将从数据库中添加 fintreen_tokenfintreen_email 设置,并且默认客户端初始化(不带参数)将使用它们。但是,如果没有找到设置(数据库记录为空),即使您启用了 FINTREEN_USE_BAKCPACK 标志,它也将回退到 .env 中的配置值。否则,您可以在 initClient 方法上使用自己的参数。

用法

0. 通用用法

您可以使用 php-client 中的所有方法,使用 getClient() 方法。示例

$fintreen = new FintreenModel();
$fintreen->initClient();
$this->data['fintreenCurrencies'] = $fintreen->getClient()->getCurrenciesList();
$this->data['statusesList'] = $fintreen->getClient()->getOrderStatusList();
$this->data['calculation'] = $fintreen->getClient()->calculate($amount, $cryptoCodes);

/*####....*/

$fintreen->getClient()->createTransaction($amount, $cryptoCode)

/* you can also use:
checkTransaction(), getTransactionsList() and sendRequest() methods, just like in the php client with getClient() method. 
*/

/* Alternatively you can use createTransaction and getCurrenciesList without getClient*/

$fintreen->getCurrenciesList(); // This has cache wrapper with TTL of 10 minutes by default
// but you can use raw no cache method via client  $fintreen->getClient()->getCurrenciesList();

[$linkToRedirect, $createdTransaction] = $fintreen->createTransaction($amount, $cryptoCode);

1. 客户端初始化

由于这只是一个 Laravel 包装器,您可以不带参数初始化客户端。这将从 config/fintreen.php 文件中加载配置,该文件应已发布(安装点 3),它接受环境变量。

但您仍然可以使用自己的参数初始化客户端。

$fintreen = new FintreenModel();
$fintreen->initClient($token, $email, $isTest);

2. 计算

您可以使用现有的路由 {{route('fintreen.calculate')}} 进行计算,该路由默认为 /fintreen/calculate。您需要设置的 POST 参数是 currency(加密货币代码)和 amount(欧元中的法定货币)。

使用 jQuery 的示例

$request = $.ajax({
    url: "{{route('fintreen.calculate')}}",
    method: 'POST',
    data: {
        amount: amount,
        currency: currency,
    },
    beforeSend: function() {
        $('#submit-btn').addClass('hidden');
    },
    success: function(response) {
        // Handle success response
        if(response.status === 1) {
            $('#approx-to-pay').css('color', 'green').html(response.message);
            $('#submit-btn').removeClass('hidden');
        } else {
            $('#approx-to-pay').css('color', 'red').html(response.message);
            $('#submit-btn').addClass('hidden');
        }
    },
    error: function(error) {
        // Handle error response
        $('#request-response').css('color', 'red').text('Error calculation!');
    }
});

但当然,最好使用自定义路由。请参阅 ./vendor/fintreen/laravel-client/src/app/Http/Controllers/FintreenController.php 中的 calculateAction

use Fintreen\Laravel\app\Models\Fintreen\FintreenModel;

....

$fintreen = new FintreenModel();
$fintreen->initClient();
$calcData = $fintreen->getClient()->calculate($amount, $cryptoCodes);

注意,在自定义版本中,您可以设置 initClient 的参数,并使用逗号分隔的加密货币代码计算方法。

3. 创建交易

[$linkToRedirect, $createdTransaction] = $fintreen->createTransaction($amount, $cryptoCode);
return redirect($linkToRedirect); // Redirect user to gateway link

在真实项目中使用验证的示例

use Fintreen\Laravel\app\Exceptions\FintreenApiException;
use Fintreen\Laravel\app\Models\Fintreen\FintreenModel;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Response;
use Illuminate\Http\Request;

// .........

$fintreen = new FintreenModel();
$fintreen->initClient();
$this->data['fintreenCurrencies'] = $fintreen->getCurrenciesList();

if ($request->isMethod('post')) {
    $error = false;
    $token = $request->post('g-recaptcha-response');
    $cryptoCode = $request->post('crypto-code');
    $amount = (float)$request->post('amount');
    $captchaValidaion = $this->validateRecaptcha($token, 'submit');
    if (!$captchaValidaion) {
        $error = true;
        $this->data['validationErrors'][] = 'Google recaaptcha check failed';
    }
    if (!$amount) {
        $error = true;
        $this->data['validationErrors'][] = 'Minimum amount is ' . FintreenModel::MIN_EURO_AMOUNT_DEFAULT;
    }
    if (isset($this->data['fintreenCurrencies']['crypto'])) {
        $exists = false;
        foreach ($this->data['fintreenCurrencies']['crypto'] as $fintreenCryptoCurrency) {
            if ($fintreenCryptoCurrency['code'] == $cryptoCode) {
                if ( $fintreenCryptoCurrency['min_eur_api'] > $amount) {
                    $error = true;
                    $this->data['validationErrors'][] = 'Minimum amount is ' . $fintreenCryptoCurrency['min_eur_api'];
                }
                $exists = true;
                break;
            }

        }
        if (!$exists) {
            $error = true;
            $this->data['validationErrors'][] = 'Crypto code validation error';
        }
    } else {
        $error = true;
        $this->data['validationErrors'][] = 'Crypto code validation error';
    }

    if ($error === false) {
        try {
            [$linkToRedirect, $createdTransaction] = $fintreen->createTransaction($amount, $cryptoCode);
            return redirect($linkToRedirect);
        } catch (FintreenApiException $e) {
            Log::channel('fintreen_deposit')->debug($e->getMessage(), ['context' => $e]);
            $this->data['validationErrors'][] = 'Something went wrong';
        } catch (\Exception $e) {
            Log::channel('fintreen_deposit')->debug($e->getMessage(), ['context' => $e]);
            $this->data['validationErrors'][] = 'Something went wrong';
        }
    }
}

4. 交易列表和检查

4.1 交易列表

交易列表与 php 客户端类似。

可用于过滤的参数可以在这里找到 https://fintreen.docs.apiary.io/#/reference/order-flow/transactions-list/get-transactions-list/200?mc=reference%2Forder-flow%2Ftransactions-list%2Fget-transactions-list%2F200

use Fintreen\Laravel\app\Models\Fintreen\FintreenModel;

$fintreenModel = new FintreenModel();
$fintreenModel->initClient();

$filters = [];
$fintreenModel->getClient()->getTransactionsList($filters); // returns array

// Or use raw 
$fintreenModel->getClient()->sendRequest('transactions', 'GET', $filters); // returns json string

4.2 交易检查

要检查交易是否已支付,您可以使用控制台命令 fintreen:transactions:check

fintreen:transactions:check {$localId?} {--limit=}

它将在 FintreenModel 上运行 check 方法。

您也可以从实例中调用此方法并传递回调。

use Fintreen\Laravel\app\Models\Fintreen\FintreenModel;

//***

$fintreenModel = new FintreenModel();

$modelItem = $fintreenModel->find(1); // Use local id here
$modelItem->initClient(); // 
$modelItem->check();

// ! Or use callable 

// Callback usage in the application
$modelItem->check(function ($successfullTransaction) {
    // Code to deposit amount to user balance
});

!! 注意,只有当交易成功时,回调才会触发。

5. 如何处理交易支付事件(如果交易成功,在您的应用程序中存入余额)

这是最危险的一个。请小心,并避免双重检查和存入余额。

FintreenModel 上的 check 方法可以接收回调。如果交易已支付,它将

  1. 更新表中的状态
  2. 然后分派事件 FintreenTransactionIsSuccess
  3. 如果设置了回调,它将触发回调。

有两种方式 - 使用如上所述的自定义检查和事件订阅。

回调方法

$fintreenModel->check(function ($successfullTransaction) use ($someData) {
    // Code to deposit amount to user balance
});

!! 注意,只有当交易成功时,回调才会触发。

事件方法

当交易成功时,将触发 FintreenTransactionIsSuccess 事件。

use Fintreen\Laravel\app\Events\FintreenTransactionIsSuccess;

Event::listen(FintreenTransactionIsSuccess::class, function ($event) {
    // Handle the event, e.g., update user balance
});

要创建它,请阅读 https://laravel.net.cn/docs/10.x/events#registering-events-and-listeners

php artisan make:listener FintreenTransactionIsSuccessListener

监听器示例

<?php

namespace App\Listeners;

use Fintreen\Laravel\app\Events\FintreenTransactionIsSuccess;

class FintreenTransactionIsSuccessListener
{

    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {}

    /**
     * Handle the event.
     *
     * @param  object  $event
     * @return void
     */
    public function handle(FintreenTransactionIsSuccess $event)
    {
        $a = 1;
    }
}

不要忘记在您的 App\Providers\EventServiceProvider 中注册它

FintreenTransactionIsSuccess::class => [
    FintreenTransactionIsSuccessListener::class
]

!! 注意,只有当交易成功时,才会触发事件。

6. 使用 webhook

6.1 使用现有 webhook

您可以将现有 webhook 设置为在交易检查时检索数据。默认情况下,它使用 /fintreen/webhook,但您仍然需要在 https://fintreen.com/account/tokens 的“更新 webhook”部分中设置它,并且在 POST 请求的中间件中忽略 CsRF。为此,请编辑您的 VerifyCsrfToken,位于 App\Http\Middleware\VerifyCsrfToken

    protected $except = [
        'fintreen/webhook'
    ];

如果您正在使用现有 webhook,默认情况下它将在 FintreenModel 上运行 check 方法来处理交易。此方法将交易标记为成功并触发 FintreenTransactionIsSuccess 事件。

6.2 使用自定义 webhook

自定义 webhook 检索数据的示例。

  1. 创建路由
  2. 通过不带 Csrf 的 POST 请求检查其是否工作
  3. 在您的账户设置中设置它 https://fintreen.com/account/tokens 的“更新 webhook”部分
  4. 获取数据

在您的 routes/web.php 中

Route::post('/your/fintreen/webhook/path', [YourController::class,'yourWebHookAction' ])
->name('fintreen-webhook')
->withoutMiddleware([\App\Http\Middleware\VerifyCsrfToken::class]);

6.3 Webhook 格式

格式是 json

{"type":"TRANSACTION_WEBHOOK_PAID_CHECK","transaction_id":154}

要检索 webhook 数据以检查交易,您可以使用

$input = file_get_contents('php://input');
$dataSent = json_decode($input);

/// OR
$transacitonId = $request->post('transaction_id');

7. 良好的实践和异常处理

最好为这个库使用自己的日志通道。将新通道添加到 config/logging.php

'fintreen_deposit' => [
    'driver' => 'single',
    'path' => storage_path('logs/fintreen_deposit.log'),
    'level' => env('LOG_LEVEL', 'debug'),
],

目前有两种异常类型

FintreenClientException - 当客户端未正确初始化时

FintreenApiException - 当请求失败时