且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在后端通过onTokenRefresh处理Firebase Cloud Messaging

更新时间:2022-11-27 19:11:51

我们采用的方法是假设所有onTokenRefresh id是新的,并且将其他设备添加到服务器上的设备列表中.然后,无论何时发送消息,我们都使用返回的结果删除或替换不推荐使用的设备令牌.用PHP实现:

We are going with the approach where we assume all onTokenRefresh ids are new, additional devices that we add to the device list on the server. Then, whenever we send a message we use the returned result to delete or replace deprecated device tokens. Implementation in PHP:

// $devices is a list of the device ids to send to

// 1. send a message to a list of devices
$response = Firebase::request('POST', 'send', ['json' => $this->payloadFor($devices)]);

// 2. check the response to see if we need to make changes to the device list

// if it is a network error, no changes needed
if ($response->getStatusCode() != 200) {
    Log::info("FCM http error " . $response->getStatusCode());
    return;
}

$body = json_decode($response->getBody(), $asArray = true);

// do we need to dig deeper?
if ($body['failure'] == 0 && $body['canonical_ids'] == 0) return;

if (count($body['results']) != count($devices)) {
    Log::info("FCM error : device count not matching result count");
    return;
}

// we have errors that need processing, so step through the results list
foreach ($body['results'] as $key => $result) {

    if (isset($result['error'])) {
        switch ($result['error']) {
            case 'NotRegistered':
            case 'InvalidRegistration':
                $deletedRows = Device::where('token', $devices[$key])->delete();
                Log::info("FCM trimmed: $devices[$key]");
                break;

            default:
                Log::info("FCM error " . $result['error']);
                break;
        }
    }

    // we need to update some device tokens
    if (isset($result['registration_id'])) {
        Device::deprecate($devices[$key], $result['registration_id']);
        Log::info("FCM replaced: " . $devices[$key]);
    }
}