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

Bing Ads Api Bundle Laravel Package

coddict/bing-ads-api-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require coddict/bing-ads-api-bundle
    

    Add to config/bundles.php:

    Coddict\BingAdsApiBundle\CoddictBingAdsApiBundle::class => ['all' => true],
    
  2. 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
    
  3. 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);
    }
    

Implementation Patterns

Workflow: OAuth2 Authentication

  1. 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']);
    
  2. Handle Callback Exchange the code for an access token:

    $token = $this->bingAdsClient->getAccessToken($request->query->get('code'));
    $this->bingAdsClient->setAccessToken($token);
    
  3. Refresh Tokens Automate token refresh using a cron job or event listener:

    $this->bingAdsClient->refreshAccessToken();
    

Integration with Laravel Services

  1. 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;
    });
    
  2. API Requests Use the callApi() method for REST endpoints:

    $response = $this->bingAdsClient->callApi(
        'GET',
        '/campaigns',
        ['CustomerId' => '12345']
    );
    
  3. Event-Driven Workflows Listen for token refresh events:

    $this->events->listen(
        BingAdsEvents::TOKEN_REFRESHED,
        function ($token) {
            // Store token in DB or cache
        }
    );
    

Common Use Cases

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')

Gotchas and Tips

Pitfalls

  1. Environment Mismatch

    • Issue: Forgetting to switch between sandbox and production environments.
    • Fix: Validate the BING_ADS_ENVIRONMENT in .env and use:
      $this->bingAdsClient->setEnvironment('production'); // Explicitly set if needed
      
  2. Token Expiry

    • Issue: Silent failures due to expired tokens.
    • Fix: Implement a middleware to refresh tokens:
      public function handle($request, Closure $next)
      {
          if (!$this->bingAdsClient->isTokenValid()) {
              $this->bingAdsClient->refreshAccessToken();
          }
          return $next($request);
      }
      
  3. Rate Limiting

    • Issue: 429 Too Many Requests errors.
    • Fix: Add exponential backoff:
      try {
          $response = $this->bingAdsClient->callApi('GET', '/campaigns');
      } catch (RateLimitException $e) {
          sleep($e->getRetryAfter());
          retry();
      }
      

Debugging Tips

  1. Enable Logging Configure Monolog in config/packages/coddict_bing_ads_api.yaml:

    logging:
        enabled: true
        channel: 'bing_ads'
    
  2. Inspect Raw Responses Use the getLastResponse() method:

    $response = $this->bingAdsClient->callApi('GET', '/campaigns');
    \Log::debug('Raw Response:', [$response->getBody(), $response->getStatusCode()]);
    
  3. Validate OAuth Scopes Ensure scopes are correctly configured in the auth URL:

    $authUrl = $this->bingAdsClient->getAuthUrl([
        'scope' => 'https://bingads.microsoft.com/OfflineAccess ReadWrite',
    ]);
    

Extension Points

  1. Custom API Clients Extend BingAdsClient to add domain-specific methods:

    class CustomBingAdsClient extends BingAdsClient
    {
        public function getCampaignsById($campaignId)
        {
            return $this->callApi('GET', "/campaigns/{$campaignId}");
        }
    }
    
  2. Event Listeners Subscribe to BingAdsEvents for custom logic:

    $this->events->listen(BingAdsEvents::API_REQUEST, function ($request) {
        // Modify request before sending
    });
    
  3. Configuration Overrides Override bundle config in config/packages/coddict_bing_ads_api.yaml:

    default_timeout: 30
    retry_attempts: 3
    

Pro Tips

  • 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 {}
    
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.
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver