Installation
composer require baks-dev/four-tochki
php artisan vendor:publish --provider="BaksDev\FourTochki\FourTochkiServiceProvider"
php artisan migrate
Configuration
.env:
FOURTOCHKI_API_KEY=your_api_key_here
FOURTOCHKI_WAREHOUSE_ID=12345
config/fourtochki.php with your warehouse IDs (from 4tochki Partner Warehouses).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']]
);
}
Run a Test
php artisan test --group=four-tochki
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);
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']]);
}
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...
}
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
);
});
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')
]);
}
}
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
Doctrine vs. Eloquent Mismatch
InventoryRepository to use Eloquent:
class EloquentInventoryRepository implements InventoryRepositoryInterface {
public function findByWarehouse($warehouseId) {
return \App\Models\Inventory::where('warehouse_id', $warehouseId)->get();
}
}
API Rate Limits
use Symfony\Component\HttpClient\RetryStrategy;
$client = \Http::withOptions([
'retry' => RetryStrategy::fromConfig([
'max_retries' => 3,
'delay' => 1000,
'multiplier' => 2,
'max_delay' => 5000,
]),
]);
Webhook Validation
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');
}
}
Time Zone Mismatches
$createdAt = Carbon::parse($payload['created_at'])->timezone('Europe/Moscow');
Warehouse ID Hardcoding
$warehouseId = config('fourtochki.warehouses.default');
// or
$warehouseId = env('FOURTOchki_WAREHOUSE_ID');
Enable API Logging Add a middleware to log API requests/responses:
\BaksDev\FourTochki\Http\Middleware\LogApiRequests::class,
Check logs in storage/logs/laravel.log.
Test with Sandbox Credentials Use 4tochki’s sandbox environment for testing:
FOURTOCHKI_API_BASE_URI=https://sandbox.4tochki.ru/api
Validate API Responses
Use Laravel’s dd() or dump() to inspect raw responses:
$response = FourTochki::orders()->get($orderId);
dd($response->toArray());
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');
}
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);
}
}
Override Repository Logic Replace the default repository implementations:
$this->app->bind(
\BaksDev\FourTochki\Repository\OrderRepositoryInterface::class,
\App\Repositories\CustomOrderRepository::class
);
Add Custom Fields to Models Extend the package’s entities to include additional fields:
class ExtendedOrder extends \BaksDev\FourTochki\Entity\Order {
protected $customField;
}
Webhook Handlers Register custom webhook handlers:
FourTochki::webhooks()->extend('custom_event', function ($payload) {
// Handle custom event
});
How can I help you explore Laravel packages today?