PHP code example of sebdesign / laravel-viva-payments

1. Go to this page and download the library: Download sebdesign/laravel-viva-payments 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/ */

    

sebdesign / laravel-viva-payments example snippets


'viva' => [
    'api_key' => env('VIVA_API_KEY'),
    'merchant_id' => env('VIVA_MERCHANT_ID'),
    'environment' => env('VIVA_ENVIRONMENT', 'production'),
    'client_id' => env('VIVA_CLIENT_ID'),
    'client_secret' => env('VIVA_CLIENT_SECRET'),
    'isv_partner_id' => env('VIVA_ISV_PARTNER_ID'),
    'isv_partner_api_key' => env('VIVA_ISV_PARTNER_API_KEY'),
],

use Sebdesign\VivaPayments\Facades\Viva;

$orderCode = Viva::orders()->create(
    order: new CreatePaymentOrder(amount: 1000),
);

use Sebdesign\VivaPayments\Facades\Viva;

$redirectUrl = Viva::orders()->redirectUrl(
    ref: $orderCode,
    color: '0000ff',
    paymentMethod: 23,
);

return redirect()->away(path: $redirectUrl);

use Sebdesign\VivaPayments\Facades\Viva;

$response = Viva::transactions()->retrieve(transactionId: request('t'));



namespace App\Http\Controllers;

use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Sebdesign\VivaPayments\Enums\TransactionStatus;
use Sebdesign\VivaPayments\Facades\Viva;
use Sebdesign\VivaPayments\Requests\CreatePaymentOrder;
use Sebdesign\VivaPayments\Requests\Customer;
use Sebdesign\VivaPayments\VivaException;

class CheckoutController extends Controller
{
    /**
     * Create a payment order and redirect to the checkout page.
     */
    public function checkout(): RedirectResponse
    {
        try {
            $orderCode = Viva::orders()->create(new CreatePaymentOrder(
                amount: 1000,
                customerTrns: 'Short description of purchased items/services to display to your customer',
                customer: new Customer(
                    email: '[email protected]',
                    fullName: 'John Doe',
                    countryCode: 'GB',
                    requestLang: 'en-GB',
                ),
            ));
        } catch (VivaException $e) {
            report($e);

            return back()->withErrors($e->getMessage());
        }

        $redirectUrl = Viva::orders()->redirectUrl(
            ref: $orderCode,
            color: '0000ff',
            paymentMethod: 23,
        );

        return redirect()->away($redirectUrl);
    }

    /**
     * Redirect from the checkout page and get the order details from the API.
     */
    public function confirm(Request $request): RedirectResponse
    {
        try {
            $transaction = Viva::transactions()->retrieve($request->input('t'));
        } catch (VivaException $e) {
            report($e);

            return back()->withErrors($e->getMessage());
        }

        $status = match ($transaction->statusId) {
            case TransactionStatus::PaymentPending: 'The order is pending.',
            case TransactionStatus::PaymentSuccessful: 'The order is paid.',
            case TransactionStatus::Error: 'The order was not paid.',
        }

        return view('order/success', compact('status'));
    }
}

Route::get('viva/webhooks', [WebhookController::class, 'verify']);
Route::post('viva/webhooks', [WebhookController::class, 'handle']);



namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;

class VerifyCsrfToken extends Middleware
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array<int, string>
     */
    protected $except = ['viva/webhooks'];
}

use Sebdesign\VivaPayments\Enums\WebhookEventType;
use Sebdesign\VivaPayments\Events\WebhookEvent;

class EventServiceProvider
{
    protected $listen = [
        WebhookEvent::class => [WebhookEventListener::class],
    ];
}

class WebhookEventListener
{
    public function handle(WebhookEvent $event): void
    {
        match ($event->EventTypeId) {
            WebhookEventType::TransactionPaymentCreated => ...,
            WebhookEventType::TransactionFailed => ...,
            WebhookEventType::TransactionReversalCreated => ...,
            default => ...,
        };
    }
}

use Sebdesign\VivaPayments\Enums\WebhookEventType;
use Sebdesign\VivaPayments\Events\TransactionFailed;
use Sebdesign\VivaPayments\Events\TransactionPaymentCreated;

class EventServiceProvider
{
    protected $listen = [
        TransactionPaymentCreated::class => [
            ConfirmOrder::class,
        ],
        TransactionFailed::class => [
            CancelOrder::class,
        ],
    ];
}

class ConfirmOrder
{
    public function handle(TransactionPaymentCreated $event): void
    {
        //
    }
}

class CancelOrder
{
    public function handle(TransactionFailed $event): void
    {
        //
    }
}

use Sebdesign\VivaPayments\Facades\Viva;
use Sebdesign\VivaPayments\Requests\CreatePaymentOrder;
use Sebdesign\VivaPayments\Requests\Customer;

$orderCode = Viva::orders()->create(
    order: new CreatePaymentOrder(
        amount: 1000,
        customerTrns: 'Short description of purchased items/services to display to your customer',
        customer: new Customer(
            email: '[email protected]',
            fullName: 'John Doe',
            phone: '+30999999999',
            countryCode: 'GB',
            requestLang: 'en-GB',
        ),
        paymentTimeOut: 300,
        preauth: false,
        allowRecurring: false,
        maxInstallments: 12,
        paymentNotification: true,
        tipAmount: 100,
        disableExactAmount: false,
        disableCash: true,
        disableWallet: true,
        sourceCode: '1234',
        merchantTrns: 'Short description of items/services purchased by customer',
        tags: [
            'tags for grouping and filtering the transactions',
            'this tag can be searched on VivaWallet sales dashboard',
            'Sample tag 1',
            'Sample tag 2',
            'Another string',
        ],
        cardTokens: ['ct_5d0a4e3a7e04469f82da228ca98fd661'],
    ),
    guzzleOptions: [],
);

use Sebdesign\VivaPayments\Facades\Viva;

$url = Viva::orders()->redirectUrl(
    ref: $orderCode,
    color: '0000ff',
    paymentMethod: 23,
);

use Sebdesign\VivaPayments\Facades\Viva;

$transaction = Viva::transactions()->retrieve(
    transactionId: 'c90d4902-6245-449f-b2b0-51d99cd09cfe',
    guzzleOptions: [],
);

use Sebdesign\VivaPayments\Facades\Viva;
use Sebdesign\VivaPayments\Requests\CreateRecurringTransaction;

$response = Viva::transactions()->createRecurring(
    transactionId: '252b950e-27f2-4300-ada1-4dedd7c17904',
    transaction: new CreateRecurringTransaction(
        amount: 100,
        installments: 1,
        customerTrns: 'A description of products / services that is displayed to the customer',
        merchantTrns: 'Your merchant reference',
        sourceCode: '6054',
        tipAmount: 0,
    ),
    guzzleOptions: [],
);

use Sebdesign\VivaPayments\Facades\Viva;

Viva::withOAuthCredentials(
    clientId: 'client_id',
    clientSecret: 'client_secret',
);

use Sebdesign\VivaPayments\Facades\Viva;

// Using `client_id` and `client_secret` from `config/services.php`:
$token = Viva::oauth()->requestToken();

// Using custom client credentials
$token = Viva::oauth()->requestToken(
    clientId: 'client_id',
    clientSecret: 'client_secret',
    guzzleOptions: [],
);

use Sebdesign\VivaPayments\Facades\Viva;

Viva::withToken(token: 'eyJhbGciOiJSUzI1...');

use Sebdesign\VivaPayments\Facades\Viva;

$cardToken = Viva::cards()->createToken(
    transactionId: '6cffe5bf-909c-4d69-b6dc-2bef1a6202f7',
    guzzleOptions: [],
);

use Sebdesign\VivaPayments\Facades\Viva;

$key = Viva::webhooks()->getVerificationKey(
    guzzleOptions: [],
);

use Sebdesign\VivaPayments\Facades\Viva;
use Sebdesign\VivaPayments\Requests\CreatePaymentOrder;
use Sebdesign\VivaPayments\Requests\Customer;

$orderCode = Viva::isv()->orders()->create(
    order: new CreatePaymentOrder(
        amount: 1000,
        customerTrns: 'Short description of purchased items/services to display to your customer',
        customer: new Customer(
            email: '[email protected]',
            fullName: 'John Doe',
            phone: '+30999999999',
            countryCode: 'GB',
            requestLang: 'en-GB',
        ),
        paymentTimeOut: 300,
        preauth: false,
        allowRecurring: false,
        maxInstallments: 12,
        paymentNotification: true,
        tipAmount: 100,
        disableExactAmount: false,
        disableCash: true,
        disableWallet: true,
        sourceCode: '1234',
        merchantTrns: 'Short description of items/services purchased by customer',
        tags: [
            'tags for grouping and filtering the transactions',
            'this tag can be searched on VivaWallet sales dashboard',
            'Sample tag 1',
            'Sample tag 2',
            'Another string',
        ],
        isvAmount: 10,
        resellerSourceCode: '2345',
    ),
    guzzleOptions: [],
);

use Sebdesign\VivaPayments\Facades\Viva;

$transaction = Viva::isv()->transactions()->retrieve(
    transactionId: 'c90d4902-6245-449f-b2b0-51d99cd09cfe',
    guzzleOptions: [],
);

use Sebdesign\VivaPayments\Facades\Viva;
use Sebdesign\VivaPayments\Requests\CreateRecurringTransaction;

Viva::withBasicAuthCredentials(
    config('services.viva.isv_partner_id').':'.config('services.viva.merchant_id'),
    config('services.viva.isv_partner_api_key'),
);

$transaction = Viva::isv()->transactions()->createRecurring(
    transactionId: 'c90d4902-6245-449f-b2b0-51d99cd09cfe',
    transaction: new CreateRecurringTransaction(
        amount: 100,
        isvAmount: 1,
        customerTrns: 'A description of products / services that is displayed to the customer',
        merchantTrns: 'Your merchant reference',
        sourceCode: '4929333',
        resellerSourceCode: '1565',
    ),
    guzzleOptions: [],
);