petzsch/laravel-btcpay

此包已被废弃,不再维护。没有推荐替代包。

laravel的BtcPay包装器

v6.0.3 2022-11-18 13:04 UTC

README

该项目不再维护。因此已被存档。

LaravelBtcPay

LaravelBtcPay Social Image

Latest Version on Packagist Total Downloads

LaravelBtcPay使您和您的业务能够在Laravel应用程序中交易比特币、莱特币和10+其他BtcPay支持的加密货币。

需要PHP ^7.3

支持资源

内容

安装

安装包

您可以通过composer安装此包

composer require petzsch/laravel-btcpay

发布配置文件

使用以下命令发布配置文件

php artisan vendor:publish --provider="Petzsch\LaravelBtcpay\LaravelBtcpayServiceProvider"

这将在您的config目录内创建一个laravel-btcpay.php文件。

添加配置值

将以下键添加到您的.env文件中,并将值更新为您的偏好设置(有关配置的更多信息,请参阅配置说明

BTCPAY_API_KEY=YourRandomApiKeyThatYouOptainedFromYourBTCPayUserSettings
BTCPAY_SERVER_URL=https://btcpay.your.server.tld

配置Webhooks(可选)

BtcPay资源状态更新完全基于webhooks(IPNs)。LaravelBtcPay完全能够自动处理webhook请求。每当从BtcPay服务器接收到webhook时,都会触发BtcpayWebhookReceived事件。请执行以下步骤以配置您的应用程序以监听webhook

1. 设置您的webhook路由

在您希望的路线文件(推荐使用web.php)中解析btcPayWebhook路由宏。该宏接受一个单个的、可选的参数,即您希望接收BtcPay webhook POST请求的URI路径。如果没有提供,则默认为'laravel-btcpay/webhook'

// ... your other 'web' routes

Route::btcPayWebhook(); // https://example.com/laravel-btcpay/webhook

// OR ...

Route::btcPayWebhook('receive/webhooks/here'); // https://example.com/receive/webhooks/here

ℹ️ 要在应用程序的任何位置检索您刚创建的webhook路由,请使用:route('laravel-btcpay.webhook.capture')

LaravelBtcPay 还提供了自动填充配置的 webhook URL 的便利性。具体来说,当

您可以通过取消注释 laravel-btcpay.php 配置文件中的 auto_populate_webhook 数组中的相应条目来为每个资源启用此功能。

⚠️ 如果手动设置了值,很可能是通过在资源初始化期间使用 $resource->setNotificationURL('https://...'),则自动填充将被覆盖。

2. 设置您的 webhook 监听器

首先生成一个事件监听器

php artisan make:listener BtcPayWebhookListener --event=\Petzsch\LaravelBtcpay\Events\BtcpayWebhookReceived

然后,在生成的监听器的 handle(...) 函数中实现您应用程序特定的逻辑。

在以下示例中,我们假设您已经创建了一个发票,并将它的 token 存储在您的内部 Order 模型中

/**
 * Handle the webhook event, keeping in mind that the server doesn't trust the client (us), so neither should
 * we trust the server. Well, trust, but verify.
 *
 * @param BtcpayWebhookReceived $event
 * @return void
 */
public function handle(BtcpayWebhookReceived $event)
{
    // Extract event payload
    $payload = $event->payload;

    // Verify that webhook is for a BtcPay Invoice resource
    if (in_array($payload['event']['code'], array_keys(BtcPayConstants::INVOICE_WEBHOOK_CODES))) {
        try {
            // Do not trust the webhook data. Pull the referenced Invoice from BtcPay's server
            $invoice = LaravelBtcpay::getInvoice($payload['data']['id']);

            // Now grab our internal Order instance for this supposed Invoice
            $order = Order::whereOrderId($invoice->getOrderId())->first();

            // Verify Invoice token, previously stored at time of creation
            // Learn more at: https://github.com/petzsch/laravel-btcpay#create-an-invoice
            if ($invoice->getToken() !== $order->invoice_token) {
                return;
            }

            $invoice_status = $invoice->getStatus();

            // Do something about the new Invoice status
            if ($invoice_status === InvoiceStatus::Paid) {
                $order->update(['status' => $invoice_status]) && OrderStatusChanged::dispatch($order->refresh());
            }
        } catch (BtcPayException $e) {
            Log::error($e);
        }
    }
}

最后,将您的监听器映射到 EventServiceProvider$listen 数组中的 BtcpayWebhookReceived 事件

/**
 * The event listener mappings for the application.
 *
 * @var array
 */
protected $listen = [
    // ... other event-listener mappings
    BtcpayWebhookReceived::class => [
        BtcPayWebhookListener::class,
    ],
]

示例

发票

发票是面向特定买家的时效性付款请求。发票有一个固定的价格,通常以法定货币计价。它还有由 BtcPay 计算的支持的加密货币的等价价格,该价格在锁定的汇率下计算,并在 15 分钟(或您配置的任何时间)后过期。

创建发票

在这个示例中,我们假设您已经创建了一个相当于您的 Order 模型的实例,将其与这个发票相关联(称为 $order

TODO: 检查是否所有这些都可以与绿色领域暴露的发票对象一起工作!!!

// Create instance of Invoice
$invoice = LaravelBtcpay::Invoice(449.99, 'USD');

// Set item details (Only 1 item per Invoice)
$invoice->setItemDesc('You "Joe Goldberg" Life-Size Wax Figure');
$invoice->setItemCode('sku-1234');
$invoice->setPhysical(true); // Set to false for digital/virtual items

// Ensure you provide a unique OrderId for each Invoice
$invoice->setOrderId($order->order_id);

// Create Buyer Instance
$buyer = LaravelBtcpay::Buyer();
$buyer->setName('John Doe');
$buyer->setEmail('john.doe@example.com');
$buyer->setAddress1('2630 Hegal Place');
$buyer->setAddress2('Apt 42');
$buyer->setLocality('Alexandria');
$buyer->setRegion('VA');
$buyer->setPostalCode(23242);
$buyer->setCountry('US');
$buyer->setNotify(true); // Instructs BtcPay to email Buyer about their Invoice

// Attach Buyer to Invoice
$invoice->setBuyer($buyer);

// Set URL that Buyer will be redirected to after completing the payment, via GET Request
$invoice->setRedirectURL(route('your-btcpay-success-url'));
// Set URL that Buyer will be redirected to after closing the invoice or after the invoice expires, via GET Request
$invoice->setCloseURL(route('your-btcpay-cancel-url'));
$invoice->setAutoRedirect(true);

// Optional. Learn more at: https://github.com/vrajroham/laravel-btcpay#1-setup-your-webhook-route
$invoice->setNotificationUrl('https://example.com/your-custom-webhook-url');

// This is the recommended IPN format that BtcPay advises for all new implementations
$invoice->setExtendedNotifications(true);

// Create invoice on BtcPay's server
$invoice = LaravelBtcpay::createInvoice($invoice);

$invoiceId = $invoice->getId();
$invoiceToken = $invoice->getToken();

// You should save Invoice ID and Token, for your reference
$order->update(['invoice_id' => $invoiceId, 'invoice_token' => $invoiceToken]);

// Redirect user to the Invoice's hosted URL to complete payment
// This could be done more elegantly with our JS modal!
$paymentUrl = $invoice->getUrl();
return Redirect::to($paymentUrl);

ℹ️ 建议您在您的内部模型中存储发票 ID 和令牌。令牌在验证 webhook 时可能很有用。

检索现有发票

$invoice = LaravelBtcpay::getInvoice('invoiceId_sGsdVsgheF');

检索现有发票列表

在这个示例中,我们检索所有 MTD(月度发票):TODO:绿色领域不支持!!!

$startDate = date('Y-m-d', strtotime('first day of this month'));
$endDate = date('Y-m-d');

$invoices = LaravelBtcpay::getInvoices($startDate, $endDate);

退款发票

TODO:添加对拉取付款的支持以实现退款(目前未包含)

测试

composer test

更新日志

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

贡献

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

安全

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

致谢

授权

MIT授权(MIT)。请参阅授权文件获取更多信息。