PHP code example of oluokunkabiru / api-call-logger

1. Go to this page and download the library: Download oluokunkabiru/api-call-logger 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/ */

    

oluokunkabiru / api-call-logger example snippets


use Illuminate\Support\Facades\Http;

$response = Http::withApiLogging('vtpass', 'buy-airtime')
    ->withHeaders(['api-key' => $key, 'secret-key' => $secret])
    ->post("{$baseUrl}/pay", $payload);

Http::withApiLogging('gobeller', 'create-wallet', [
    'loggable' => $transaction,                              // link the log to a local model
    'tenant'   => $institution->code,                        // override the tenant for this call
    'meta'     => ['wallet_type' => 'savings'],              // anything extra
    'success'  => fn ($response) => (bool) $response->json('status'), // providers that return 200 + status:false
])->post(...);

// config/api-call-logger.php
'capture' => [
    'http_client' => env('API_CALL_LOGGER_CAPTURE_HTTP_CLIENT', false),
    'only_hosts' => [],                 // e.g. ['*.vtpass.com', 'api.paystack.co']
    'except_hosts' => ['*.internal'],
],
'providers' => [
    'paystack' => ['hosts' => ['api.paystack.co']],
    'vtpass'   => ['hosts' => ['vtpass.com', 'sandbox.vtpass.com']],
],

// The provider comes from the segment after "webhooks": /api/webhooks/flutterwave → flutterwave
Route::prefix('webhooks')->middleware('api-call-logger.inbound')->group(function () {
    Route::post('flutterwave', FlutterwaveWebhookController::class);
    Route::post('fyatu', FyatuWebhookController::class);
});

// Or give the provider (and context) explicitly
Route::post('paystack/callback', ...)->middleware('api-call-logger.inbound:paystack,charge-success');

use Oluokunkabiru\ApiCallLogger\Facades\ApiCallLogger;

ApiCallLogger::log(
    provider: 'gobeller',
    method: 'POST',
    url: $this->baseUrl . $endpoint,
    request: $payload,                 // array or raw string (JSON / form decoded automatically)
    response: $responseBody,
    status: $statusCode,               // null for connection failures
    success: $success,                 // defaults to 2xx
    durationMs: $durationMs,
    context: 'self-service',
    requestHeaders: $headers,
    responseHeaders: $responseHeaders,
    loggable: $transaction,
);

// Or let the package time it for you:
$result = ApiCallLogger::measure('bank-soap', 'POST', $wsdl, fn () => $client->Transfer($args), request: $args);

ApiCallLogger::withTenant($request->header('X-Institution-Code'));
ApiCallLogger::withMeta(['channel' => 'mobile']);

// Or resolve them lazily, in a service provider:
ApiCallLogger::resolveTenantUsing(fn () => request()->attributes->get('institution')?->code);
ApiCallLogger::resolveUserUsing(fn () => auth('admin')->id());   // default: auth()->id()

'redaction' => [
    'enabled' => env('API_CALL_LOGGER_REDACT_SENSITIVE', true), // false = keep PII for debugging
    'replacement' => '[REDACTED]',
    'always' => ['password', 'secret_key', 'authorization', 'token', 'pin', 'cvv', 'card_number', ...],
    'sensitive' => ['bvn', 'nin', 'document_id_no', 'image_encoding', ...],
    'max_string_length' => 500,  // longer strings become "<truncated N bytes>"
    'max_depth' => 10,
],

'patterns' => [
    'card_numbers' => true,          // Luhn-valid 13–19 digits → 411111******1111 (PCI first 6 / last 4)
    'jwt' => true,                   // → [REDACTED:jwt]
    'auth_schemes' => true,          // "Bearer abc…" / "Basic abc…" inside any string
    'emails' => false,               // → jo***@gmail.com
    'phones' => false,               // → +*********4567
    'url_digits_min_length' => 10,   // /kyc/bvn/22222222222 → /kyc/bvn/*******2222 (null = off)
    'custom' => ['/sk_(live|test)_[A-Za-z0-9]+/' => '[REDACTED:paystack-key]'],
],

ApiCallLogger::forget(userId: '42');
ApiCallLogger::forget(tenant: 'INST-01');
ApiCallLogger::forget(loggable: $customer);

$decision = ApiCallLogger::retryDecision($log);   // ->blockers, ->confirmations, ->allowed($force)

$newLog = ApiCallLogger::retry($log);              // safe call: replayed
$newLog = ApiCallLogger::retry($log, force: true); // risky call: you accept the confirmations

'retry' => [
    'enabled' => true,
    'safe_methods' => ['GET', 'HEAD', 'OPTIONS'],   // retried without confirmation
    'unsafe_methods' => 'confirm',                 // allow | confirm | deny for everything else
    '> 30,                          // block a parallel retry of the same record
],

'providers' => [
    'vtpass' => [
        'hosts' => ['sandbox.vtpass.com'],
        'retry_headers' => ['api-key' => env('VTPASS_API_KEY'), 'secret-key' => env('VTPASS_SECRET_KEY')],
    ],
],

// or at runtime (e.g. credentials stored in a settings table)
ApiCallLogger::retryHeadersUsing('masspay', fn ($log) => [
    'Authorization' => 'Bearer ' . Setting::resolve('masspay.api_key'),
]);

// App\Providers\AppServiceProvider::boot()
Gate::define('viewApiCallLogs', fn ($user) => $user->hasRole('super_admin'));
Gate::define('retryApiCallLogs', fn ($user, $log = null) => $user->hasRole('super_admin'));

use Oluokunkabiru\ApiCallLogger\Models\ApiCallLog;

class ApiCallLogResource extends Resource
{
    protected static ?string $model = ApiCallLog::class;
    // columns: provider, method, path, context, status_code, success, duration_ms, created_at
}

// Retry header action: show the risks, retry with force once confirmed
Action::make('retry')
    ->visible(fn (ApiCallLog $record) => ! ApiCallLogger::retryDecision($record)->blocked())
    ->

use Oluokunkabiru\ApiCallLogger\Models\ApiCallLog;

ApiCallLog::provider('vtpass')->failed()->where('created_at', '>=', now()->subHour())->count();
ApiCallLog::outbound()->slowerThan(4000)->latest()->get();
ApiCallLog::where('correlation_id', $id)->get();
$transactionLogs = ApiCallLog::where('loggable_type', $tx->getMorphClass())->where('loggable_id', $tx->id)->get();

Event::listen(ApiCallLogged::class, function (ApiCallLogged $event) {
    if (! $event->log->success && $event->log->provider === 'masspay') {
        Notification::route('slack', config('services.slack.ops'))->notify(new ProviderFailing($event->log));
    }
});

// routes/console.php
Schedule::command('api-call-logger:prune')->daily();   // or: Schedule::command('model:prune')->daily();
bash
php artisan api-call-logger:forget --user=42
php artisan api-call-logger:forget --tenant=INST-01 --force