Passed
Push — master ( df05de...783437 )
by Darko
05:58
created

BtcPayWebhookListener::handle()   A

Complexity

Conditions 5
Paths 10

Size

Total Lines 18
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
eloc 13
c 2
b 1
f 0
dl 0
loc 18
rs 9.5222
cc 5
nc 10
nop 1
1
<?php
2
3
namespace App\Listeners;
4
5
use App\Models\User;
6
use BTCPayServer\Client\Invoice;
7
use BTCPayServer\Exception\BTCPayException;
8
use Illuminate\Support\Facades\Log;
9
use Petzsch\LaravelBtcpay\Constants\BtcPayConstants;
10
use Petzsch\LaravelBtcpay\Events\BtcpayWebhookReceived;
11
use Petzsch\LaravelBtcpay\LaravelBtcpay;
12
13
class BtcPayWebhookListener
14
{
15
    /**
16
     * Create the event listener.
17
     */
18
    public function __construct()
19
    {
20
        //
21
    }
22
23
    /**
24
     * Handle the event.
25
     */
26
    public function handle(BtcpayWebhookReceived $event): void
27
    {
28
        $payload = $event->payload;
29
        if ($payload['event']['code'] === BtcPayConstants::INVOICE_WEBHOOK_CODES) {
30
            // We have received a payment for an invoice and user should be upgraded to a paid plan based on order
31
            try {
32
                $invoice = LaravelBtcpay::getInvoice($payload['data']['id']);
33
                $invoice_status = $invoice->getStatus();
34
                if ($invoice_status === 'Settled') {
35
                    preg_match('/(?P<role>\w+(\+\+)?)[ ](?P<addYears>\d+)/i', $invoice->getData()['metadata']['itemDesc'], $matches);
36
                    $user = User::query()->where('email', '=', $invoice->getData()['metadata']['buyerEmail'])->first();
37
                    if ($user) {
38
                        User::updateUserRole($user->id, $matches['role']);
39
                        User::updateUserRoleChangeDate($user->id, null, $matches['addYears']);
40
                    }
41
                }
42
            } catch (BTCPayException $e) {
43
                Log::error($e->getMessage());
44
            }
45
        }
46
    }
47
}
48