You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Bing Ads API获取指定账户的广告总花费(PHP集成)

Hey there, I’ve built integrations with the Bing Ads API in PHP before, so let me break down exactly how to pull the total ad spend for a specific account using either SOAP (the official recommended approach) or raw cURL calls. I know it can be tricky to find working examples, so I’ll include full code snippets and key gotchas to watch out for.

Prerequisites First

  • You’ll need a Bing Ads Developer Account and a registered application to get your Client ID, Client Secret, and Developer Token.
  • A valid OAuth 2.0 Access Token for the target account (use the Authorization Code Flow to generate this; remember tokens expire, so you’ll need a refresh mechanism for production).
  • The Account ID of the account you want to fetch spend data for.

Bing Ads provides a SOAP-based API, and PHP’s built-in SoapClient works well here. We’ll use the Reporting Service to generate a summary report of account spend.

<?php
// Replace these with your actual credentials
$accessToken = 'YOUR_OAUTH_ACCESS_TOKEN';
$accountId = 'TARGET_ACCOUNT_ID';
$developerToken = 'YOUR_DEVELOPER_TOKEN';

// Initialize SOAP client with the Reporting Service WSDL
$wsdl = 'https://reporting.api.bingads.microsoft.com/Api/Advertiser/Reporting/v13/ReportingService.svc?wsdl';
$soapClient = new SoapClient($wsdl, [
    'trace' => true, // Enable for debugging (view requests/responses)
    'exceptions' => true,
    'soap_version' => SOAP_1_1
]);

// Set up required SOAP headers
$headers = [
    new SoapHeader('https://bingads.microsoft.com/Reporting/v13', 'AuthenticationToken', $accessToken),
    new SoapHeader('https://bingads.microsoft.com/Reporting/v13', 'DeveloperToken', $developerToken),
    new SoapHeader('https://bingads.microsoft.com/Reporting/v13', 'CustomerAccountId', $accountId)
];
$soapClient->__setSoapHeaders($headers);

// Build the account performance report request
$reportRequest = [
    'AccountPerformanceReportRequest' => [
        'Format' => 'Csv',
        'ReportName' => 'Total Ad Spend Summary',
        'ReturnOnlyCompleteData' => false,
        'Aggregation' => 'Summary', // Get a single total row
        'Columns' => ['AccountId', 'Spend'], // Only fetch needed columns
        'Scope' => ['AccountIds' => [$accountId]],
        'Time' => ['PredefinedTime' => 'Last7Days'] // Adjust this to your desired date range
    ]
];

try {
    // Submit the report generation request
    $submitResponse = $soapClient->SubmitGenerateReport(['ReportRequest' => $reportRequest]);
    $reportRequestId = $submitResponse->SubmitGenerateReportResult->ReportRequestId;

    // Poll until the report is ready (Bing Ads reports are asynchronous)
    do {
        sleep(5); // Wait 5 seconds between checks to avoid rate limits
        $statusResponse = $soapClient->GetReportRequestStatus(['ReportRequestId' => $reportRequestId]);
        $reportStatus = $statusResponse->GetReportRequestStatusResult->Status;
    } while ($reportStatus === 'Pending' || $reportStatus === 'InProgress');

    if ($reportStatus === 'Success') {
        // Download the report and parse the total spend
        $downloadUrl = $statusResponse->GetReportRequestStatusResult->ReportDownloadUrl;
        $reportContent = file_get_contents($downloadUrl);
        
        // Parse CSV (skip header row, take the first data row)
        $rows = explode(PHP_EOL, trim($reportContent));
        if (isset($rows[1])) {
            [$account, $totalSpend] = str_getcsv($rows[1]);
            echo "Total Ad Spend for Account $account: $" . number_format($totalSpend, 2);
        }
    } else {
        echo "Report generation failed with status: $reportStatus";
    }
} catch (SoapFault $e) {
    echo "SOAP Error: " . $e->getMessage();
    // Uncomment below to debug raw request/response
    // echo "\nRequest:\n" . $soapClient->__getLastRequest();
    // echo "\nResponse:\n" . $soapClient->__getLastResponse();
}
?>

Option 2: Using Raw cURL

If you prefer not to use SoapClient, you can simulate the SOAP request with cURL. This is useful if you need more control over the HTTP request.

<?php
// Replace with your credentials
$accessToken = 'YOUR_OAUTH_ACCESS_TOKEN';
$accountId = 'TARGET_ACCOUNT_ID';
$developerToken = 'YOUR_DEVELOPER_TOKEN';

// SOAP XML for submitting the report request
$submitXml = <<<XML
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v13="https://bingads.microsoft.com/Reporting/v13">
   <soapenv:Header>
      <v13:AuthenticationToken>$accessToken</v13:AuthenticationToken>
      <v13:DeveloperToken>$developerToken</v13:DeveloperToken>
      <v13:CustomerAccountId>$accountId</v13:CustomerAccountId>
   </soapenv:Header>
   <soapenv:Body>
      <v13:SubmitGenerateReportRequest>
         <v13:ReportRequest xsi:type="v13:AccountPerformanceReportRequest" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
            <v13:Format>Csv</v13:Format>
            <v13:ReportName>Total Spend Report</v13:ReportName>
            <v13:ReturnOnlyCompleteData>false</v13:ReturnOnlyCompleteData>
            <v13:Aggregation>Summary</v13:Aggregation>
            <v13:Columns>
               <v13:AccountPerformanceReportColumn>AccountId</v13:AccountPerformanceReportColumn>
               <v13:AccountPerformanceReportColumn>Spend</v13:AccountPerformanceReportColumn>
            </v13:Columns>
            <v13:Scope>
               <v13:AccountIds>$accountId</v13:AccountIds>
            </v13:Scope>
            <v13:Time>
               <v13:PredefinedTime>Last7Days</v13:PredefinedTime>
            </v13:Time>
         </v13:ReportRequest>
      </v13:SubmitGenerateReportRequest>
   </soapenv:Body>
</soapenv:Envelope>
XML;

// Initialize cURL for submit request
$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL => 'https://reporting.api.bingads.microsoft.com/Api/Advertiser/Reporting/v13/ReportingService.svc',
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $submitXml,
    CURLOPT_HTTPHEADER => [
        'Content-Type: text/xml; charset=utf-8',
        'SOAPAction: "https://bingads.microsoft.com/Reporting/v13/SubmitGenerateReport"'
    ],
    CURLOPT_RETURNTRANSFER => true
]);

$submitResponse = curl_exec($ch);
if (curl_errno($ch)) {
    die("cURL Error on submit: " . curl_error($ch));
}
curl_close($ch);

// Parse response to get ReportRequestId
$xmlResponse = simplexml_load_string($submitResponse);
$xmlResponse->registerXPathNamespace('v13', 'https://bingads.microsoft.com/Reporting/v13');
$reportRequestId = (string)$xmlResponse->xpath('//v13:ReportRequestId')[0];

// Poll for report status
do {
    sleep(5);
    $statusXml = <<<XML
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v13="https://bingads.microsoft.com/Reporting/v13">
   <soapenv:Header>
      <v13:AuthenticationToken>$accessToken</v13:AuthenticationToken>
      <v13:DeveloperToken>$developerToken</v13:DeveloperToken>
      <v13:CustomerAccountId>$accountId</v13:CustomerAccountId>
   </soapenv:Header>
   <soapenv:Body>
      <v13:GetReportRequestStatusRequest>
         <v13:ReportRequestId>$reportRequestId</v13:ReportRequestId>
      </v13:GetReportRequestStatusRequest>
   </soapenv:Body>
</soapenv:Envelope>
XML;

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => 'https://reporting.api.bingads.microsoft.com/Api/Advertiser/Reporting/v13/ReportingService.svc',
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $statusXml,
        CURLOPT_HTTPHEADER => [
            'Content-Type: text/xml; charset=utf-8',
            'SOAPAction: "https://bingads.microsoft.com/Reporting/v13/GetReportRequestStatus"'
        ],
        CURLOPT_RETURNTRANSFER => true
    ]);

    $statusResponse = curl_exec($ch);
    curl_close($ch);

    $statusXmlResponse = simplexml_load_string($statusResponse);
    $statusXmlResponse->registerXPathNamespace('v13', 'https://bingads.microsoft.com/Reporting/v13');
    $reportStatus = (string)$statusXmlResponse->xpath('//v13:Status')[0];
} while ($reportStatus === 'Pending' || $reportStatus === 'InProgress');

// Process successful report
if ($reportStatus === 'Success') {
    $downloadUrl = (string)$statusXmlResponse->xpath('//v13:ReportDownloadUrl')[0];
    $reportContent = file_get_contents($downloadUrl);
    
    $rows = explode(PHP_EOL, trim($reportContent));
    if (isset($rows[1])) {
        [$account, $totalSpend] = str_getcsv($rows[1]);
        echo "Total Ad Spend for Account $account: $" . number_format($totalSpend, 2);
    }
} else {
    echo "Report failed with status: $reportStatus";
}
?>

Key Notes to Avoid Headaches

  • OAuth Token Management: Access tokens expire after about 1 hour. For production, implement a refresh token flow to automatically get new tokens when needed.
  • Date Ranges: Instead of PredefinedTime, you can use CustomDateRangeStart and CustomDateRangeEnd to specify exact dates (format: YYYY-MM-DD).
  • Rate Limits: Bing Ads has rate limits for API calls. Don’t poll for report status too frequently (5 seconds is safe, but adjust based on their docs).
  • Permissions: Ensure your Bing Ads application has the Reporting permission enabled, and the OAuth token is associated with a user who has access to the target account.
  • Debugging: Use the trace option in SoapClient or print cURL request/response bodies to troubleshoot errors. Bing Ads returns detailed error messages that will point you to issues like invalid tokens or missing permissions.

内容的提问来源于stack exchange,提问作者Pankaj K

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:45:19