PHP code example of core45 / laravel-tubapay

1. Go to this page and download the library: Download core45/laravel-tubapay library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

core45 / laravel-tubapay example snippets


use Core45\LaravelTubaPay\Services\TubaPayCheckoutOptions;

public function __construct(private readonly TubaPayCheckoutOptions $checkoutOptions)
{
}

public function render(): View
{
    $grandTotalInMajorUnits = $this->cart->grandTotalGross() / 100; // if you store cents

    $tubaPayOptions = $this->checkoutOptions->forAmount($grandTotalInMajorUnits);

    // $tubaPayOptions->available === false  => TubaPay is not eligible for this amount
    // $tubaPayOptions->recommendedInstallments => pre-select this value
    // $tubaPayOptions->installments => list of available plans
    // $tubaPayOptions->consents => list of consents the customer must accept

    return view('checkout.cart', [
        'tubaPayOptions' => $tubaPayOptions,
    ]);
}

use Illuminate\Validation\ValidationException;

public function placeOrder(Request $request): RedirectResponse
{
    if ($request->input('payment_method') === 'tubapay') {
        $options = $this->checkoutOptions->forAmount($this->cart->total());

        if (! $options->available) {
            throw ValidationException::withMessages([
                'payment_method' => __('TubaPay is not available for this cart.'),
            ]);
        }

        $installments = (int) $request->input('tubapay_installments');
        if ($installments <= 0) {
            throw ValidationException::withMessages([
                'tubapay_installments' => __('Please pick an installment plan.'),
            ]);
        }

        $acceptedConsents = (array) $request->input('tubapay_consents', []);
        foreach ($options->consents as $consent) {
            if ($consent->

use Core45\LaravelTubaPay\Contracts\CheckoutSelectionStore;
use Core45\LaravelTubaPay\Services\TubaPayCheckoutService;
use Core45\TubaPay\DTO\CheckoutSelection;
use Core45\TubaPay\DTO\Customer;
use Core45\TubaPay\DTO\OrderItem;

public function __construct(
    private readonly CheckoutSelectionStore $selectionStore,
    private readonly TubaPayCheckoutService $checkoutService,
) {}

public function startTubaPayPayment(Order $order, array $installments, array $acceptedConsents): RedirectResponse
{
    $selection = new CheckoutSelection(
        installments: (int) $installments,
        acceptedConsents: $acceptedConsents,
        returnUrl: route('checkout.thanks', ['order' => $order->uuid]),
    );

    // Persist so it survives a request boundary (and so you can recover it if anything fails)
    $this->selectionStore->put($order->uuid, $selection);

    $customer = new Customer(
        firstName: $order->billing_first_name,
        lastName: $order->billing_last_name,
        email: $order->billing_email,
        phone: $order->billing_phone,
        street: $order->billing_street,
        zipCode: $order->billing_zip,
        town: $order->billing_town,
    );

    $items = $order->items->map(fn ($item) => new OrderItem(
        name: $item->name,
        totalValue: $item->total_gross_major, // major units (e.g. 1000.00 for 1000 PLN)
    ))->all();

    $transaction = $this->checkoutService->createTransaction(
        externalRef: $order->uuid,
        customer: $customer,
        items: $items,
        callbackUrl: route('tubapay.webhook'), // or the package's built-in route
        selection: $selection, // pass it explicitly — do not rely on the store fallback
    );

    return redirect($transaction->transactionLink);
}

use App\Listeners\TubaPay\HandlePaymentReceived;
use App\Listeners\TubaPay\HandleRecurringOrderRequested;
use App\Listeners\TubaPay\HandleTransactionAccepted;
use App\Listeners\TubaPay\HandleTransactionRejected;
use Core45\LaravelTubaPay\Events\PaymentReceived;
use Core45\LaravelTubaPay\Events\RecurringOrderRequested;
use Core45\LaravelTubaPay\Events\TransactionStatusChanged;
use Illuminate\Support\Facades\Event;

public function boot(): void
{
    Event::listen(TransactionStatusChanged::class, HandleTransactionAccepted::class);
    Event::listen(TransactionStatusChanged::class, HandleTransactionRejected::class);
    Event::listen(PaymentReceived::class, HandlePaymentReceived::class);
    Event::listen(RecurringOrderRequested::class, HandleRecurringOrderRequested::class);
}

namespace App\Listeners\TubaPay;

use App\Models\Order;
use Core45\LaravelTubaPay\Events\TransactionStatusChanged;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;

final class HandleTransactionAccepted implements ShouldQueue
{
    public function handle(TransactionStatusChanged $event): void
    {
        if (! $event->isAccepted()) {
            return;
        }

        $order = Order::query()->where('uuid', $event->getExternalRef())->first();

        if ($order === null) {
            Log::warning('TubaPay: order not found for accepted transaction', [
                'external_ref' => $event->getExternalRef(),
            ]);

            return;
        }

        // Idempotency — webhooks can retry
        if ($order->paid && $order->payment_gateway_name === 'tubapay') {
            return;
        }

        $order->forceFill([
            'paid' => true,
            'status' => 'processing',
            'payment_gateway_name' => 'tubapay',
            'payment_gateway_order_id' => $event->getAgreementNumber(),
        ])->save();
    }
}

final class HandleTransactionRejected implements ShouldQueue
{
    public function handle(TransactionStatusChanged $event): void
    {
        if (! $event->isRejected()) {
            return;
        }

        $order = Order::query()->where('uuid', $event->getExternalRef())->first();

        $order?->forceFill(['status' => 'cancelled'])->save();
    }
}

$event->getExternalRef();      // your order reference
$event->getAgreementNumber();  // TubaPay agreement number
$event->getStatus();           // AgreementStatus string
$event->isAccepted();
$event->isRejected();
$event->isPending();

use App\Models\Order;
use Core45\LaravelTubaPay\Contracts\TubaPayOrderResolver;
use Core45\LaravelTubaPay\Contracts\TubaPayTransactable;

final class OrderResolver implements TubaPayOrderResolver
{
    public function resolve(string $externalRef): ?TubaPayTransactable
    {
        return Order::query()->where('uuid', $externalRef)->first();
    }
}

use Core45\LaravelTubaPay\Contracts\TubaPayTransactable;

final class Order extends Model implements TubaPayTransactable
{
    public function markTubaPayAccepted(string $agreementNumber): void
    {
        $this->forceFill([
            'status' => 'paid',
            'tubapay_agreement_number' => $agreementNumber,
        ])->save();
    }

    public function markTubaPayRejected(string $status, ?string $agreementNumber = null): void
    {
        $this->forceFill([
            'status' => $status,
            'tubapay_agreement_number' => $agreementNumber,
        ])->save();
    }

    public function recordTubaPayEvent(string $event, string $details): void
    {
        $this->history()->create([
            'event' => $event,
            'details' => $details,
        ]);
    }

    public function isTubaPayPaid(): bool
    {
        return $this->status === 'paid';
    }
}

// AppServiceProvider::register()
$this->app->bind(
    \Core45\LaravelTubaPay\Contracts\TubaPayOrderResolver::class,
    \App\Services\OrderResolver::class,
);

$topBarContent = app(\Core45\LaravelTubaPay\Facades\TubaPay::class)::content()->topBar();

use Illuminate\Support\Facades\Schedule;

Schedule::command('tubapay:prune-selections')
    ->daily()
    ->onOneServer();

use Core45\LaravelTubaPay\Models\TubaPayTransaction;

$transaction = TubaPayTransaction::findByExternalRef('order-uuid');

TubaPayTransaction::pending()->get();
TubaPayTransaction::successful()->get();
TubaPayTransaction::failed()->get();
TubaPayTransaction::forCustomer('[email protected]')->get();

if ($transaction->isSuccessful()) {
    // ...
}

$transaction = $this->checkoutService->createTransaction(...);

TubaPayTransaction::query()
    ->where('external_ref', $order->uuid)
    ->update(['currency' => $order->currency]);

use Core45\LaravelTubaPay\Services\TubaPayStatusMapper;

$localStatus = app(TubaPayStatusMapper::class)->map($event->getStatus());

$this->app->instance(\Core45\TubaPay\TubaPay::class, $fakeTubaPay);
bash
php artisan vendor:publish --tag=tubapay-config
php artisan vendor:publish --tag=tubapay-migrations
php artisan migrate
bash
php artisan vendor:publish --tag=tubapay-views
blade
@props([
    'options',
    'name' => 'tubapay_installments',
    'wireModel' => null,
])

<div {{ $attributes->merge(['class' => 'tubapay-installment-selector']) }}>
    <p>{{ $options->installmentTitle() }}</p>

    @foreach ($options->installments as $option)
        <label for="{{ $name }}_{{ $option->installments }}">
            <input
                type="radio"
                name="{{ $name }}"
                id="{{ $name }}_{{ $option->installments }}"
                value="{{ $option->installments }}"
                @if ($wireModel) wire:model.live="{{ $wireModel }}" @endif
                @checked($option->selected)
            >
            <span>{{ $option->label }}</span>
        </label>
    @endforeach
</div>
bash
php artisan vendor:publish --tag=tubapay-lang