baks-dev/avito
Laravel/PHP 8.4+ модуль для интеграции с Avito API: подключение через Composer, готовая основа для работы с запросами/данными Avito и набор PHPUnit тестов (группа avito). MIT лицензия.
Installation
composer require baks-dev/avito
Ensure your project uses PHP 8.4+ and Laravel 10.x (or Symfony 6+ if applicable).
Configuration
Publish the package config (if available) or manually set credentials in .env:
AVITO_API_TOKEN=your_partner_token_here
AVITO_API_URL=https://api.avito.ru
AVITO_CATEGORY_ID=123 # Optional: Default category for listings
Service Registration
Bind the Avito client in AppServiceProvider:
use BaksDev\Avito\AvitoClient;
public function register()
{
$this->app->bind(AvitoClient::class, function ($app) {
return new AvitoClient(
$app['config']['avito.token'],
$app['config']['avito.api_url']
);
});
}
First Use Case: Fetch Ads Inject the client into a controller or service:
use BaksDev\Avito\AvitoClient;
public function showAds(AvitoClient $avito)
{
$ads = $avito->searchAds([
'categoryId' => $this->categoryId,
'limit' => 20,
'sort' => 'PRICE_ASC'
]);
return response()->json($ads);
}
Where to Look First
vendor/baks-dev/avito/src/AvitoClient.php (core methods).vendor/baks-dev/avito/src/Exceptions/ (error handling).vendor/baks-dev/avito/tests/ (usage patterns and edge cases).Dependency Injection
AvitoClient into services/controllers.public function __construct(private AvitoClient $avito) {}
AvitoClient::search()) to maintain testability.Configuration Management
config/avito.php:
return [
'token' => env('AVITO_API_TOKEN'),
'api_url' => env('AVITO_API_URL', 'https://api.avito.ru'),
'default_category' => env('AVITO_CATEGORY_ID'),
'timeout' => 30, // seconds
];
php artisan vendor:publish --provider="BaksDev\Avito\AvitoServiceProvider"
Request/Response Handling
$params = [
'categoryId' => 123,
'filter' => ['price' => ['from' => 1000]],
'sort' => 'PRICE_DESC'
];
$ads = $avito->searchAds($params);
$ads = collect($avito->searchAds($params))->map(function ($ad) {
return [
'id' => $ad['id'],
'title' => $ad['title'],
'price' => $ad['price']['value'],
'url' => $ad['url']
];
});
Authentication Patterns
.env).config/avito.php:
'auth' => [
'client_id' => env('AVITO_OAUTH_CLIENT_ID'),
'client_secret' => env('AVITO_OAUTH_CLIENT_SECRET'),
'redirect_uri' => env('AVITO_OAUTH_REDIRECT_URI'),
],
Error Handling
try {
$ads = $avito->searchAds($params);
} catch (\BaksDev\Avito\Exceptions\AvitoException $e) {
Log::error("Avito API error: " . $e->getMessage());
return response()->json(['error' => 'Failed to fetch ads'], 500);
}
class AvitoRateLimitException extends \Exception {}
Caching Strategies
$ads = Cache::remember("avito_ads_{$categoryId}", now()->addHours(1), function () use ($avito, $categoryId) {
return $avito->searchAds(['categoryId' => $categoryId]);
});
Queueing for Bulk Operations
dispatch(new SyncAvitoListings($avito, $listingIds))->onQueue('avito');
use BaksDev\Avito\AvitoClient;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
class SyncAvitoListings implements ShouldQueue
{
use Queueable;
public function __construct(
private AvitoClient $avito,
private array $listingIds
) {}
public function handle()
{
foreach ($this->listingIds as $id) {
$this->avito->getListing($id);
}
}
}
Integration with Laravel Features
public function toArray($request)
{
return [
'data' => $this->ads->map(function ($ad) {
return new AvitoAdResource($ad);
}),
];
}
event(new AvitoListingSynced($listing));
Webhook Listeners
public function handle(AvitoWebhookEvent $event)
{
$payload = $event->payload;
// Process webhook (e.g., update local DB)
}
Rate Limit Handling
use Symfony\Component\Retry\Retry;
$retry = new Retry(3, 1000); // 3 retries, 1s delay
$ads = $retry->retry(function () use ($avito, $params) {
return $avito->searchAds($params);
});
Testing Patterns
$mock = Mockery::mock(AvitoClient::class);
$mock->shouldReceive('searchAds')->once()->andReturn($mockAds);
$this->app->instance(AvitoClient::class, $mock);
php artisan test --group=avito
Localization
$adTitle = Str::of($ad['title'])->ascii()->title();
Monitoring
Telescope::addData(['avito' => [
'response_time' => $endTime - $startTime,
'status' => $response->status(),
]]);
Authentication Issues
.env and implement refresh logic if using OAuth.encryption service to securely store tokens in the database if needed.Rate Limiting
429 Too Many Requests.How can I help you explore Laravel packages today?