从旧版 FCM API 迁移到 HTTP v1

问题描述 投票:0回答:2
public function fcm_command($token,$command){
    $path_to_fcm = 'https://fcm.googleapis.com/v1/projects/projects/messages:send';
    
    //Taglock Server Key
    $server_key = "";
    $headers = array(
        'Authorization:key=' .$server_key,
        'Content-Type:application/json'
        );
    $fields = array('to'=>$token,'data'=>array('command'=>$command));
    $payload = json_encode($fields);
    $curl_session = curl_init();
    curl_setopt($curl_session, CURLOPT_URL, $path_to_fcm);
    curl_setopt($curl_session, CURLOPT_POST, true);
    curl_setopt($curl_session, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl_session, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl_session, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
    curl_setopt($curl_session, CURLOPT_POSTFIELDS, $payload);
    $res = curl_exec($curl_session);
    curl_close($curl_session);
    return array('status'=>REST_Controller::HTTP_OK,'message'=> 'Command sent to device');
}

我正在使用旧的 $server_key 并且仅更新了

$path_to_fcm = 'https://fcm.googleapis.com/v1/projects/projects/messages:send';
,但没有收到通知。我需要生成新的服务器密钥还是需要旧的?

php push-notification firebase-cloud-messaging
2个回答

0
投票

v1 API 不再有效,您必须迁移到 HTTP v1 https://firebase.google.com/docs/cloud-messaging/migrate-v1

库 Google Api 客户端 https://github.com/googleapis/google-api-php-client/releases

从 Firebase“管理服务帐户”获取 JSON。

可以查看这个代码示例:

require_once '/google-api-php-client/vendor/autoload.php';

function notification($notifications){
$serviceAccountPath = 'service-account-file.json';

// Your Firebase project ID
$projectId = 'xxxxxx';

// Example message payload
$message = [
   'token' => 'deviceToken',
       'notification' => [
          'title' => $title,
           'body' => $msg,
        ],
    ];

  $accessToken = getAccessToken($serviceAccountPath);
  $response = sendMessage($accessToken, $projectId, $message);
}

function getAccessToken($serviceAccountPath) {
    $client = new Client();
    $client->setAuthConfig($serviceAccountPath);
    $client->addScope('https://www.googleapis.com/auth/firebase.messaging');
    $client->useApplicationDefaultCredentials();
    $token = $client->fetchAccessTokenWithAssertion();
    return $token['access_token'];
}

function sendMessage($accessToken, $projectId, $message) {
    $url = 'https://fcm.googleapis.com/v1/projects/' . $projectId . '/messages:send';
    $headers = [
        'Authorization: Bearer ' . $accessToken,
        'Content-Type: application/json',
    ];
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['message' => $message]));
    $response = curl_exec($ch);
    
    curl_close($ch);
    return $response;
}
© www.soinside.com 2019 - 2024. All rights reserved.