PHP + FCM push notification

 <?php


$data = json_decode(file_get_contents("php://input"), true);

// === CONFIGURATION ===

$serviceAccountFile = '.../_service.json'; // Path to your downloaded service account JSON

$projectId = 'project_id';               // Replace with your Firebase project ID


// Database connection (Replace with your own DB configuration)

// $db = new mysqli('localhost', 'username', 'password', 'database');


// $fcmToken = $_GET['fcm_token'];


// if (!$fcmToken) {

    // exit("User FCM token not found.");

// }


// === CREATE JWT FOR OAUTH ===


$serviceAccount = json_decode(file_get_contents($serviceAccountFile), true);


$header = base64url_encode(json_encode([

    'alg' => 'RS256',

    'typ' => 'JWT'

]));


$now = time();

$payload = base64url_encode(json_encode([

    'iss' => $serviceAccount['client_email'],

    'scope' => 'https://www.googleapis.com/auth/firebase.messaging',

    'aud' => 'https://oauth2.googleapis.com/token',

    'iat' => $now,

    'exp' => $now + 3600,

]));


$signatureInput = "$header.$payload";


// Sign with private key

$privateKey = openssl_pkey_get_private($serviceAccount['private_key']);

openssl_sign($signatureInput, $signature, $privateKey, 'sha256WithRSAEncryption');

$jwt = "$signatureInput." . base64url_encode($signature);


// === EXCHANGE JWT FOR ACCESS TOKEN ===

$tokenRequest = [

    'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',

    'assertion' => $jwt

];


$ch = curl_init('https://oauth2.googleapis.com/token');

curl_setopt($ch, CURLOPT_POST, true);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($tokenRequest));

curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);


$response = curl_exec($ch);

curl_close($ch);


$tokenData = json_decode($response, true);

$accessToken = $tokenData['access_token'] ?? null;


if (!$accessToken) {

    exit("Failed to get access token: $response\n");

}


// === SEND FCM PUSH NOTIFICATION ===


if($data["is_promotional"] == 1){

$message = [

    'message' => [

        'topic' => "CNMM_PROMOTIONAL",

        'notification' => [

            'title' => $data["title"],

            'body' => $data["message"]

        ]

    ]

];

}else{

  $message = [

    'message' => [

        'token' => $data["fcmToken"],

        'notification' => [

            'title' => $data["title"],

            'body' => $data["message"]

        ]

    ]

];  

}


$ch = curl_init("https://fcm.googleapis.com/v1/projects/$projectId/messages:send");

curl_setopt($ch, CURLOPT_POST, true);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($message));

curl_setopt($ch, CURLOPT_HTTPHEADER, [

    'Authorization: Bearer ' . $accessToken,

    'Content-Type: application/json'

]);


$response = curl_exec($ch);

curl_close($ch);



// === BASE64URL HELPERS ===

function base64url_encode($data) {

    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');

}


Comments