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

Four Tochki Laravel Package

baks-dev/four-tochki

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps for Laravel Integration

  1. Installation

    composer require baks-dev/four-tochki
    php artisan vendor:publish --provider="BaksDev\FourTochki\FourTochkiServiceProvider"
    
    • Publish config and migrations:
      php artisan migrate
      
  2. Configuration

    • Set API credentials in .env:
      FOURTOCHKI_API_KEY=your_api_key_here
      FOURTOCHKI_WAREHOUSE_ID=12345
      
    • Update config/fourtochki.php with your warehouse IDs (from 4tochki Partner Warehouses).
  3. First Use Case: Sync Inventory

    use BaksDev\FourTochki\Facades\FourTochki;
    
    // Fetch inventory for a warehouse
    $inventory = FourTochki::inventory()->get(['warehouse_id' => env('FOURTOCHKI_WAREHOUSE_ID')]);
    
    // Update local database (assuming you've set up a model)
    foreach ($inventory as $item) {
        \App\Models\Product::updateOrCreate(
            ['sku' => $item['sku']],
            ['quantity' => $item['quantity']]
        );
    }
    
  4. Run a Test

    php artisan test --group=four-tochki
    

Implementation Patterns

1. Service Facade Pattern

Use the FourTochki facade to interact with 4tochki’s API:

// Orders
$orders = FourTochki::orders()->list(['limit' => 10]);
$order = FourTochki::orders()->get($orderId);

// Inventory
$inventory = FourTochki::inventory()->get(['warehouse_id' => 12345]);

// Shipments
$shipment = FourTochki::shipments()->create($orderId, $carrier);

2. Event-Driven Workflows

Leverage Laravel’s event system to react to 4tochki webhooks:

// Register webhook listener
FourTochki::webhooks()->listen('order_updated', function ($payload) {
    event(new \App\Events\OrderUpdated($payload));
});

// Handle the event in a listener
public function handle(OrderUpdated $event) {
    $order = \App\Models\Order::find($event->payload['id']);
    $order->update(['status' => $event->payload['status']]);
}

3. Queue-Based Processing

Offload long-running tasks (e.g., bulk inventory sync) to queues:

// Dispatch a job
SyncInventoryJob::dispatch(env('FOURTOCHKI_WAREHOUSE_ID'));

// Job implementation
public function handle() {
    $inventory = FourTochki::inventory()->get(['warehouse_id' => $this->warehouseId]);
    // Process inventory...
}

4. Customizing API Requests

Extend the package’s HTTP client for custom logic:

// Override the default HTTP client in a service provider
$this->app->bind(\BaksDev\FourTochki\Http\Client::class, function ($app) {
    return new \BaksDev\FourTochki\Http\Client(
        $app['http.client'],
        config('fourtochki.api.base_uri'),
        new CustomRequestInterceptor() // Your custom logic
    );
});

5. Database Sync Patterns

Use Laravel’s model events to keep local data in sync:

// Sync inventory on product creation/update
Product::observe(ProductObserver::class);

class ProductObserver {
    public function saved(Product $product) {
        if ($product->wasRecentlyCreated) {
            $this->syncWithFourTochki($product);
        }
    }

    private function syncWithFourTochki(Product $product) {
        FourTochki::inventory()->update($product->sku, [
            'quantity' => $product->quantity,
            'warehouse_id' => env('FOURTOCHKI_WAREHOUSE_ID')
        ]);
    }
}

6. CLI Integration

Use the package’s console commands in Laravel:

// Sync inventory via CLI
php artisan fourtochki:inventory:sync --warehouse=12345

// Create a shipment
php artisan fourtochki:shipment:create order_id=123 carrier=4tochki

Gotchas and Tips

Pitfalls

  1. Doctrine vs. Eloquent Mismatch

    • The package uses Doctrine ORM by default. To avoid conflicts:
      • Replace Doctrine models with Eloquent models or use raw queries via DBAL.
      • Example: Override the InventoryRepository to use Eloquent:
        class EloquentInventoryRepository implements InventoryRepositoryInterface {
            public function findByWarehouse($warehouseId) {
                return \App\Models\Inventory::where('warehouse_id', $warehouseId)->get();
            }
        }
        
  2. API Rate Limits

    • 4tochki may throttle requests. Implement exponential backoff:
      use Symfony\Component\HttpClient\RetryStrategy;
      
      $client = \Http::withOptions([
          'retry' => RetryStrategy::fromConfig([
              'max_retries' => 3,
              'delay' => 1000,
              'multiplier' => 2,
              'max_delay' => 5000,
          ]),
      ]);
      
  3. Webhook Validation

    • Always validate 4tochki webhook signatures to prevent spoofing:
      public function handleWebhook(Request $request) {
          $payload = $request->getContent();
          $signature = $request->header('X-4tochki-Signature');
      
          if (!hash_equals(
              hash_hmac('sha256', $payload, config('fourtochki.webhook_secret')),
              $signature
          )) {
              abort(403, 'Invalid signature');
          }
      }
      
  4. Time Zone Mismatches

    • 4tochki may return timestamps in UTC or Moscow time (MSK). Normalize them:
      $createdAt = Carbon::parse($payload['created_at'])->timezone('Europe/Moscow');
      
  5. Warehouse ID Hardcoding

    • Avoid hardcoding warehouse IDs in code. Use Laravel’s config or environment variables:
      $warehouseId = config('fourtochki.warehouses.default');
      // or
      $warehouseId = env('FOURTOchki_WAREHOUSE_ID');
      

Debugging Tips

  1. Enable API Logging Add a middleware to log API requests/responses:

    \BaksDev\FourTochki\Http\Middleware\LogApiRequests::class,
    

    Check logs in storage/logs/laravel.log.

  2. Test with Sandbox Credentials Use 4tochki’s sandbox environment for testing:

    FOURTOCHKI_API_BASE_URI=https://sandbox.4tochki.ru/api
    
  3. Validate API Responses Use Laravel’s dd() or dump() to inspect raw responses:

    $response = FourTochki::orders()->get($orderId);
    dd($response->toArray());
    
  4. Handle API Errors Gracefully Catch exceptions and log them:

    try {
        $shipment = FourTochki::shipments()->create($orderId, $carrier);
    } catch (\BaksDev\FourTochki\Exception\ApiException $e) {
        \Log::error('4tochki API error: ' . $e->getMessage());
        abort(500, 'Failed to create shipment');
    }
    

Extension Points

  1. Custom API Endpoints Extend the ApiClient to add unsupported endpoints:

    class CustomApiClient extends \BaksDev\FourTochki\Http\ApiClient {
        public function customEndpoint($params) {
            return $this->get('custom/endpoint', $params);
        }
    }
    
  2. Override Repository Logic Replace the default repository implementations:

    $this->app->bind(
        \BaksDev\FourTochki\Repository\OrderRepositoryInterface::class,
        \App\Repositories\CustomOrderRepository::class
    );
    
  3. Add Custom Fields to Models Extend the package’s entities to include additional fields:

    class ExtendedOrder extends \BaksDev\FourTochki\Entity\Order {
        protected $customField;
    }
    
  4. Webhook Handlers Register custom webhook handlers:

    FourTochki::webhooks()->extend('custom_event', function ($payload) {
        // Handle custom event
    });
    

Configuration Quirks

  1. Missing Config Keys
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity