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

Core Laravel Package

nikolag/core

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup for First Use Case

  1. Install the Package

    composer require nikolag/core
    

    Ensure your composer.json includes "laravel/framework": "^5.5|^6.0|^7.0|^8.0|^9.0|^10.0" as a dependency.

  2. Publish Configuration Publish the default config to config/nikolag.php:

    php artisan vendor:publish --provider="Nikolag\Core\Providers\NikolagServiceProvider" --tag="config"
    
  3. Define a Basic Gateway Integration Create a new service class (e.g., app/Services/Payment/Gateway/StripeGateway.php) extending Nikolag\Core\Contracts\GatewayContract:

    namespace App\Services\Payment\Gateway;
    
    use Nikolag\Core\Contracts\GatewayContract;
    use Nikolag\Core\Exceptions\GatewayException;
    
    class StripeGateway implements GatewayContract
    {
        public function processPayment(array $data): array
        {
            // Implement Stripe-specific logic
            return ['success' => true, 'transaction_id' => 'stripe_123'];
        }
    }
    
  4. Register the Gateway Bind the gateway in a service provider (e.g., app/Providers/AppServiceProvider.php):

    public function register()
    {
        $this->app->bind(
            \Nikolag\Core\Contracts\GatewayContract::class,
            \App\Services\Payment\Gateway\StripeGateway::class
        );
    }
    
  5. Use the Gateway Inject GatewayContract into a controller or service and call processPayment():

    use Nikolag\Core\Contracts\GatewayContract;
    
    class PaymentController extends Controller
    {
        public function __construct(private GatewayContract $gateway) {}
    
        public function charge(Request $request)
        {
            $result = $this->gateway->processPayment($request->all());
            return response()->json($result);
        }
    }
    

Implementation Patterns

Core Workflows

  1. Gateway Abstraction

    • Implement GatewayContract for all payment gateways (e.g., Stripe, PayPal, Mollie).
    • Use dependency injection to swap gateways dynamically via config:
      // config/nikolag.php
      'default' => env('NIKOLAG_GATEWAY', 'stripe'),
      'connections' => [
          'stripe' => \App\Services\Payment\Gateway\StripeGateway::class,
          'paypal' => \App\Services\Payment\Gateway\PayPalGateway::class,
      ],
      
    • Resolve the gateway in services:
      $gateway = app(\Nikolag\Core\Contracts\GatewayContract::class);
      // OR use the facade:
      $result = \Nikolag\Core\Facades\Nikolag::gateway()->processPayment($data);
      
  2. Transaction Handling

    • Extend Nikolag\Core\Models\Transaction for gateway-specific fields:
      namespace App\Models;
      
      use Nikolag\Core\Models\Transaction as BaseTransaction;
      
      class Transaction extends BaseTransaction
      {
          protected $casts = [
              'stripe_id' => 'string',
              'paypal_status' => 'string',
          ];
      }
      
    • Use Nikolag\Core\Services\TransactionService to log transactions:
      $transaction = app(\Nikolag\Core\Services\TransactionService::class)
          ->create(['amount' => 100, 'gateway' => 'stripe', 'metadata' => []]);
      
  3. Webhook Processing

    • Implement Nikolag\Core\Contracts\WebhookHandlerContract for gateway-specific webhooks:
      namespace App\Services\Payment\Handlers;
      
      use Nikolag\Core\Contracts\WebhookHandlerContract;
      
      class StripeWebhookHandler implements WebhookHandlerContract
      {
          public function handle(array $payload): void
          {
              // Parse Stripe events (e.g., charge.succeeded)
          }
      }
      
    • Register handlers in config/nikolag.php:
      'webhooks' => [
          'stripe' => \App\Services\Payment\Handlers\StripeWebhookHandler::class,
      ],
      
  4. Refunds and Captures

    • Extend Nikolag\Core\Contracts\GatewayContract methods:
      public function refund(string $transactionId, float $amount): array;
      public function capture(string $transactionId, float $amount): array;
      
    • Use the facade for consistency:
      $refund = \Nikolag\Core\Facades\Nikolag::gateway()->refund($transactionId, 50);
      

Integration Tips

  • Laravel Cashier Compatibility: Use Nikolag\Core\Services\CashierBridge to extend Cashier with custom gateways:
    $user->newSubscription('premium', 'custom-plan')
         ->gateway('stripe')
         ->create($token);
    
  • Testing: Mock GatewayContract in PHPUnit:
    $this->mock(\Nikolag\Core\Contracts\GatewayContract::class, function ($mock) {
        $mock->shouldReceive('processPayment')
             ->andReturn(['success' => true]);
    });
    
  • Logging: Leverage Nikolag\Core\Logging\PaymentLogger for audit trails:
    app(\Nikolag\Core\Logging\PaymentLogger::class)->log('payment.attempt', $data);
    

Gotchas and Tips

Pitfalls

  1. Configuration Overrides

    • The package expects nikolag.php in src/config for published configs. If using a custom path, override the provider’s getConfigPath():
      // In a custom service provider
      $this->mergeConfigFrom(__DIR__.'/../config/nikolag.php', 'nikolag');
      
  2. Facade vs. Dependency Injection

    • Avoid mixing facades and DI in the same class to prevent tight coupling. Prefer DI for testability:
      // Anti-pattern: Mixing facades and DI
      class PaymentService {
          public function __construct(GatewayContract $gateway) {
              $this->gateway = $gateway;
              $this->fallback = \Nikolag\Core\Facades\Nikolag::gateway(); // Redundant!
          }
      }
      
  3. Webhook Idempotency

    • Gateways like Stripe may retry webhooks. Use Nikolag\Core\Services\IdempotencyService to deduplicate:
      $idempotency = app(\Nikolag\Core\Services\IdempotencyService::class);
      if (!$idempotency->isProcessed($payload['id'])) {
          $handler->handle($payload);
          $idempotency->markProcessed($payload['id']);
      }
      
  4. Transaction Model Binding

    • If extending Transaction, ensure the model is bound in AppServiceProvider:
      $this->app->bind(
          \Nikolag\Core\Models\Transaction::class,
          \App\Models\Transaction::class
      );
      
  5. Currency and Amount Handling

    • Always validate currency codes (ISO 4217) and amounts (e.g., bcdiv($amount, '100', 2) for cents). The package does not enforce this by default.

Debugging

  • Gateway-Specific Errors: Wrap gateway calls in try-catch blocks to log exceptions:
    try {
        $result = $gateway->processPayment($data);
    } catch (\Nikolag\Core\Exceptions\GatewayException $e) {
        \Log::error('Payment failed', ['gateway' => 'stripe', 'error' => $e->getMessage()]);
        throw new \RuntimeException('Payment processing error', 0, $e);
    }
    
  • Webhook Debugging: Use Nikolag\Core\Debugging\WebhookValidator to validate payloads:
    $validator = new \Nikolag\Core\Debugging\WebhookValidator($payload, 'stripe');
    if (!$validator->isValid()) {
        \Log::warning('Invalid webhook payload', ['errors' => $validator->errors()]);
    }
    

Extension Points

  1. Custom Traits

    • Extend Nikolag\Core\Traits\HasGatewayConfig for shared gateway logic:
      namespace App\Traits;
      
      use Nikolag\Core\Traits\HasGatewayConfig;
      
      trait StripeConfigurable
      {
          use HasGatewayConfig;
      
          protected function getGatewayConfig(): array
          {
              return config('nikolag.connections.stripe');
          }
      }
      
  2. Utility Classes

    • Override Nikolag\Core\Utilities\PaymentHelper for custom validation:
      namespace App\Utilities;
      
      use Nikolag\Core\Utilities\PaymentHelper
      
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.
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle
dmstr/api-platform-utils-bundle
dmstr/api-configuration-bundle
chrisdev/ux-components
baks-dev/finances
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle