批量应用程序到Facebook api中的用户通知

问题描述 投票:2回答:1

有没有办法批量发送App-to-User通知? 目前我使用php脚本使用POST请求逐个发送给/{recipient_userid}/notifications边缘,感觉我做错了。

php facebook facebook-graph-api
1个回答
1
投票

tl;博士

$userIds = ['100000000000000','100000000000001', '100000000000002']; // Users who will receive the notification.
$notificationMessage = 'Test message!'; // Notification message. Character limit: 180, truncate after 120.
$linkHref = 'posts/123'; // Path after Facebook Web Games URL that facebook's iframe will display on notification click.
$analyticsRef = 'new-posts'; // Group notifications for App Analytics.

var_dump(sendBatchRequests($userIds, $notificationMessage, $linkHref, $analyticsRef));

function sendBatchRequests($ids, $message, $href = '', $ref = null) {
    $APP_ACCESS_TOKEN = '123456789012345|AbCdEfGhIjKlMnOpQrStUvWxYz'; // How to create one: https://stackoverflow.com/a/48831913/1494454
    $FACEBOOK_BATCH_ELEMENT_LIMIT = 50; // Maximum amount of request grouped into a batch. Facebook's limit is 50: https://developers.facebook.com/docs/graph-api/making-multiple-requests#limits

    $results = [];
    $idChunks = array_chunk($ids, $FACEBOOK_BATCH_ELEMENT_LIMIT);
    foreach ($idChunks as $idChunk) {
        $batch = [];
        foreach ($idChunk as $id) {
            $batch[] = [
               'method' => 'POST',
               'relative_url' => "{$id}/notifications?template={$message}" . ($ref ? "&ref={$ref}" : ''),
            ];
        }
        $results[] = file_get_contents('https://graph.facebook.com/', false, stream_context_create([
            'http' => [
                'method'  => 'POST',
                'header'  => "Content-type: application/json; charset=UTF-8",
                'content' => json_encode([
                    'access_token' => $APP_ACCESS_TOKEN,
                    'batch' => $batch,
                ]),
            ],
        ]));
    }
    return $results;
}

说明

有一个example on GitHub如何做到这一点,但它真的很旧,所以我创造了一个现代的,最新的灵感来自它。 notification APIguide to do batch requests都有很好的文档记录,所以你只需要实现它就可以在vanilla PHP中完成。

sendBatchRequests函数将为$message中给出的每个用户发送带有$userIds文本的通知。它会将每个$FACEBOOK_BATCH_ELEMENT_LIMIT数量的请求分组,并每批激发一个HTTP请求。 API响应存储在$results中。单击通知会将用户重定向到Facebook游戏iframe内的应用程序的Facebook Web游戏URL。您可以使用$linkHref指定该URL之后的路径。 $ref用于分析目的。请参阅上面链接的文档中的更多内容

这只是一个例子。您仍然必须确保每个用户都有一个请求,并且脚本不会超时并检查请求是否成功。

© www.soinside.com 2019 - 2024. All rights reserved.