Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Najnakup Laravel Package

birko/najnakup

Laravel/PHP package for integrating Najnakup “overenie objednavky” (order verification). Helps verify/confirm customer orders through the Najnakup service, suitable for shops that need post-order validation and trust checks.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to Begin

  1. Install the Package

    composer require birko/najnakup
    

    Verify compatibility with your Laravel version (8.x or 9.x recommended).

  2. Publish Configuration

    php artisan vendor:publish --provider="Birko\Najnakup\NajnakupServiceProvider" --tag="config"
    

    Update .env with Najnakup credentials:

    NAJNAKUP_API_KEY=your_api_key
    NAJNAKUP_API_SECRET=your_secret
    NAJNAKUP_BASE_URL=https://api.najnakup.sk/v1
    
  3. First Use Case: Verify Order Status

    use Birko\Najnakup\Facades\Najnakup;
    
    $orderId = 'ORD12345';
    $verification = Najnakup::verify($orderId);
    
    if ($verification->success()) {
        // Order is valid; proceed with business logic
        $this->processValidOrder($verification->data());
    } else {
        // Handle failure (e.g., log, retry, or notify user)
        $this->handleVerificationError($verification->error());
    }
    
  4. Key Files to Inspect

    • config/najnakup.php: API endpoints, timeouts, and defaults.
    • src/Facades/Najnakup.php: Main facade for quick integration.
    • src/Exceptions/: Custom exceptions for error handling.

Implementation Patterns

Core Workflows

1. Webhook Integration

Handle Najnakup’s real-time notifications (e.g., order updates, refunds):

use Birko\Najnakup\Facades\Najnakup;
use Illuminate\Http\Request;

public function najnakupWebhook(Request $request)
{
    $payload = $request->json()->all();
    $validation = Najnakup::validateWebhook($payload);

    if ($validation->isValid()) {
        // Process the webhook (e.g., update order in DB)
        $this->syncOrderWithNajnakup($validation->data());
    }

    return response()->json(['status' => 'processed']);
}

2. Batch Processing

Verify multiple orders efficiently (e.g., during nightly reconciliation):

$orderIds = ['ORD1', 'ORD2', 'ORD3'];
$results = Najnakup::verifyBatch($orderIds);

foreach ($results as $result) {
    if ($result->success()) {
        $this->updateOrderStatus($result->data());
    }
}

3. Queue-Based Verification

Offload verification to a background job to avoid blocking requests:

use Birko\Najnakup\Jobs\VerifyOrderJob;

// Dispatch job
VerifyOrderJob::dispatch($orderId);

// Job implementation
public function handle()
{
    $response = Najnakup::verify($this->orderId);
    // Store result or trigger follow-up actions
}

4. Custom Response Transformation

Extend responses to include additional metadata or formatting:

Najnakup::extend(function ($client) {
    $client->onResponse(function ($response) {
        $response->setCustomField('processed_at', now());
        return $response;
    });
});

Laravel-Specific Patterns

Service Provider Binding

Bind the Najnakup client to an interface for better testability:

// app/Providers/AppServiceProvider.php
public function register()
{
    $this->app->bind(
        \Birko\Najnakup\Contracts\NajnakupClient::class,
        \Birko\Najnakup\NajnakupClient::class
    );
}

Middleware for API Calls

Add middleware to log or transform requests/responses:

// app/Http/Middleware/LogNajnakupRequests.php
public function handle($request, Closure $next)
{
    $response = $next($request);
    \Log::info('Najnakup API Response', $response->json());
    return $response;
}

Event Listeners

Trigger Laravel events after verification (e.g., OrderVerified):

// app/Listeners/HandleOrderVerification.php
public function handle($event)
{
    if ($event->isVerified()) {
        event(new OrderVerified($event->order));
    }
}

Artisan Commands

Create CLI tools for manual verification or debugging:

php artisan najnakup:verify ORD123
// app/Console/Commands/VerifyNajnakupOrder.php
protected $signature = 'najnakup:verify {orderId}';
public function handle()
{
    $result = Najnakup::verify($this->argument('orderId'));
    $this->line($result->success() ? 'Verified!' : 'Failed: ' . $result->error());
}

Gotchas and Tips

Common Pitfalls

1. API Credential Leaks

  • Risk: Hardcoding API keys in config or logs.
  • Fix: Use Laravel’s .env and validate credentials on startup:
    if (empty(config('najnakup.api_key'))) {
        throw new \RuntimeException('Najnakup API key not configured.');
    }
    

2. Rate Limiting

  • Risk: Hitting Najnakup’s API limits during batch operations.
  • Fix: Implement exponential backoff or use Laravel queues:
    use Illuminate\Support\Facades\Queue;
    
    Queue::later(now()->addSeconds(5), function () {
        Najnakup::verify($orderId);
    });
    

3. Webhook Signature Validation

  • Risk: Accepting malicious webhook payloads.
  • Fix: Always validate signatures:
    $validation = Najnakup::validateWebhook($payload, $request->header('X-Signature'));
    if (!$validation->isValid()) {
        abort(403, 'Invalid webhook signature');
    }
    

4. Timeouts and Retries

  • Risk: API timeouts or transient failures.
  • Fix: Configure retries in the client:
    Najnakup::setRetryOptions([
        'max_attempts' => 3,
        'delay' => 1000, // ms
    ]);
    

5. Database Schema Conflicts

  • Risk: Package migrations clashing with existing tables.
  • Fix: Review najnakup.php config for table names and prefix them:
    'database' => [
        'prefix' => 'najnakup_',
    ],
    

Debugging Tips

1. Enable Verbose Logging

Najnakup::setLogLevel(\Monolog\Logger::DEBUG);

Check logs at storage/logs/laravel.log.

2. Mock the Client for Testing

// tests/TestCase.php
protected function mockNajnakupClient()
{
    $this->app->instance(
        \Birko\Najnakup\Contracts\NajnakupClient::class,
        Mockery::mock(\Birko\Najnakup\Contracts\NajnakupClient::class)
    );
}

3. Inspect Raw API Responses

Use a middleware to log raw responses:

public function handle($request, Closure $next)
{
    $response = $next($request);
    \Log::debug('Najnakup Raw Response', [
        'status' => $response->status(),
        'body' => $response->getBody(),
    ]);
    return $response;
}

Configuration Quirks

1. Base URL Overrides

  • Useful for staging environments:
    NAJNAKUP_BASE_URL=https://staging.najnakup.sk/v1
    

2. Custom Endpoints

  • Extend the client to support non-standard endpoints:
    Najnakup::extendEndpoint('custom', 'orders/{id}/custom-action');
    

3. Timeout Settings

  • Adjust for slow connections:
    Najnakup::setTimeout(30); // seconds
    

Extension Points

1. Custom Response Classes

Extend the default response handler:

use Birko\Najnakup\Responses\NajnakupResponse;

class CustomNajnakupResponse extends NajnakupResponse
{
    public function getFormattedData()
    {
        return $this->data + ['custom_field' => 'value'];
    }
}

// Register in service provider
Najnakup::setResponseClass(CustomNajnakupResponse::class);

2. Plugin System

Add hooks for pre/post API calls:

Najnakup::onBeforeRequest(function ($request) {
    $request->headers->set('X-Custom-Header', 'value');
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle