victorybiz/laravel-crypto-payment-gateway

GoUrl.io Crypto Payment Gateway for Laravel

v1.3.0 2024-04-01 19:16 UTC

This package is auto-updated.

Last update: 2024-08-31 00:31:32 UTC


README

GoUrl.io Crypto Payment Gateway for Laravel.

Latest Version on Packagist Total Downloads GitHub Actions

preview

目录


安装

您可以通过 composer 安装此包。

composer require victorybiz/laravel-crypto-payment-gateway

接下来,您应该使用 vendor:publish Artisan 命令发布配置、迁移和资产文件。配置、迁移和资产文件将分别放置在您的应用的 configdatabase/migrationspublic/vendor 目录中。

php artisan vendor:publish --provider="Victorybiz\LaravelCryptoPaymentGateway\LaravelCryptoPaymentGatewayServiceProvider"

需求

此包在 GoUrl.ioCryptoAPI 支付网关 上创建了一个 Laravel 包装器。

  • GoUrl.io 网站上免费注册或登录。
  • 创建 新的支付盒子
  • 确保指定您的外部钱包地址和回调 URL。
  • 获取您要支持的每种货币支付盒子的公钥和私钥。

依赖

使用 AlpinejsTailwindCSScompactstandard 盒子模板。而 gourl-cryptobox-iframegourl-cryptobox-boostrap 使用的是 GoUrl.io 提供的资产。您不需要安装任何依赖项,此包使用依赖项的 CDN 版本。

配置

您需要创建以下文件;

  • 一个带有 callback 方法的 PaymentController。有关更多详细信息,请参阅下文。
  • 在任何地方创建一个静态类方法以钩接 IPN(即时支付通知)。最好您可以在同一 PaymentController 中定义静态方法 public static function ipn($cryptoPaymentModel, $payment_details, $box_status){..},以便于代码管理。有关更多详细信息,请参阅下文。
  • 定义支付路由。
  • 在环境文件中定义公钥和私钥。
定义支付路由
// routes/web.php

// You can protect the 'payments.crypto.pay' route with `auth` middleware to allow access by only authenticated user
Route::match(['get', 'post'], '/payments/crypto/pay', Victorybiz\LaravelCryptoPaymentGateway\Http\Controllers\CryptoPaymentController::class)
                ->name('payments.crypto.pay');

// You you need to create your own callback controller and define the route below
// The callback route should be a publicly accessible route with no auth
// However, you may also exclude the route from CSRF Protection by adding their URIs to the $except property of the VerifyCsrfToken middleware.
Route::post('/payments/crypto/callback', [App\Http\Controllers\Payment\PaymentController::class, 'callback'])
                ->withoutMiddleware(['web', 'auth']);

有关 回调路由 的更多详细信息,请参阅下文。

在环境文件中定义公钥和私钥。

在您的.env文件中定义了创建的支付盒的公钥和私钥,用于您各种货币。

GOURL_PAYMENTBOX_BITCOIN_PUBLIC_KEY
GOURL_PAYMENTBOX_BITCOIN_PRIVATE_KEY

GOURL_PAYMENTBOX_BITCOINCASH_PUBLIC_KEY
GOURL_PAYMENTBOX_BITCOINCASH_PRIVATE_KEY

配置选项

请参阅已发布的config/laravel-crypto-payment-gateway.php,了解自定义支付盒的可用选项,例如更改logobox_templatebox_template_options和其他配置选项。

使用方法

支付数据提交

支付数据可以通过以下方式进行提交:

  • 表单提交
  • AJAX请求
  • 会话重定向(通过控制器、Livewire组件或您的应用程序中的任何地方)

无论哪种方法,都需要发送BTC中的数据字段amount或USD中的amountUSD,两者不能同时使用。可选数据字段userIDorderID(如果您想将数据引用到应用程序中的任何模型,例如产品模型)以及redirect(在收到付款后要重定向到的URL)。

表单提交的使用
<form id="payment-form" method="post" action="{{ route('payments.crypto.pay) }}">
  @csrf
  <input type="text" name="amountUSD" placeholder="Amount">
    <input type="hidden" name="userID" value="{{ Auth::user()->id }}">
  <input type="hidden" name="orderID" value="1">
  <input type="hidden" name="redirect" value="{{ url()->full() }}">
  <button type="submit">Pay</button>
</form>       
AJAX请求的使用
axios({
  method: "post",
  url: "/payments/crypto/pay",
  data: {
    amountUSD: 20.50,
    userID: 1,
    orderID: 101,
    redirect: 'https://domain.com/redirect-url',
  },
  headers: {
    'Accept': 'application/json'
    // Ensure you include your TOKEN as well
  },
})
  .then(function (response) {
    // The url is available in `data` key of the json response:
    // {
    //   status: true,
    //   message: 'Request successful.',
    //   data: 'https://your-domain.com/payments/crypto/pay?cryptopsid=some-unique-token-string'
    // }
    if (response.data.status === true) {
      const paymentUrl = response.data.data
      window.location = paymentUrl
    }
  })
  .catch(function (response) {
    //handle error
    console.log(response);
  });
通过控制器、Livewire组件或应用中的任何位置使用会话重定向

您需要确保在发送到支付网关之前验证您的数据

// This could be in a controller method or livewire component method
use Victorybiz\LaravelCryptoPaymentGateway\LaravelCryptoPaymentGateway;

$payment_url = LaravelCryptoPaymentGateway::startPaymentSession([
    'amountUSD' => $validatedData['amount'], // OR 'amount' when sending BTC value
    'orderID' => $product->id,
    'userID' => Auth::user()->id,
    'redirect' => url()->full(),
]);
// redirect to the payment page
redirect()->to($payment_url);

回调

当用户完成付款时,GoUrl.io的服务器将通过您在加密支付盒的“回调URL”字段中指定的回调URL使用HTTP POST方法发送支付数据。

回调控制器

创建一个PaymentController并调用Laravel Crypto Payment Gateway的回调方法实例。

<?php

namespace App\Http\Controllers\Payment;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Victorybiz\LaravelCryptoPaymentGateway\LaravelCryptoPaymentGateway;

class PaymentController extends Controller
{
    /**
     * Cryptobox callback.
     */
    public function callback(Request $request)
    {   
      return LaravelCryptoPaymentGateway::callback();
    }
}
回调路由

定义回调路由到创建的控制器,回调路由应该是一个公开可访问的路由,没有认证。但是,您也可以通过将它们的URI添加到VerifyCsrfToken中间件的$except属性中,排除该路由的CSRF保护。如果您使用Cloudflare、Mod_Security和其他CDN服务,请点击这里查看您需要添加到白名单中的GoUrl.io服务器IP。

// routes/web.php
 
Route::post('/payments/crypto/callback', [App\Http\Controllers\Payment\PaymentController::class, 'callback'])
                ->withoutMiddleware(['web', 'auth']);

IPN(即时支付通知)

一旦GoUrl.io的Cryptobox Class在幕后处理完接收到的回调,然后它会调用一个cryptobox_new_payment(...)函数,该函数允许您定义付款后的处理。要连接到该函数以处理IPN(即时付款通知)并执行自定义处理,例如发送电子邮件通知和在确认付款后向用户赋值,创建一个静态类方法。这可以是在您应用程序中的任何地方定义的静态类方法。最好您只需在相同的PaymentController中定义静态方法,以便于代码管理。

<?php

namespace App\Http\Controllers\Payment;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Victorybiz\LaravelCryptoPaymentGateway\LaravelCryptoPaymentGateway;

class PaymentController extends Controller
{
    //...
    
    /**
     * Cryptobox IPN Example
     * 
     * @param \Victorybiz\LaravelCryptoPaymentGateway\Models\CryptoPaymentModel $cryptoPaymentModel
     * @param array $payment_details
     * @param string $box_status
     * @return bool
     */
    public static function ipn($cryptoPaymentModel, $payment_details, $box_status)
    {            
        if ($cryptoPaymentModel) {  
            /*
            // ADD YOUR CODE HERE
            // ------------------
            // For example, you have a model `UserOrder`, you can create new Bitcoin payment record to this model
            $userOrder = UserOrder::where('payment_id', $cryptoPaymentModel->paymentID)->first();
            if (!$userOrder) 
            {
                UserOrder::create([
                    'payment_id' => $cryptoPaymentModel->paymentID,
                    'user_id'    => $payment_details["user"],
                    'order_id'   => $payment_details["order"],
                    'amount'     => floatval($payment_details["amount"]),
                    'amountusd'  => floatval($payment_details["amountusd"]),
                    'coinlabel'  => $payment_details["coinlabel"],
                    'txconfirmed'  => $payment_details["confirmed"],
                    'status'     => $payment_details["status"],
                ]);
            }
            // ------------------

            // Received second IPN notification (optional) - Bitcoin payment confirmed (6+ transaction confirmations)
            if ($userOrder && $box_status == "cryptobox_updated")
            {
                $userOrder->txconfirmed = $payment_details["confirmed"];
                $userOrder->save();
            }
            // ------------------
            */

            // Onetime action when payment confirmed (6+ transaction confirmations)
            if (!$cryptoPaymentModel->processed && $payment_details["confirmed"])
            {
                // Add your custom logic here to give value to the user.
        
                // ------------------
                // set the status of the payment to processed
                // $cryptoPaymentModel->setStatusAsProcessed();

                // ------------------
                // Add logic to send notification of confirmed/processed payment to the user if any
            }
            
        }
        return true;
    }
}

然后更新已发布的config/laravel-crypto-payment-gateway.php并设置hook_ipn键的值,将IPN(即时付款通知)功能连接到上面定义的静态类方法。

// config/laravel-crypto-payment-gateway.php

/**
 * Hook IPN (Instant payment notification) to the following static class method.
 * In this static class method, you can  add your custom logic and give value to the user once your confirmed payment box status.
 * You can also add payment notification logic. 
 * This can be a static class method defined anywhere in your application.
 * This can also be static method/action defined in controller class but route must not be defined for the action.
 * 
 * The Static Method Definition in your class:
 * @param \Victorybiz\LaravelCryptoPaymentGateway\Models\CryptoPaymentModel $cryptoPaymentModel
 * @param array $payment_details
 * @param string $box_status
 * @return bool
 * public static function ipn($cryptoPaymentModel, $payment_details, $box_status)
 * {
 *  // Add your custom logic here.
 *  return true;
 * }
 * 
 * Example: [\Victorybiz\LaravelCryptoPaymentGateway\Http\Controllers\CryptoPaymentController::class, 'ipn']
 */
'hook_ipn' => [\App\Http\Controllers\Payment\PaymentController, 'ipn'],

crypto_payments 表的 Eloquent 模型

此包为crypto_payments提供Eloquent模型。

use Victorybiz\LaravelCryptoPaymentGateway\Models\CryptoPaymentModel;

$cryptoPayment = CryptoPaymentModel::find($paymentID);

$cryptoPayment = CryptoPaymentModel::where('paymentID', $paymentID);

$processedCryptoPayment = CryptoPaymentModel::where('processed', true);

高级使用

GoUrl.io PHP Class API 的实例(cryptobox.class.php

此包提供对核心GoUrl.io实例的访问,cryptobox.class.php是该包在幕后使用的。

use Victorybiz\LaravelCryptoPaymentGateway\LaravelCryptoPaymentGateway;

$laravelCryptoPaymentGateway = new LaravelCryptoPaymentGateway;

$cryptobox = $laravelCryptoPaymentGateway->getCryptobox($options = []);

$payment_history = $cryptobox->payment_history($boxID = "", $orderID = "", $userID = "", $countryID = "", $boxType = "", $period = "7 DAY");

点击这里了解有关GoUrl.io PHP Class API和可用方法的更多信息。

资源

以下包组合在一起构成了这个无缝包。

测试

composer test

变更日志

有关最近更改的更多信息,请参阅变更日志

贡献

有关详细信息,请参阅贡献指南

安全

如果您发现任何安全相关的问题,请通过电子邮件lavictorybiz@gmail.com而不是使用问题跟踪器。

鸣谢

许可

MIT许可证(MIT)。有关更多信息,请参阅许可文件

Laravel 包模板

本包使用 Laravel Package Boilerplate 生成的。