Install the Bundle
composer require coddict/bing-ads-api-bundle
Add to config/bundles.php:
Coddict\BingAdsApiBundle\CoddictBingAdsApiBundle::class => ['all' => true],
Configure Environment Publish the default config:
php bin/console config:dump-reference coddict_bing_ads_api
Update .env with required keys:
BING_ADS_CLIENT_ID=your_client_id
BING_ADS_CLIENT_SECRET=your_client_secret
BING_ADS_DEVELOPER_TOKEN=your_dev_token
BING_ADS_ENVIRONMENT=sandbox|production # Default: sandbox
First Use Case: Authentication
Inject the BingAdsClient service in a controller or command:
use Coddict\BingAdsApiBundle\Service\BingAdsClient;
public function __construct(private BingAdsClient $bingAdsClient) {}
public function authenticate(Request $request)
{
$authUrl = $this->bingAdsClient->getAuthUrl();
return redirect($authUrl);
}
Redirect to Auth URL
Use the getAuthUrl() method to redirect users to Bing Ads OAuth2 flow:
$authUrl = $this->bingAdsClient->getAuthUrl(['scope' => 'https://bingads.microsoft.com/OfflineAccess']);
Handle Callback
Exchange the code for an access token:
$token = $this->bingAdsClient->getAccessToken($request->query->get('code'));
$this->bingAdsClient->setAccessToken($token);
Refresh Tokens Automate token refresh using a cron job or event listener:
$this->bingAdsClient->refreshAccessToken();
Service Container Binding Bind custom services to extend functionality:
$this->app->bind(BingAdsClient::class, function ($app) {
$client = new BingAdsClient(
$app['config']['bing_ads.client_id'],
$app['config']['bing_ads.client_secret'],
$app['config']['bing_ads.developer_token']
);
$client->setEnvironment($app['config']['bing_ads.environment']);
return $client;
});
API Requests
Use the callApi() method for REST endpoints:
$response = $this->bingAdsClient->callApi(
'GET',
'/campaigns',
['CustomerId' => '12345']
);
Event-Driven Workflows Listen for token refresh events:
$this->events->listen(
BingAdsEvents::TOKEN_REFRESHED,
function ($token) {
// Store token in DB or cache
}
);
| Use Case | Implementation Example |
|---|---|
| Campaign Management | $this->bingAdsClient->callApi('POST', '/campaigns', $campaignData) |
| Reporting | $this->bingAdsClient->downloadReport('CampaignPerformance', ['TimePeriod' => 'ThisMonth']) |
| Bulk Operations | $this->bingAdsClient->uploadBulkMutation($filePath, 'Campaign') |
Environment Mismatch
sandbox and production environments.BING_ADS_ENVIRONMENT in .env and use:
$this->bingAdsClient->setEnvironment('production'); // Explicitly set if needed
Token Expiry
public function handle($request, Closure $next)
{
if (!$this->bingAdsClient->isTokenValid()) {
$this->bingAdsClient->refreshAccessToken();
}
return $next($request);
}
Rate Limiting
429 Too Many Requests errors.try {
$response = $this->bingAdsClient->callApi('GET', '/campaigns');
} catch (RateLimitException $e) {
sleep($e->getRetryAfter());
retry();
}
Enable Logging
Configure Monolog in config/packages/coddict_bing_ads_api.yaml:
logging:
enabled: true
channel: 'bing_ads'
Inspect Raw Responses
Use the getLastResponse() method:
$response = $this->bingAdsClient->callApi('GET', '/campaigns');
\Log::debug('Raw Response:', [$response->getBody(), $response->getStatusCode()]);
Validate OAuth Scopes Ensure scopes are correctly configured in the auth URL:
$authUrl = $this->bingAdsClient->getAuthUrl([
'scope' => 'https://bingads.microsoft.com/OfflineAccess ReadWrite',
]);
Custom API Clients
Extend BingAdsClient to add domain-specific methods:
class CustomBingAdsClient extends BingAdsClient
{
public function getCampaignsById($campaignId)
{
return $this->callApi('GET', "/campaigns/{$campaignId}");
}
}
Event Listeners
Subscribe to BingAdsEvents for custom logic:
$this->events->listen(BingAdsEvents::API_REQUEST, function ($request) {
// Modify request before sending
});
Configuration Overrides
Override bundle config in config/packages/coddict_bing_ads_api.yaml:
default_timeout: 30
retry_attempts: 3
Use Laravel Cache for Tokens Store access tokens in the cache to avoid repeated DB writes:
$token = $this->cache->get('bing_ads_token');
if (!$token) {
$token = $this->bingAdsClient->refreshAccessToken();
$this->cache->put('bing_ads_token', $token, now()->addHours(1));
}
Leverage Laravel Queues Offload long-running operations (e.g., bulk uploads) to queues:
dispatch(new UploadBulkCampaignsJob($filePath, $this->bingAdsClient));
Type Safety with PHP 8.1+ Use attributes to validate API responses:
#[Assert\All([
new Assert\Type('array'),
new Assert\KeyExists('Id'),
new Assert\Type(['Id' => 'string']),
])]
public function validateCampaign(array $campaign): void {}
How can I help you explore Laravel packages today?