PHP code example of aghfatehi / laravel-tap

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

    

aghfatehi / laravel-tap example snippets


// config/app.php
'providers' => [
    Aghfatehi\Tap\TapServiceProvider::class,
],

'aliases' => [
    'Tap' => Aghfatehi\Tap\Facades\Tap::class,
],

// In your view (Blade)
<form action="{{ route('tap.pay') }}" method="POST">
    @csrf
    <input type="hidden" name="amount" value="500.00">
    <input type="hidden" name="description" value="Order #1234">
    <input type="hidden" name="order_id" value="ORD-1234">
    <input type="hidden" name="first_name" value="{{ auth()->user()->name ?? 'Customer' }}">
    <button type="submit">Pay with Tap</button>
</form>



namespace App\Http\Controllers;

use Aghfatehi\Tap\Facades\Tap;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class CheckoutController extends Controller
{
    public function charge(Request $request)
    {
        $amount = 500.00;
        $currency = config('tap.currency', 'SAR');

        // ─── Build the charge payload ──────────────────
        $payload = [
            'amount' => $amount,
            'currency' => $currency,
            'customer_initiated' => true,
            'threeDSecure' => true,
            'description' => 'Order #ORD-1234',
            'customer' => [
                'first_name' => $request->user()?->name ?? 'Ahmed',
                'last_name' => 'Ali',
                'email' => $request->user()?->email ?? '[email protected]',
                'phone' => [
                    'country_code' => '966',
                    'number' => '500000001',
                ],
            ],
            'merchant' => [
                'id' => config('tap.merchant_id'),
            ],
            'source' => [
                'id' => 'src_all',  // Show all available payment methods
            ],
            'redirect' => [
                'url' => route('tap.callback'),
            ],
            'post' => [
                'url' => route('tap.webhook'),
            ],
            'reference' => [
                'order' => 'ORD-1234',
            ],
            'metadata' => [
                'udf1' => 'custom_data_1',
                'udf2' => 'custom_data_2',
            ],
        ];

        try {
            $response = Tap::createCharge($payload);

            if (isset($response['id'])) {
                $checkoutUrl = $response['transaction']['url'] ?? null;

                if ($checkoutUrl) {
                    // Save transaction ID for verification
                    session(['tap_charge_id' => $response['id']]);

                    // Redirect to Tap hosted checkout page
                    return redirect()->away($checkoutUrl);
                }

                // Some payment methods are synchronous (e.g., saved cards)
                // — they return status directly
                return response()->json($response);
            }

            return back()->withErrors(['error' => 'Failed to initiate payment']);
        } catch (\Aghfatehi\Tap\Exceptions\TapException $e) {
            Log::error('Tap Charge Error: ' . $e->getMessage());
            return back()->withErrors(['error' => $e->getMessage()]);
        }
    }

    public function callback(Request $request)
    {
        $tapId = $request->input('tap_id') ?? session('tap_charge_id');

        if (!$tapId) {
            return redirect('/')->withErrors(['error' => 'Payment verification failed']);
        }

        try {
            $response = Tap::getCharge($tapId);
            $status = $response['status'] ?? '';

            if (in_array($status, ['CAPTURED', 'AUTHORIZED'], true)) {
                return redirect('/')->with('success', 'Payment completed successfully');
            }

            return redirect('/')->withErrors(['error' => 'Payment was not completed']);
        } catch (\Throwable $e) {
            return redirect('/')->withErrors(['error' => $e->getMessage()]);
        }
    }
}

// Step 1: Authorize (hold payment)
$authorize = Tap::createAuthorize([
    'amount' => 500.00,
    'currency' => 'SAR',
    'customer_initiated' => true,
    'customer' => [
        'first_name' => 'Ahmed',
        'last_name' => 'Ali',
        'email' => '[email protected]',
        'phone' => ['country_code' => '966', 'number' => '500000001'],
    ],
    'merchant' => ['id' => config('tap.merchant_id')],
    'source' => ['id' => 'src_all'],
    'redirect' => ['url' => route('tap.callback')],
    'post' => ['url' => route('tap.webhook')],
]);

$authorizeId = $authorize['id']; // auth_xxxxx

// After customer completes 3DS on hosted page...

// Step 2: Capture (collect authorized amount)
$captured = Tap::captureCharge($authorizeId, [
    'amount' => 500.00, // optional: can be partial amount
]);

if ($captured['status'] === 'CAPTURED') {
    // Payment collected successfully
}

// Void an authorized (not yet captured) charge
$voided = Tap::voidCharge('auth_xxxxx');
// $voided['status'] === 'VOID'

// Refund a captured charge (full or partial)
$refunded = Tap::refundCharge('chg_xxxxx', [
    'amount' => 100.00,
    'reason' => 'Customer requested refund',
]);

use Aghfatehi\Tap\Facades\Tap;

// Create a charge (hosted checkout)
$charge = Tap::createCharge([...]);

// Retrieve a charge by ID
$charge = Tap::getCharge('chg_xxxxx');

// List charges with filters
$charges = Tap::listCharges([
    'status' => 'CAPTURED',
    'limit' => 20,
    'period' => ['date_from' => '2026-01-01', 'date_to' => '2026-12-31'],
]);

// Update charge metadata
$updated = Tap::updateCharge('chg_xxxxx', [
    'description' => 'Updated description',
    'metadata' => ['udf1' => 'new_value'],
]);

// Create authorization
$authorize = Tap::createAuthorize([...]);

// Get authorization details
$auth = Tap::getAuthorize('auth_xxxxx');

// Capture authorized charge
$captured = Tap::captureCharge('auth_xxxxx', ['amount' => 500.00]);

// Void authorized charge
$voided = Tap::voidCharge('auth_xxxxx');

// Refund captured charge
$refunded = Tap::refundCharge('chg_xxxxx', [
    'amount' => 100.00,
    'reason' => 'Customer request',
]);

// Create a token (from card data or saved card)
$token = Tap::createToken([
    'card' => [
        'number' => 'tok_xxxxx', // from frontend SDK
    ],
]);

// Create a customer
$customer = Tap::createCustomer([
    'first_name' => 'Ahmed',
    'last_name' => 'Ali',
    'email' => '[email protected]',
    'phone' => ['country_code' => '966', 'number' => '500000001'],
]);

// List customers
$customers = Tap::listCustomers(['limit' => 10]);

// List cards for a customer
$cards = Tap::listCards('cus_xxxxx');

// Delete a saved card
Tap::deleteCard('card_xxxxx');

// This runs inside WebhookController automatically:
$validator = app(\Aghfatehi\Tap\Services\WebhookValidator::class);

$isValid = $validator->verify(
    payload: $request->all(),
    receivedHash: $request->header('hashstring', ''),
    secretKey: config('tap.secret_key'),
    type: 'charge'
);

// In AppServiceProvider::boot()
\Illuminate\Support\Facades\Event::listen(
    \Aghfatehi\Tap\Events\PaymentSucceeded::class,
    function ($event) {
        // Update your order status
        \App\Models\Order::where('reference_id', $event->payload['reference']['order'] ?? '')
            ->update(['status' => 'paid']);
    }
);

\Illuminate\Support\Facades\Event::listen(
    \Aghfatehi\Tap\Events\PaymentFailed::class,
    function ($event) {
        \Log::error('Payment failed', [
            'tap_id' => $event->tapId,
            'error' => $event->errorMessage,
        ]);
    }
);

// config/tap.php
'routes' => [
    'prefix' => 'payment/tap',  // Custom prefix
    'middleware' => ['web', 'auth'],  // Custom middleware
],

'source' => ['id' => 'tok_xxxxx']
bash
php artisan vendor:publish --tag=tap-config
bash
php artisan vendor:publish --tag=tap-migrations
php artisan migrate
bash
composer vendor:publish --tag=tap-config
php artisan vendor:publish --tag=tap-migrations
php artisan migrate