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

Bingads Laravel Package

microsoft/bingads

Microsoft Bing Ads PHP SDK with PSR-4 autoloading and SOAP proxies for all Bing Ads API services. Simplifies OAuth authentication and integrates easily via Composer (microsoft/bingads) so you can build and manage advertising apps in PHP.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require microsoft/bingads
    

    Ensure extension=soap is enabled in php.ini.

  2. First Authentication Use the OAuthDesktopMobileAuthCodeGrant for local development:

    use Microsoft\BingAds\V13\Authentication\OAuthDesktopMobileAuthCodeGrant;
    use Microsoft\BingAds\V13\Authentication\AuthenticationHelper;
    
    $authenticationHelper = new AuthenticationHelper();
    $authCodeGrant = new OAuthDesktopMobileAuthCodeGrant(
        $authenticationHelper->GetDeveloperToken(),
        $authenticationHelper->GetRefreshToken(),
        $authenticationHelper->GetAccessToken(),
        $authenticationHelper->GetAuthCode()
    );
    $authCodeGrant->Authenticate();
    
  3. First API Call Fetch account information:

    use Microsoft\BingAds\V13\CampaignManagement\CampaignManagementServiceClient;
    
    $serviceClient = new CampaignManagementServiceClient(
        $authCodeGrant->GetAccessToken(),
        $authCodeGrant->GetRefreshToken(),
        $authCodeGrant->GetCustomerId()
    );
    
    $accounts = $serviceClient->GetCustomerAccounts();
    

Key Resources


Implementation Patterns

1. Service Client Workflow

Pattern: Initialize once, reuse across requests.

// app/Services/BingAdsService.php
class BingAdsService {
    private $serviceClient;

    public function __construct(OAuthDesktopMobileAuthCodeGrant $auth) {
        $this->serviceClient = new CampaignManagementServiceClient(
            $auth->GetAccessToken(),
            $auth->GetRefreshToken(),
            $auth->GetCustomerId()
        );
    }

    public function getCampaigns() {
        return $this->serviceClient->GetCampaigns();
    }
}

2. Bulk Operations

Use BulkService for large-scale updates:

$bulkService = new BulkServiceClient($auth);
$bulkOperation = new BulkOperationHeader();
$bulkOperation->Operation = BulkOperationType::Add;
$bulkOperation->Objects = [$campaign1, $campaign2];

$bulkResponse = $bulkService->ExecuteBulkOperation($bulkOperation);

3. Reporting

Generate and download reports:

$reportingService = new ReportingServiceClient($auth);
$reportRequest = new ReportRequest();
$reportRequest->ReportName = "CampaignPerformanceReport";
$reportRequest->Aggregation = ReportAggregation::Daily;
$reportRequest->Columns = ["CampaignName", "Impressions", "Clicks"];

$downloadRequest = new DownloadReportRequest($reportRequest);
$reportDownload = $reportingService->DownloadReport($downloadRequest);

4. Error Handling

Wrap API calls in try-catch:

try {
    $response = $serviceClient->GetCampaigns();
} catch (Exception $e) {
    if ($e->getCode() === 401) {
        $auth->RefreshToken(); // Refresh and retry
    }
    throw $e;
}

5. Configuration Management

Store credentials in .env:

BINGADS_DEVELOPER_TOKEN=your_dev_token
BINGADS_REFRESH_TOKEN=your_refresh_token
BINGADS_CUSTOMER_ID=1234567

Load via Laravel’s config() helper or a custom config file.


Gotchas and Tips

Authentication Pitfalls

  1. Token Expiry

    • Always handle 401 Unauthorized by refreshing the token:
      if ($e->getCode() === 401) {
          $auth->RefreshToken();
          retry(); // Implement retry logic
      }
      
    • Tip: Use Laravel’s retry() helper or a custom decorator.
  2. Sandbox vs. Production

    • Sandbox uses login.windows-ppe.net (not live-int.com as of v13.0.10).
    • Gotcha: Hardcoded URLs in older SDK versions may break.
  3. Scopes

    • Default scope is msads.manage (required for MFA).
    • Override temporarily with oAuthScope in ServiceClient constructor:
      $serviceClient = new CampaignManagementServiceClient(
          $auth->GetAccessToken(),
          $auth->GetRefreshToken(),
          $auth->GetCustomerId(),
          ['oAuthScope' => 'https://bingads.microsoft.com/Api/Advertiser/Manage']
      );
      

API-Specific Quirks

  1. Bulk Operations

    • Gotcha: Bulk operations fail silently on invalid objects. Validate before submission.
    • Tip: Use ValidateBulkOperation to pre-check:
      $validation = $bulkService->ValidateBulkOperation($bulkOperation);
      if ($validation->HasErrors) {
          throw new \RuntimeException("Bulk operation validation failed");
      }
      
  2. Reporting Delays

    • Some reports (e.g., OfflineConversionReport) take 24+ hours to populate.
    • Tip: Add a reportReady() check with exponential backoff.
  3. SOAP Headers

    • Gotcha: Missing CustomerId or CustomerAccountId in headers causes 400 Bad Request.
    • Tip: Verify headers with:
      $serviceClient->GetServiceClient()->GetSoapClient()->__getLastRequestHeaders();
      
  4. Rate Limiting

    • Bing Ads enforces 5 requests/second per endpoint.
    • Tip: Use Laravel’s throttle middleware or a queue:
      Queue::later(now()->addSeconds(0.2), fn() => $serviceClient->GetCampaigns());
      

Debugging Tips

  1. Enable SOAP Debugging

    $serviceClient->GetServiceClient()->GetSoapClient()->setDebug(true);
    $lastRequest = $serviceClient->GetServiceClient()->GetSoapClient()->__getLastRequest();
    $lastResponse = $serviceClient->GetServiceClient()->GetSoapClient()->__getLastResponse();
    
  2. Log Authentication Tokens

    • Security Note: Never log access_token or refresh_token in production.
    • Tip: Log only the customer_id and timestamp for debugging:
      Log::debug("BingAds request for customer {$auth->GetCustomerId()}");
      
  3. Version Mismatches

    • Gotcha: Using an outdated SDK may cause InvalidOperationException.
    • Tip: Pin the SDK version in composer.json:
      "microsoft/bingads": "13.0.28"
      

Extension Points

  1. Custom Proxies

    • Extend auto-generated proxies (e.g., CampaignManagementServiceClient) to add business logic:
      class CustomCampaignServiceClient extends CampaignManagementServiceClient {
          public function getActiveCampaigns() {
              $campaigns = parent::GetCampaigns();
              return array_filter($campaigns, fn($c) => $c->Status == 'Active');
          }
      }
      
  2. Event Listeners

    • Hook into Laravel’s illuminate.queue events to retry failed Bing Ads jobs:
      Queue::failing(function (FailedJob $job, $exception) {
          if (str_contains($exception->getMessage(), '401')) {
              $job->release(60); // Retry after 60 seconds
          }
      });
      
  3. Model Bindings

    • Use Laravel’s Eloquent to map Bing Ads entities:
      class BingAdCampaign extends Model {
          protected $fillable = ['name', 'status', 'budget'];
      
          public static function syncFromApi() {
              $campaigns = app(BingAdsService::class)->getCampaigns();
              return self::upsert($campaigns->toArray(), ['id']);
          }
      }
      
  4. Testing

    • Mock the ServiceClient in PHPUnit:
      $mockClient = $this->createMock(CampaignManagementServiceClient::class);
      $mockClient->method('GetCampaigns')->willReturn(new Campaign[]);
      $this->app->instance(CampaignManagementServiceClient::class, $mockClient);
      
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity