phpandroidfirebasepush-notification

Send push notification to Android device with PHP


I'm trying to figure out how to send push notification to Android devices with PHP.

I've looked it up on multiple sites and this is the last what I've tried:

function sendFCM($registrationIds, $notifTitle, $notifDesc, $notifChannel, $data) {

    $client = new Google_Client();
    $client->setAuthConfig('bla.json');
    $client->addScope('https://www.googleapis.com/auth/firebase.messaging');
    $client->refreshTokenWithAssertion();
    $token = $client->getAccessToken();
    $accessToken = $token['access_token'];

    $headers = array (
        'Authorization: Bearer ' . $accessToken,
        'Content-Type:application/json'
    );

    $notification = array
    (
        "title" => $notifTitle, 
        "body" => $notifDesc, 
        "icon" => "ic_logo_circle",
        "android_channel_id" => $notifChannel
    );

    $fields = array
    (
        'notification' => $notification, 
        'data' => $data, 
        'registration_ids' => $registrationIds
    );      

    $ch = curl_init();
    curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/v1/projects/projectname/messages:send' );
    curl_setopt( $ch,CURLOPT_POST, true );
    curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
    curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
    curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );

    $result = curl_exec($ch);
    print($result);

    curl_close($ch);
}

$notifData = array( 
    "title" => "this is the title",
    "msg" => "the desc",
    "image" => "whatever.jpg"
);

sendFCM($registrationIds, "Antwort auf Kommentar", "Cornholio hat dir geantwortet", "channel_reply_comment", $notifData);

$registrationIds contains array of multiple Android device tokens

{ "error": { "code": 400, "message": "Invalid JSON payload received. Unknown name "notification": Cannot find field.\nInvalid JSON payload received. Unknown name "data": Cannot find field.\nInvalid JSON payload received. Unknown name "registration_ids": Cannot find field.", "status": "INVALID_ARGUMENT", "details": [ { "@type": "type.googleapis.com/google.rpc.BadRequest", "fieldViolations": [ { "description": "Invalid JSON payload received. Unknown name "notification": Cannot find field." }, { "description": "Invalid JSON payload received. Unknown name "data": Cannot find field." }, { "description": "Invalid JSON payload received. Unknown name "registration_ids": Cannot find field." } ] } ] } }


Solution

  • The FCM v1 API doesn't expect a registration_ids field. You'll want to the tokens field instead.

    For this and more, keep the documentation on sending messages handy