Linking responses to requests with Facebook Batch Requests

纵饮孤独 提交于 2019-12-10 15:59:15

问题


I'm using Facebook's Batch Requests to post to multiple feeds and I need to link the correct response to every request in the batch. Since I found no definitive info on the documentation, do the members of the returned array appear in the same order as the requests?

In other words, if I get an error in the third member of the returned array, does that positively mean that the error refers to the third request I sent in the batch?

I can use the id for succesful requests, but error messages seem general and do not bring any data linked to the request that generated them (unless I'm missing something).


回答1:


Yes, that's correct.

My strategy is that I create a tracking array as I load up my batch requests. This array correlates the key for my associative array to the numerical order I posted the batches. When I loop over the results, I use a counter to step through the tracking array and pull out the proper associative array index. Then I use that to update the associative array with the results from that step of the batch operation.

It would be nice if batching supported the 'name' parameter and that parameter got returned with each response. But that only appears to work if you're using the name to create batch dependencies: https://developers.facebook.com/docs/reference/api/batch/

Loading up the batches:

foreach ($campaigns as $title => $campaign) {
    if (count($batch) == 20) {
        $batches[] = $batch;
        $batch = array();
    }

    $titles[] = $title;  #TRACKING array;
    $body = http_build_query($campaign);
    $body = urldecode($body);

    $batch[] = array(
        'method' => 'POST',
        'relative_url' => "/act_{$act}/adcampaigns",
        'body' => $body
    );
}

Processing the batches:

if ($batch) {
    $batches[] = $batch;
    $counter = 0;

    foreach ($batches as $batch) {
        $params = array(
          'access_token' => $access_token,
          'batch' => json_encode($batch)
        );

        $responses = $facebook->api('/', 'POST', $params);

        foreach ($responses as $response) {
            $response = json_decode($response['body'], 1);
            $campaign_id = $response['id'];
            $title = $titles[$counter];  #RETRIEVING THE INDEX FROM THE TRACKING ARRAY
            $campaigns[$title]['campaign_id'] = $campaign_id;
            $counter++; #INCREMENTING THE COUNTER
        }
    }
}


来源:https://stackoverflow.com/questions/7428923/linking-responses-to-requests-with-facebook-batch-requests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!