baks-dev/ozon
Laravel/PHP модуль для работы с Ozon API. Установка через Composer (baks-dev/ozon), поддержка PHP 8.4+, версия 7.4.10. В комплекте тесты PHPUnit (группа ozon). Лицензия MIT.
Installation:
composer require baks-dev/ozon
Ensure your project uses PHP 8.4+ and Laravel 10.x+.
Publish Configuration:
php artisan vendor:publish --provider="BaksDev\Ozon\OzonServiceProvider" --tag="config"
Configure .env with Ozon API credentials:
OZON_CLIENT_ID=your_client_id
OZON_CLIENT_SECRET=your_client_secret
OZON_SANDBOX=true # Use sandbox for testing
First API Call: Use the facade to fetch orders (example from README or tests):
use BaksDev\Ozon\Facades\Ozon;
$orders = Ozon::orders()->fetch();
Run Tests: Validate the package works in your environment:
php artisan test --group=ozon
Order Management:
$orders = Ozon::orders()->fetch(['limit' => 10]);
public function handle(OzonOrderCreated $event) {
// Process order in your system
Order::create($event->orderData);
}
Catalog Sync:
Ozon::products()->update([
'id' => 123,
'price' => 999.99,
'available' => true,
]);
class SyncOzonInventory implements ShouldQueue {
public function handle() {
$ozonProducts = Ozon::products()->fetch();
foreach ($ozonProducts as $product) {
Product::where('ozon_id', $product['id'])->update([
'stock' => $product['available_quantity'],
]);
}
}
}
OAuth Integration:
$authUrl = Ozon::auth()->getAuthorizationUrl();
public function handleOzonCallback(Request $request) {
$token = Ozon::auth()->getAccessToken($request->code);
// Store token for future use
}
Use Queues for Async Operations: Offload heavy syncs (e.g., bulk updates) to queues to avoid timeouts:
SyncOzonInventory::dispatch();
Leverage Laravel Events:
Subscribe to Ozon events (e.g., OzonOrderCreated) to trigger business logic:
// In EventServiceProvider
protected $listen = [
\BaksDev\Ozon\Events\OzonOrderCreated::class => [
HandleOzonOrder::class,
],
];
Customize HTTP Client: Extend the package’s HTTP client for retries or middleware:
// In OzonServiceProvider
$this->app->singleton(OzonClient::class, function ($app) {
return new OzonClient(
$app->make(HttpClient::class)->withOptions([
'timeout' => 30,
'retry' => true,
])
);
});
Database Migrations: Create migrations to store Ozon data locally:
Schema::create('ozon_orders', function (Blueprint $table) {
$table->id();
$table->string('ozon_id');
$table->json('data');
$table->timestamps();
});
Sandbox vs. Production:
OZON_SANDBOX can lead to real API calls..env variable to switch environments:
OZON_SANDBOX=${APP_ENV !== 'production'}
Rate Limiting:
config/http.php:
'retry' => [
'enabled' => true,
'max_attempts' => 5,
'delay' => 1000, // 1 second
],
Missing Webhook Support:
Route::post('/ozon/webhook', function (Request $request) {
$payload = $request->json()->all();
// Validate signature and process
event(new OzonWebhookReceived($payload));
});
Error Handling:
// app/Exceptions/Handler.php
public function render($request, Throwable $exception) {
if ($exception instanceof \BaksDev\Ozon\Exceptions\OzonApiException) {
return response()->json([
'error' => 'Ozon API Error',
'message' => $exception->getMessage(),
], 422);
}
return parent::render($request, $exception);
}
Type Safety:
fetch() returns array instead of a Collection or DTO).class OzonOrderDto {
public function __construct(
public string $id,
public array $items,
public float $total,
) {}
}
Enable API Logging: Add middleware to log Ozon API requests/responses:
// app/Http/Middleware/LogOzonRequests.php
public function handle($request, Closure $next) {
if ($request->is('ozon/*')) {
\Log::info('Ozon API Request', $request->all());
}
return $next($request);
}
Validate API Responses:
Use Laravel’s Http facade to inspect raw responses:
$response = Http::withHeaders([
'Authorization' => 'Bearer ' . $token,
])->get('https://api.ozon.ru/orders');
\Log::debug('Ozon Response', $response->body());
Test with Postman: Manually test Ozon endpoints using Postman with your credentials to isolate issues.
Add Custom Endpoints: Extend the package’s client to support unsupported endpoints:
// app/Services/OzonClientExtension.php
public function customEndpoint(array $data) {
return $this->client->post('https://api.ozon.ru/custom', $data);
}
Override Facade Methods: Replace facade methods in a service provider:
// app/Providers/OzonServiceProvider.php
public function register() {
$this->app->bind('ozon', function () {
return new CustomOzonService();
});
}
Add New Events: Dispatch custom events for business logic:
// In your service
event(new OzonInventoryUpdated($productId, $newStock));
Localize Error Messages: Translate Ozon API errors for users:
// app/Providers/AppServiceProvider.php
public function boot() {
\BaksDev\Ozon\Exceptions\OzonApiException::setTranslator(function ($message) {
return __("ozon.errors.$message");
});
}
How can I help you explore Laravel packages today?